Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
Repo cache: repeat git clones in Spaces start from a verified mirror on this machine (#6128)
ddupont92e49bcab6cb
diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex 8262f808d8..e5f3b4676d 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -39,7 +39,7 @@ export const METHODS = ["spaces.chooseFiles", "spaces.droppedFiles", "spaces.sendFiles","host.setUp", "host.joinWithCode", "host.action", "host.limits", "host.openSettings","settings.get", "settings.choose", "settings.update",- "runtimes.check", "runtimes.browse",+ "runtimes.check", "runtimes.browse", "repoCache.get", "repoCache.set", "repoCache.clear","keyvault.get", "keyvault.lock", "keyvault.unlock","keyvault.unlockVault", "keyvault.setup", "keyvault.setDisabled","keyvault.approve", "keyvault.deny", "keyvault.revokeGrant",diff --git a/apps/cua-spaces-desktop/src/bridge/settings.ts b/apps/cua-spaces-desktop/src/bridge/settings.tsindex 15cfae3571..0d263a0c5a 100644--- a/apps/cua-spaces-desktop/src/bridge/settings.ts+++ b/apps/cua-spaces-desktop/src/bridge/settings.ts@@ -9,7 +9,7 @@// runtimes, launch at login, usage data, the update channel, the// experiments, Welcome's "Show again", the coding agents (`model.agents`)// and the Keyvault's switches (`model.keyvault`).-import type { AppLoginItemStatus, AppSettingsInput, AppTeamInput, AppTelemetryInput } from "../native/generated/index";+import type { AppLoginItemStatus, AppSettingsInput, AppTeamInput, AppTelemetryInput, RepoCacheStatus } from "../native/generated/index";import type { AppModel } from "../model/app-model";import { words } from "../model/errors";import { bounded } from "../model/time";@@ -21,6 +21,23 @@ import { hostParts, type HostParts } from "./host-parts";import { encode } from "./value";import { cliSetting } from "./cli";+/** The repo cache as the page reads it (`RepoCacheView`); the SDK's numbers are 64-bit. */+function repoCacheView(s: RepoCacheStatus | null) {+ if (!s) throw Failure.unsupported("The repo cache is not available in this build");+ return {+ enabled: s.enabled,+ repos: s.repos,+ bytes: Number(s.bytes),+ capBytes: Number(s.capBytes),+ sizeSetting: s.sizeSetting,+ summary: s.summary,+ week: s.week,+ hits: s.hits,+ misses: s.misses,+ secondsSaved: Number(s.secondsSaved),+ };+}+function telemetryInput(model: AppModel): AppTelemetryInput | undefined {try {return model.telemetry?.status();@@ -299,6 +316,26 @@ export function settingsMethods(ctx: BridgeContext): Handlers {if (!ctx.ui.chooseProgram) throw Failure.unsupported("This build has no file picker");return { path: (await ctx.ui.chooseProgram(caller.window)) ?? null };},+ // Settings, General: the repo cache (the daemon's; the page shows its words).+ "repoCache.get": async () => repoCacheView(await model.backend.repoCacheStatus()),+ "repoCache.set": async (args) => {+ const change: { enabled?: boolean; sizeGb?: number | null } = {};+ if (args.enabled !== undefined) {+ if (typeof args.enabled !== "boolean") throw Failure.badArgs("enabled: true or false");+ change.enabled = args.enabled;+ }+ if (args.sizeGb !== undefined) {+ const g = args.sizeGb;+ if (g !== null && (typeof g !== "number" || !Number.isFinite(g) || g < 0 || g > 100_000)) throw Failure.badArgs("sizeGb: a number of GB, 0 or more, or null for automatic");+ change.sizeGb = g;+ }+ try {+ return repoCacheView(await model.backend.setRepoCache(change));+ } catch (error) {+ throw Failure.failed(words(error));+ }+ },+ "repoCache.clear": async () => repoCacheView(await model.backend.clearRepoCache()),// The page's tips (`AppSettings.tips`), saved as given."settings.update": (args) => {save(settingsUpdate(args));diff --git a/apps/cua-spaces-desktop/src/model/backend.ts b/apps/cua-spaces-desktop/src/model/backend.tsindex ec7ddc2836..fec9aadda5 100644--- a/apps/cua-spaces-desktop/src/model/backend.ts+++ b/apps/cua-spaces-desktop/src/model/backend.ts@@ -36,6 +36,7 @@ import type {SpaceLike,SpacePresenceLike,PresenceIdentity,+ RepoCacheStatus,ResourcesSnapshot,TeleportLike,} from "../native/generated/index";@@ -169,6 +170,12 @@ export interface SpacesBackend {runtimeCheckPath(kind: string, path: string): Promise<AppRuntimePathCheck>;/** Writes a runtime setting (`runtime.container`, `runtime.vm_path`), or unsets it (null). */setRuntimeSetting(key: string, value: string | null): Promise<void>;+ /** The repo cache: on or off, what it holds and saved (`repo_cache_status`); null when unknown. */+ repoCacheStatus(): Promise<RepoCacheStatus | null>;+ /** Turns the repo cache on or off and sets its size in GB (null: automatic); a missing field keeps its value. */+ setRepoCache(change: { enabled?: boolean; sizeGb?: number | null }): Promise<RepoCacheStatus | null>;+ /** Deletes every repository the repo cache holds. */+ clearRepoCache(): Promise<RepoCacheStatus | null>;localStorage(): Promise<LocalStorage | null>;/** A Cua account is signed in (or client credentials are set). */loggedIn(): Promise<boolean>;@@ -600,6 +607,28 @@ export class LiveSpacesBackend implements SpacesBackend {else this.native.configSet(key, value);}+ async repoCacheStatus(): Promise<RepoCacheStatus | null> {+ try {+ return this.native.repoCacheStatus();+ } catch {+ return null;+ }+ }++ async setRepoCache(change: { enabled?: boolean; sizeGb?: number | null }): Promise<RepoCacheStatus | null> {+ if (change.enabled !== undefined) this.native.configSet("cache.repos", change.enabled ? "on" : "off");+ if (change.sizeGb !== undefined) this.native.configSet("cache.repos_size_gb", change.sizeGb === null ? "auto" : String(change.sizeGb));+ return this.repoCacheStatus();+ }++ async clearRepoCache(): Promise<RepoCacheStatus | null> {+ try {+ return this.native.repoCacheClear();+ } catch {+ return null;+ }+ }+async localStorage(): Promise<LocalStorage | null> {return bounded(PROBE_SECONDS, () => this.cua.local().storage());}diff --git a/apps/cua-spaces-desktop/src/model/pending.ts b/apps/cua-spaces-desktop/src/model/pending.tsindex 462ba37e59..1ef4c6763d 100644--- a/apps/cua-spaces-desktop/src/model/pending.ts+++ b/apps/cua-spaces-desktop/src/model/pending.ts@@ -117,6 +117,9 @@ export class PendingSpacesBackend implements SpacesBackend {runtimeKinds = async () => (await this.b()).runtimeKinds();runtimeCheckPath = async (kind: string, path: string) => (await this.b()).runtimeCheckPath(kind, path);setRuntimeSetting = async (key: string, value: string | null) => (await this.b()).setRuntimeSetting(key, value);+ repoCacheStatus = async () => (await this.b()).repoCacheStatus();+ setRepoCache = async (change: { enabled?: boolean; sizeGb?: number | null }) => (await this.b()).setRepoCache(change);+ clearRepoCache = async () => (await this.b()).clearRepoCache();localStorage = async () => (await this.b()).localStorage();loggedIn = async () => (await this.b()).loggedIn();runningMacosVms = async () => (await this.b()).runningMacosVms();diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.tsindex de49af636c..e9134c3796 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts@@ -824,6 +824,16 @@ const DEFINITIONS = {ret: FfiType.RustBuffer,hasRustCallStatus: true,},+ "uniffi_cua_sdk_fn_func_repo_cache_clear": {+ args: [],+ ret: FfiType.RustBuffer,+ hasRustCallStatus: true,+ },+ "uniffi_cua_sdk_fn_func_repo_cache_status": {+ args: [],+ ret: FfiType.RustBuffer,+ hasRustCallStatus: true,+ },"uniffi_cua_sdk_fn_func_resolve_image": {args: [FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer],ret: FfiType.RustBuffer,@@ -3319,6 +3329,16 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_sdk_checksum_func_repo_cache_clear": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },+ "uniffi_cua_sdk_checksum_func_repo_cache_status": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_checksum_func_resolve_image": {args: [],ret: FfiType.UInt16,@@ -5994,6 +6014,8 @@ interface NativeModuleInterface {uniffi_cua_sdk_fn_func_presence_now_ms(uniffi_out_err: UniffiRustCallStatus): number;uniffi_cua_sdk_fn_func_presence_text_color(background: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_func_qualify_sandbox_ref(name: Uint8Array, local: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;+ uniffi_cua_sdk_fn_func_repo_cache_clear(uniffi_out_err: UniffiRustCallStatus): Uint8Array;+ uniffi_cua_sdk_fn_func_repo_cache_status(uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_func_resolve_image(reference: Uint8Array, backend: Uint8Array, arch: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_func_resolve_image_with_secret(reference: Uint8Array, backend: Uint8Array, arch: Uint8Array, secret: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_func_sandbox_locations(uniffi_out_err: UniffiRustCallStatus): Uint8Array;@@ -6493,6 +6515,8 @@ interface NativeModuleInterface {uniffi_cua_sdk_checksum_func_presence_now_ms(): number;uniffi_cua_sdk_checksum_func_presence_text_color(): number;uniffi_cua_sdk_checksum_func_qualify_sandbox_ref(): number;+ uniffi_cua_sdk_checksum_func_repo_cache_clear(): number;+ uniffi_cua_sdk_checksum_func_repo_cache_status(): number;uniffi_cua_sdk_checksum_func_resolve_image(): number;uniffi_cua_sdk_checksum_func_resolve_image_with_secret(): number;uniffi_cua_sdk_checksum_func_sandbox_locations(): number;diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.tsindex aebdaf6fdd..c5dfdf1958 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts@@ -689,6 +689,48 @@ export function qualifySandboxRef(name: string, local: boolean | undefined = und));}+/**+ * Deletes every repository the repo cache holds (they are copied again the+ * next time a Space clones them). Returns the cache after.+ */+export function repoCacheClear(): RepoCacheStatus /*throws*/ {+ return ((__rb: Uint8Array) => {+ try {+ return FfiConverterTypeRepoCacheStatus.lift(__rb);+ } finally {+ nativeModule().rustbuffer_free(__rb);+ }+ })(uniffiCaller.rustCallWithError(+ /*liftError:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError),+ /*caller:*/ (callStatus) => {+ return nativeModule().uniffi_cua_sdk_fn_func_repo_cache_clear(+ callStatus);+ },+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ ));+ }++/**+ * The repo cache now: on or off, how much it holds of its cap, and what+ * the last week saved.+ */+export function repoCacheStatus(): RepoCacheStatus /*throws*/ {+ return ((__rb: Uint8Array) => {+ try {+ return FfiConverterTypeRepoCacheStatus.lift(__rb);+ } finally {+ nativeModule().rustbuffer_free(__rb);+ }+ })(uniffiCaller.rustCallWithError(+ /*liftError:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError),+ /*caller:*/ (callStatus) => {+ return nativeModule().uniffi_cua_sdk_fn_func_repo_cache_status(+ callStatus);+ },+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ ));+ }+/*** Resolves `reference` for `backend` (`auto`, `local`, `provider`,* `container`/`docker`/`gvisor`, `vm`/`qemu`/`kubevirt`, `lume`)@@ -15820,6 +15862,116 @@ const FfiConverterTypeReadinessProbe = (() => {return new FFIConverter();})();+/**+ * What the repo cache holds and what it saved, in plain words for+ * Settings (`cache.repos` and `cache.repos_size_gb` are its settings,+ * changed with [`config_set`]).+ */+export type RepoCacheStatus = {+ /**+ * The cache is on (`cache.repos`).+ */+ enabled: boolean,+ /**+ * Repositories held.+ */+ repos: number,+ /**+ * What they take on disk.+ */+ bytes: bigint,+ /**+ * The size cap in force.+ */+ capBytes: bigint,+ /**+ * The size setting: `auto`, or the number of GB.+ */+ sizeSetting: string,+ /**+ * `Repos: 3, 1.2 GB of 5 GB`.+ */+ summary: string,+ /**+ * `Last week: 80% of clones came from the cache, about 2 minutes saved`.+ */+ week: string,+ /**+ * Clones served from the cache in the last week.+ */+ hits: number,+ /**+ * Clones that downloaded in the last week.+ */+ misses: number,+ /**+ * Seconds the hits saved.+ */+ secondsSaved: bigint+}++/**+ * Generated factory for {@link RepoCacheStatus} record objects.+ */+export const RepoCacheStatus = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<RepoCacheStatus, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<RepoCacheStatus>,+ });+})();++const FfiConverterTypeRepoCacheStatus = (() => {+ type TypeName = RepoCacheStatus;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ enabled: FfiConverterBool.read(from),+ repos: FfiConverterUInt32.read(from),+ bytes: FfiConverterUInt64.read(from),+ capBytes: FfiConverterUInt64.read(from),+ sizeSetting: FfiConverterString.read(from),+ summary: FfiConverterString.read(from),+ week: FfiConverterString.read(from),+ hits: FfiConverterUInt32.read(from),+ misses: FfiConverterUInt32.read(from),+ secondsSaved: FfiConverterUInt64.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterBool.write(value.enabled, into);+ FfiConverterUInt32.write(value.repos, into);+ FfiConverterUInt64.write(value.bytes, into);+ FfiConverterUInt64.write(value.capBytes, into);+ FfiConverterString.write(value.sizeSetting, into);+ FfiConverterString.write(value.summary, into);+ FfiConverterString.write(value.week, into);+ FfiConverterUInt32.write(value.hits, into);+ FfiConverterUInt32.write(value.misses, into);+ FfiConverterUInt64.write(value.secondsSaved, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterBool.allocationSize(value.enabled) ++ FfiConverterUInt32.allocationSize(value.repos) ++ FfiConverterUInt64.allocationSize(value.bytes) ++ FfiConverterUInt64.allocationSize(value.capBytes) ++ FfiConverterString.allocationSize(value.sizeSetting) ++ FfiConverterString.allocationSize(value.summary) ++ FfiConverterString.allocationSize(value.week) ++ FfiConverterUInt32.allocationSize(value.hits) ++ FfiConverterUInt32.allocationSize(value.misses) ++ FfiConverterUInt64.allocationSize(value.secondsSaved);++ }+ };+ return new FFIConverter();+})();+/*** A reference resolved for a backend.*/@@ -46587,6 +46739,12 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_func_qualify_sandbox_ref() !== 59566) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_func_qualify_sandbox_ref");}+ if (nativeModule().uniffi_cua_sdk_checksum_func_repo_cache_clear() !== 39088) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_func_repo_cache_clear");+ }+ if (nativeModule().uniffi_cua_sdk_checksum_func_repo_cache_status() !== 20147) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_func_repo_cache_status");+ }if (nativeModule().uniffi_cua_sdk_checksum_func_resolve_image() !== 56346) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_func_resolve_image");}@@ -48198,6 +48356,7 @@ export default Object.freeze({FfiConverterTypeRelayDevice,FfiConverterTypeRelayMachine,FfiConverterTypeReplayMode,+ FfiConverterTypeRepoCacheStatus,FfiConverterTypeResolvedImage,FfiConverterTypeResourcesEvent,FfiConverterTypeResourcesListener,diff --git a/apps/cua-spaces-desktop/test/bridge-native.test.ts b/apps/cua-spaces-desktop/test/bridge-native.test.tsindex 8af3900f9c..ec83fa7e24 100644--- a/apps/cua-spaces-desktop/test/bridge-native.test.ts+++ b/apps/cua-spaces-desktop/test/bridge-native.test.ts@@ -194,7 +194,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {expect(problems).toEqual([]);// Every ported method has its case (or is checked below).// (Teleport and the Keyvault: vault-native.test.ts; This machine, Devices, Settings and the rest: host-bridge.test.ts; the relay allowance: relay-usage.test.ts; resource numbers: resources.test.ts; presence: presence-bridge.test.ts; the Machines page's rename, remove and health checks: machines-view.test.ts; the Windows runtime fix: below.)- const elsewhere = new Set(["session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", "runtimes.check", "runtimes.browse", ...THREAD_OPERATIONS, ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);+ const elsewhere = new Set(["session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", "runtimes.check", "runtimes.browse", "repoCache.get", "repoCache.set", "repoCache.clear", ...THREAD_OPERATIONS, ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);const ported = bridge.registry.methods.filter((m) => !NOT_YET.includes(m) && !elsewhere.has(m));expect(ported.filter((m) => !cases.some(([c]) => c === m))).toEqual([]);});@@ -611,7 +611,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {"spaces.leave": { ids: ["local:nowhere"] },};// This machine, Devices, Settings and the rest: host-bridge.test.ts reads them with their arguments (the Machines page's rename and remove: machines-view.test.ts).- const skip = new Set<OpName>(["spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", "runtimes.check", "runtimes.browse", ...(THREAD_OPERATIONS as readonly string[] as OpName[]), ...VAULT_OPS, ...(HOST_OPS as OpName[])]);+ const skip = new Set<OpName>(["spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", "relay.usage", "sharing.removals", "sharing.ackRemovals", "resources.get", "machines.rename", "machines.remove", "machines.checkHealth", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", "cli.install", "runtimes.check", "runtimes.browse", "repoCache.get", "repoCache.set", "repoCache.clear", ...(THREAD_OPERATIONS as readonly string[] as OpName[]), ...VAULT_OPS, ...(HOST_OPS as OpName[])]);// (The thread: thread.test.ts.)const problems: string[] = [];const checked: string[] = [];diff --git a/apps/cua-spaces-desktop/test/fixtures.ts b/apps/cua-spaces-desktop/test/fixtures.tsindex 427ba2b8a7..59ea41a0a0 100644--- a/apps/cua-spaces-desktop/test/fixtures.ts+++ b/apps/cua-spaces-desktop/test/fixtures.ts@@ -215,6 +215,35 @@ export class FixtureSpacesBackend implements SpacesBackend {if (value === null) this.runtimeSettings.delete(key);else this.runtimeSettings.set(key, value);}+ repoCache = { enabled: true, sizeSetting: "auto", repos: 3, bytes: 1_288_490_189n };+ private repoCacheOf() {+ const cap = this.repoCache.sizeSetting === "auto" ? 5 : Number(this.repoCache.sizeSetting);+ return {+ enabled: this.repoCache.enabled,+ repos: this.repoCache.repos,+ bytes: this.repoCache.bytes,+ capBytes: BigInt(cap) * 1024n ** 3n,+ sizeSetting: this.repoCache.sizeSetting,+ summary: `Repos: ${this.repoCache.repos}, 1.2 GB of ${cap} GB`,+ week: "Last week: 80% of clones came from the cache, about 2 minutes saved",+ hits: 8,+ misses: 2,+ secondsSaved: 125n,+ };+ }+ async repoCacheStatus() {+ return this.repoCacheOf();+ }+ async setRepoCache(change: { enabled?: boolean; sizeGb?: number | null }) {+ if (change.enabled !== undefined) this.repoCache.enabled = change.enabled;+ if (change.sizeGb !== undefined) this.repoCache.sizeSetting = change.sizeGb === null ? "auto" : String(change.sizeGb);+ return this.repoCacheOf();+ }+ async clearRepoCache() {+ this.repoCache.repos = 0;+ this.repoCache.bytes = 0n;+ return this.repoCacheOf();+ }async localStorage() {return null;}diff --git a/apps/cua-spaces-desktop/test/host-bridge.test.ts b/apps/cua-spaces-desktop/test/host-bridge.test.tsindex 856df758bd..d78351806f 100644--- a/apps/cua-spaces-desktop/test/host-bridge.test.ts+++ b/apps/cua-spaces-desktop/test/host-bridge.test.ts@@ -630,6 +630,21 @@ describe.skipIf(!built)("This machine, Devices and Settings on the app core", ()expect(await code("runtimes.browse", { kind: "container" })).toBe("unsupported");});+ it("reads, changes and clears the repo cache, and refuses what is not a number of GB", async () => {+ const view = (await call("repoCache.get")) as { enabled: boolean; repos: number; bytes: number; capBytes: number; sizeSetting: string; summary: string; week: string };+ expect(view).toMatchObject({ enabled: true, repos: 3, sizeSetting: "auto", summary: "Repos: 3, 1.2 GB of 5 GB" });+ // The SDK's 64-bit sizes reach the page as numbers.+ expect(typeof view.bytes).toBe("number");+ expect(view.capBytes).toBe(5 * 1024 ** 3);+ expect(await call("repoCache.set", { enabled: false })).toMatchObject({ enabled: false, sizeSetting: "auto" });+ expect(await call("repoCache.set", { enabled: true, sizeGb: 2 })).toMatchObject({ enabled: true, sizeSetting: "2", summary: "Repos: 3, 1.2 GB of 2 GB" });+ expect(await call("repoCache.set", { sizeGb: null })).toMatchObject({ sizeSetting: "auto" });+ expect(await code("repoCache.set", { sizeGb: -1 })).toBe("bad_args");+ expect(await code("repoCache.set", { sizeGb: "lots" })).toBe("bad_args");+ expect(await code("repoCache.set", { enabled: "yes" })).toBe("bad_args");+ expect(await call("repoCache.clear")).toMatchObject({ repos: 0, bytes: 0 });+ });+it("lists the coding agents under AI agents, and a row's button sets one up", async () => {const s = (await call("settings.get")) as { page: { sections: { rows: { id: string }[] }[] } };expect(s.page.sections.flatMap((x) => x.rows.map((r) => r.id))).toEqual(expect.arrayContaining(["agent:claude-code", "agent:codex"]));diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swiftindex 73ed37bb67..a725e9557a 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift@@ -642,6 +642,11 @@ public final class PendingSpacesBackend: SpacesBackend, AgentsToolRunning, Cloudpublic func runtimeCheckPath(kind: String, path: String) async throws -> AppRuntimePathCheck {try await b().runtimeCheckPath(kind: kind, path: path)}+ public func repoCacheStatus() async -> RepoCacheState? { await b().repoCacheStatus() }+ public func setRepoCache(enabled: Bool?, size: String?) async throws -> RepoCacheState? {+ try await b().setRepoCache(enabled: enabled, size: size)+ }+ public func clearRepoCache() async throws -> RepoCacheState? { try await b().clearRepoCache() }public func setRuntimeSetting(key: String, value: String?) async throws {try await b().setRuntimeSetting(key: key, value: value)}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swiftindex 16c44ad16b..8247494b3a 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift@@ -11,6 +11,31 @@ import Foundation/// The platform side of Spaces: the cua SDK calls the app makes. Every/// decision about what they mean (names, status, grouping, what is allowed)/// is the app core's; this only moves data.+/// What the repo cache holds and saved, in the plain words Settings shows+/// (the SDK's `repo_cache_status`; never a repository name).+public struct RepoCacheState: Equatable, Sendable {+ public var enabled: Bool+ public var repos: UInt32+ public var bytes: UInt64+ public var capBytes: UInt64+ /// `auto`, or the number of GB.+ public var sizeSetting: String+ /// `Repos: 3, 1.2 GB of 5 GB`.+ public var summary: String+ /// `Last week: 80% of clones came from the cache, about 2 minutes saved`.+ public var week: String+ public var hits: UInt32+ public var misses: UInt32+ public var secondsSaved: UInt64++ public init(enabled: Bool, repos: UInt32, bytes: UInt64, capBytes: UInt64, sizeSetting: String,+ summary: String, week: String, hits: UInt32, misses: UInt32, secondsSaved: UInt64) {+ self.enabled = enabled; self.repos = repos; self.bytes = bytes; self.capBytes = capBytes+ self.sizeSetting = sizeSetting; self.summary = summary; self.week = week+ self.hits = hits; self.misses = misses; self.secondsSaved = secondsSaved+ }+}+public protocol SpacesBackend: AnyObject, Sendable {/// The registry, one row per Space, with a bounded reachability probe.func rows() async throws -> [AppSpaceRow]@@ -96,6 +121,14 @@ public protocol SpacesBackend: AnyObject, Sendable {/// Writes a runtime setting (`runtime.container`, `runtime.vm_path`), or/// unsets it (`nil`).func setRuntimeSetting(key: String, value: String?) async throws+ /// The repo cache (Settings, General): on or off, what it holds and what+ /// the last week saved; `nil` when this backend has none.+ func repoCacheStatus() async -> RepoCacheState?+ /// Turns the repo cache on or off (`cache.repos`) and sets its size+ /// (`cache.repos_size_gb`: `auto` or a number of GB); `nil` keeps a value.+ func setRepoCache(enabled: Bool?, size: String?) async throws -> RepoCacheState?+ /// Deletes every repository the repo cache holds.+ func clearRepoCache() async throws -> RepoCacheState?/// Free space where local Spaces are written and which images are/// pulled (`local().storage()`), when known.func localStorage() async -> LocalStorage?@@ -284,6 +317,9 @@ public extension SpacesBackend {throw FixtureError(message: "Runtimes can't be checked here")}func setRuntimeSetting(key: String, value: String?) async throws {}+ func repoCacheStatus() async -> RepoCacheState? { nil }+ func setRepoCache(enabled: Bool?, size: String?) async throws -> RepoCacheState? { nil }+ func clearRepoCache() async throws -> RepoCacheState? { nil }}/// The wizard's GPU choices from the SDK's `gpu_support`: the first option@@ -623,6 +659,26 @@ public final class LiveSpacesBackend: SpacesBackend, @unchecked Sendable {if let value { _ = try configSet(key: key, value: value) } else { _ = try configUnset(key: key) }}+ static func repoCache(_ s: RepoCacheStatus) -> RepoCacheState {+ RepoCacheState(enabled: s.enabled, repos: s.repos, bytes: s.bytes, capBytes: s.capBytes,+ sizeSetting: s.sizeSetting, summary: s.summary, week: s.week,+ hits: s.hits, misses: s.misses, secondsSaved: s.secondsSaved)+ }++ public func repoCacheStatus() async -> RepoCacheState? {+ (try? CuaSDK.repoCacheStatus()).map(Self.repoCache)+ }++ public func setRepoCache(enabled: Bool?, size: String?) async throws -> RepoCacheState? {+ if let enabled { _ = try configSet(key: "cache.repos", value: enabled ? "on" : "off") }+ if let size { _ = try configSet(key: "cache.repos_size_gb", value: size) }+ return await repoCacheStatus()+ }++ public func clearRepoCache() async throws -> RepoCacheState? {+ Self.repoCache(try CuaSDK.repoCacheClear())+ }+/// The SDK's kind as the app core's Settings input takes it.static func runtimeKind(_ k: RuntimeKindState) -> AppRuntimeKindInput {AppRuntimeKindInput(@@ -1309,6 +1365,34 @@ public final class FixtureSpacesBackend: SpacesBackend, @unchecked Sendable {public func setRuntimeSetting(key: String, value: String?) async throws {await MainActor.run { fixtureRuntimeSettings[key] = value }}+ /// The fixture Mac's repo cache.+ public var fixtureRepoCache = RepoCacheState(+ enabled: true, repos: 3, bytes: 1_288_490_189, capBytes: 5 << 30, sizeSetting: "auto",+ summary: "Repos: 3, 1.2 GB of 5 GB",+ week: "Last week: 80% of clones came from the cache, about 2 minutes saved",+ hits: 8, misses: 2, secondsSaved: 125)+ public func repoCacheStatus() async -> RepoCacheState? { await MainActor.run { fixtureRepoCache } }+ public func setRepoCache(enabled: Bool?, size: String?) async throws -> RepoCacheState? {+ await MainActor.run {+ if let enabled { fixtureRepoCache.enabled = enabled }+ if let size {+ fixtureRepoCache.sizeSetting = size+ let gb = size == "auto" ? 5.0 : (Double(size) ?? 5.0)+ fixtureRepoCache.capBytes = UInt64(gb * 1024 * 1024 * 1024)+ fixtureRepoCache.summary = "Repos: \(fixtureRepoCache.repos), 1.2 GB of \(size == "auto" ? "5" : size) GB"+ }+ return fixtureRepoCache+ }+ }+ public func clearRepoCache() async throws -> RepoCacheState? {+ await MainActor.run {+ fixtureRepoCache.repos = 0+ fixtureRepoCache.bytes = 0+ fixtureRepoCache.summary = "Repos: 0, 0 MB of 5 GB"+ fixtureRepoCache.week = "No clones yet this week"+ return fixtureRepoCache+ }+ }func fixtureCheck(kind: String, path: String) -> AppRuntimePathCheck {let known = (fixtureInstalled[kind] ?? []).first { $0.path == path }return AppRuntimePathCheck(path: path, exists: known != nil, executable: known != nil, tool: known?.tool,diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+RepoCache.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+RepoCache.swiftnew file mode 100644index 0000000000..48398e4522--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+RepoCache.swift@@ -0,0 +1,52 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Foundation++/// Settings, General's "Repo and dependency cache": `repoCache.get` (on or+/// off, what it holds and what the last week saved, in the host's words),+/// `repoCache.set` (the switch and the size in GB, `null` for automatic) and+/// `repoCache.clear`. The cache itself belongs to the Cua daemon.+extension WebUIBridge {+ func repoCache(_ method: String, _ args: [String: Any]) async throws -> Any {+ let state: RepoCacheState?+ do {+ switch method {+ case "repoCache.get":+ state = await model.backend.repoCacheStatus()+ case "repoCache.clear":+ state = try await model.backend.clearRepoCache()+ default:+ var enabled: Bool?+ if let v = args["enabled"], !(v is NSNull) {+ guard let b = v as? Bool, !(v is NSNumber) || CFGetTypeID(v as CFTypeRef) == CFBooleanGetTypeID() else {+ throw Failure.badArgs("enabled: true or false")+ }+ enabled = b+ }+ var size: String?+ if let v = args["sizeGb"] {+ if v is NSNull {+ size = "auto"+ } else {+ guard let n = (v as? NSNumber)?.doubleValue, n.isFinite, n >= 0, n <= 100_000 else {+ throw Failure.badArgs("sizeGb: a number of GB, 0 or more, or null for automatic")+ }+ size = n == n.rounded() ? String(UInt64(n)) : String(n)+ }+ }+ state = try await model.backend.setRepoCache(enabled: enabled, size: size)+ }+ } catch let failure as Failure {+ throw failure+ } catch {+ throw Failure(code: "failed", message: LiveSpacesBackend.words(error))+ }+ guard let s = state else { throw Failure.unsupported("The repo cache is not available in this build") }+ return [+ "enabled": s.enabled, "repos": Int(s.repos), "bytes": s.bytes, "capBytes": s.capBytes,+ "sizeSetting": s.sizeSetting, "summary": s.summary, "week": s.week,+ "hits": Int(s.hits), "misses": Int(s.misses), "secondsSaved": s.secondsSaved,+ ] as [String: Any]+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex 56722979c1..f9a3a5762a 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -105,7 +105,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"host.setUp", "host.joinWithCode", "host.action", "host.limits", "host.openSettings","settings.get", "settings.choose", "settings.update",// Settings, Advanced's runtime rows (WebUIBridge+Runtimes.swift).- "runtimes.check", "runtimes.browse",+ "runtimes.check", "runtimes.browse", "repoCache.get", "repoCache.set", "repoCache.clear","keyvault.get", "keyvault.lock", "keyvault.unlock","keyvault.unlockVault", "keyvault.setup", "keyvault.setDisabled","keyvault.approve", "keyvault.deny", "keyvault.revokeGrant",@@ -372,6 +372,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {return settings()case "runtimes.check", "runtimes.browse":return try await runtimes(method, args)+ case "repoCache.get", "repoCache.set", "repoCache.clear":+ return try await repoCache(method, args)case "settings.choose":let row = try string(args, "row")// An empty option only for a runtime path ("Reset to detected").diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swiftindex b4fea65950..9c4f0657f6 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift@@ -129,6 +129,12 @@ struct BridgeContractTests {}func cloudTool(_ tool: String, _ args: [String: Any]) async throws -> Any { try await inner.cloudTool(tool, args) }+ func repoCacheStatus() async -> RepoCacheState? { await inner.repoCacheStatus() }+ func setRepoCache(enabled: Bool?, size: String?) async throws -> RepoCacheState? {+ try await inner.setRepoCache(enabled: enabled, size: size)+ }+ func clearRepoCache() async throws -> RepoCacheState? { try await inner.clearRepoCache() }+func rows() async throws -> [AppSpaceRow] { try await inner.rows() }func create(_ args: AppCreateSpaceArgs, createId: String,progress: @escaping @Sendable (SpaceCreateProgress) -> Void) async throws -> String {@@ -277,6 +283,7 @@ struct BridgeContractTests {("spaces.sendFiles", ["spaceId": space, "paths": ["/tmp/cua-contract-notes.txt"]]),("settings.get", [:]), ("settings.choose", ["row": "telemetry", "option": "off"]),("runtimes.check", ["kind": "container", "path": "/usr/local/bin/docker"]), ("runtimes.browse", ["kind": "container"]),+ ("repoCache.get", [:]), ("repoCache.set", ["enabled": true, "sizeGb": 2]), ("repoCache.clear", [:]),("settings.update", ["tips": ["off": false, "done": ["try-agent"]]]),("keyvault.get", [:]),("keyvault.lock", ["ids": ["kv-1"]]),diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swiftindex 8a8a445193..8be4dbb18a 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift@@ -441,7 +441,7 @@ struct WebUIHostTests {for m in ["spaces.add", "clouds.status", "teleport.catalog", "teleport.run", "sharing.share", "volume.overview","agents.setupDriver", "about.set", "update.get", "update.install", "loginItem.set", "devices.approve", "storage.run","notifications.list", "telemetry.track", "telemetry.linkNotice", "telemetry.acknowledgeLinkNotice", "spaces.windows", "stream.pip", "spaces.thumbnail", "spaces.sendFiles", "host.setUp", "host.action",- "host.limits", "host.openSettings"] {+ "host.limits", "host.openSettings", "repoCache.get", "repoCache.set", "repoCache.clear"] {#expect(WebUIBridge.methods.contains(m), "\(m)")}#expect(!WebUIBridge.methods.contains("spaces.new"))@@ -579,6 +579,29 @@ struct WebUIHostTests {#expect(await failure(bridge, "host.limits", ["maxSpaces": 1.5]) == "bad_args")}+ /// Settings, General's repo cache: read, switched, sized and cleared in+ /// the host's words; a value that is not a number of GB is refused.+ @Test func theRepoCacheReadsChangesAndClears() async throws {+ let (bridge, _) = bridge(backend: FixtureSpacesBackend())+ let got = try #require(try await bridge.handle("repoCache.get", [:]) as? [String: Any])+ #expect(got["enabled"] as? Bool == true)+ #expect(got["summary"] as? String == "Repos: 3, 1.2 GB of 5 GB")+ #expect(got["sizeSetting"] as? String == "auto")+ let off = try #require(try await bridge.handle("repoCache.set", ["enabled": false]) as? [String: Any])+ #expect(off["enabled"] as? Bool == false)+ #expect(off["sizeSetting"] as? String == "auto", "a field not given keeps its value")+ let sized = try #require(try await bridge.handle("repoCache.set", ["enabled": true, "sizeGb": 2]) as? [String: Any])+ #expect(sized["sizeSetting"] as? String == "2")+ #expect(sized["summary"] as? String == "Repos: 3, 1.2 GB of 2 GB")+ let auto = try #require(try await bridge.handle("repoCache.set", ["sizeGb": NSNull()]) as? [String: Any])+ #expect(auto["sizeSetting"] as? String == "auto")+ #expect(await failure(bridge, "repoCache.set", ["sizeGb": -1]) == "bad_args")+ #expect(await failure(bridge, "repoCache.set", ["sizeGb": "lots"]) == "bad_args")+ #expect(await failure(bridge, "repoCache.set", ["enabled": "yes"]) == "bad_args")+ let cleared = try #require(try await bridge.handle("repoCache.clear", [:]) as? [String: Any])+ #expect(cleared["repos"] as? Int == 0)+ }+@Test func hostStatusCarriesTheWholeStateAndTheProgress() async throws {let host = FixtureHost()let (bridge, _) = bridge(host: host)diff --git a/apps/cua-spaces-web/src/__tests__/settings-repo-cache.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-repo-cache.test.tsxnew file mode 100644index 0000000000..e26b0a2a49--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/settings-repo-cache.test.tsx@@ -0,0 +1,69 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Settings, General: the "Repo and dependency cache" row. A switch, a size+// limit, Clear cache and what it holds in plain words.++import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";++import { wasmBuilt } from "@/bridge/__tests__/testCore";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+afterEach(cleanup);++describe.skipIf(!wasmBuilt)("Settings, Repo and dependency cache", () => {+ it("shows what it holds in plain words and changes the switch, the size and clears", async () => {+ const calls: [string, unknown][] = [];+ await mountApp("/settings/general", {+ failsCreates: false,+ listsGhost: false,+ intercept: (op, args) => {+ if (op === "repoCache.set" || op === "repoCache.clear") calls.push([op, args]);+ return undefined;+ },+ });+ const sw = await waitFor(() => {+ const el = document.querySelector<HTMLElement>("#repo-cache");+ expect(el).not.toBeNull();+ return el!;+ });+ const text = document.body.textContent ?? "";+ expect(text).toContain("Repo and dependency cache");+ expect(document.querySelector("[data-repo-cache-summary]")?.textContent).toBe("Repos: 3, 1.2 GB of 5 GB");+ expect(document.querySelector("[data-repo-cache-week]")?.textContent).toMatch(/^Last week: \d+% of clones came from the cache, about 2 minutes saved$/);+ // Words the product avoids, and a middle dot.+ const group = document.querySelector('[data-settings-group="repo-cache"]')?.textContent ?? "";+ expect(group).not.toContain("·");+ expect(group).not.toMatch(/device|computer/i);+ // It does not promise dependencies yet.+ expect(group.replace("Repo and dependency cache", "")).not.toMatch(/dependenc|package|lockfile/i);++ // Size: empty is automatic; a number saves when the field is left.+ const size = document.querySelector<HTMLInputElement>('[data-setting-row="repo-cache-size"]')!;+ expect(size.value).toBe("");+ expect(size.placeholder).toBe("Automatic");+ await act(async () => void fireEvent.change(size, { target: { value: "2" } }));+ await act(async () => void fireEvent.blur(size));+ await waitFor(() => expect(calls).toEqual([["repoCache.set", { sizeGb: 2 }]]));+ await waitFor(() => expect(document.querySelector<HTMLInputElement>('[data-setting-row="repo-cache-size"]')!.value).toBe("2"));+ await waitFor(() => expect(document.querySelector("[data-repo-cache-summary]")?.textContent).toBe("Repos: 3, 1.2 GB of 2 GB"));+ // A number that is not valid is put back, not saved.+ await act(async () => void fireEvent.change(size, { target: { value: "-3" } }));+ await act(async () => void fireEvent.blur(size));+ expect(calls.length).toBe(1);++ // Clear cache empties it.+ const clear = document.querySelector<HTMLButtonElement>('[data-setting-row="repo-cache-clear"]')!;+ await act(async () => void fireEvent.click(clear));+ await waitFor(() => expect(calls[1]).toEqual(["repoCache.clear", {}]));+ await waitFor(() => expect(document.querySelector("[data-repo-cache-summary]")?.textContent).toBe("Repos: 0, 0 MB of 2 GB"));+ expect(document.querySelector("[data-repo-cache-week]")?.textContent).toBe("No clones yet this week");++ // Off hides the size and Clear; the switch calls the host.+ await act(async () => void fireEvent.click(sw));+ await waitFor(() => expect(calls[2]).toEqual(["repoCache.set", { enabled: false }]));+ await waitFor(() => expect(document.querySelector('[data-setting-row="repo-cache-size"]')).toBeNull());+ });+});diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex e87e04ff62..f066f85a78 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -152,6 +152,9 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"loginItem.openSettings": {},"runtimes.check": { kind: "container", path: "/usr/local/bin/docker" },"runtimes.browse": { kind: "container" },+ "repoCache.get": {},+ "repoCache.set": { enabled: true, sizeGb: 2 },+ "repoCache.clear": {},"devices.get": {},"devices.enroll": {},"devices.checkEnrolled": {},diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex e1c7a0a4a4..e40cc1c8dc 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -117,6 +117,9 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {"loginItem.openSettings": {},"runtimes.check": { kind: "container", path: "/usr/local/bin/docker" },"runtimes.browse": { kind: "container" },+ "repoCache.get": {},+ "repoCache.set": { enabled: true, sizeGb: 2 },+ "repoCache.clear": {},"devices.get": {},"devices.enroll": {},"devices.checkEnrolled": {},diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.tsindex 8c193c4c9d..786371a9a9 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/settings.ts@@ -11,7 +11,7 @@ import { HostError } from "../../adapter";import type { DeviceInput, DevicesInput, PairingCode } from "../../contracts/devices";import type { MachineRow } from "../../contracts/host";import type { NotificationInput } from "../../contracts/notifications";-import type { AboutInput, DriveCheckInput, Experiments, LoginItemReport, StorageInput, UpdateState } from "../../contracts/settings";+import type { AboutInput, DriveCheckInput, Experiments, LoginItemReport, RepoCacheView, StorageInput, UpdateState } from "../../contracts/settings";import { NO_EXPERIMENTS } from "../../contracts/volume";import { demoMachine, MAC_DEMO_PLATFORM, type DemoPlatform } from "./platform";import { DEMO_BROWSED, demoProbe } from "./runtimes";@@ -190,6 +190,26 @@ export function createDemoSettings(ctx: DemoSettingsContext): Handlers {const patchDevice = (id: string, patch: Partial<NonNullable<DevicesInput["devices"]>[number]>) => {devices = { ...devices, devices: devices.devices?.map((d) => (d.id === id ? { ...d, ...patch } : d)) };};+ // The repo cache: three repositories and a week of hits to show (the real+ // words come from the host, `cua_sdk::RepoCacheStatus`).+ const repoCache = { enabled: true, sizeGb: null as number | null, repos: 3, bytes: Math.round(1.2 * GIB) };+ const sizeWords = (bytes: number) => (bytes >= GIB ? `${Math.round((bytes / GIB) * 10) / 10} GB` : `${Math.round(bytes / (1024 * 1024))} MB`);+ const repoCacheView = (): RepoCacheView => {+ const capBytes = Math.round((repoCache.sizeGb ?? 5) * GIB);+ const none = repoCache.repos === 0;+ return {+ enabled: repoCache.enabled,+ repos: repoCache.repos,+ bytes: repoCache.bytes,+ capBytes,+ sizeSetting: repoCache.sizeGb === null ? "auto" : String(repoCache.sizeGb),+ summary: `Repos: ${repoCache.repos}, ${sizeWords(repoCache.bytes)} of ${sizeWords(capBytes)}`,+ week: none ? "No clones yet this week" : "Last week: 80% of clones came from the cache, about 2 minutes saved",+ hits: none ? 0 : 8,+ misses: none ? 0 : 2,+ secondsSaved: none ? 0 : 125,+ };+ };const ok = (applied: boolean): DriveCheckInput => ({ ok: true, reachable: true, authorized: true, versioning: true, detail: null, applied });return {@@ -243,6 +263,20 @@ export function createDemoSettings(ctx: DemoSettingsContext): Handlers {},"runtimes.browse": ({ kind }) => ({ path: DEMO_BROWSED[kind] ?? null }),+ "repoCache.get": () => repoCacheView(),+ "repoCache.set": async (change) => {+ await wait(stepMs);+ if (change.enabled !== undefined) repoCache.enabled = change.enabled;+ if (change.sizeGb !== undefined) repoCache.sizeGb = change.sizeGb;+ return repoCacheView();+ },+ "repoCache.clear": async () => {+ await wait(stepMs);+ repoCache.repos = 0;+ repoCache.bytes = 0;+ return repoCacheView();+ },+"devices.get": () => {if (!ctx.signedIn()) throw new HostError("Sign in to Cua to see your machines", "signed_out");return structuredClone(devices);diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex fb28c61fb6..83196b6929 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -3933,6 +3933,53 @@"targetEpoch"]},+ "RepoCacheView": {+ "type": "object",+ "properties": {+ "enabled": {+ "type": "boolean"+ },+ "repos": {+ "type": "number"+ },+ "bytes": {+ "type": "number"+ },+ "capBytes": {+ "type": "number"+ },+ "sizeSetting": {+ "type": "string"+ },+ "summary": {+ "type": "string"+ },+ "week": {+ "type": "string"+ },+ "hits": {+ "type": "number"+ },+ "misses": {+ "type": "number"+ },+ "secondsSaved": {+ "type": "number"+ }+ },+ "required": [+ "enabled",+ "repos",+ "bytes",+ "capBytes",+ "sizeSetting",+ "summary",+ "week",+ "hits",+ "misses",+ "secondsSaved"+ ]+ },"RuntimeFix": {"type": "object","properties": {@@ -8265,6 +8312,15 @@"upgradeUrl"]},+ "repoCache.clear": {+ "$ref": "#/$defs/RepoCacheView"+ },+ "repoCache.get": {+ "$ref": "#/$defs/RepoCacheView"+ },+ "repoCache.set": {+ "$ref": "#/$defs/RepoCacheView"+ },"resources.get": {"type": ["object",@@ -10663,6 +10719,15 @@"upgradeUrl"]},+ "repoCache.clear": {+ "$ref": "#/$defs/RepoCacheView"+ },+ "repoCache.get": {+ "$ref": "#/$defs/RepoCacheView"+ },+ "repoCache.set": {+ "$ref": "#/$defs/RepoCacheView"+ },"resources.get": {"type": ["object",diff --git a/apps/cua-spaces-web/src/bridge/contracts/settings.ts b/apps/cua-spaces-web/src/bridge/contracts/settings.tsindex 90f9eb053b..125eba3730 100644--- a/apps/cua-spaces-web/src/bridge/contracts/settings.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/settings.ts@@ -216,3 +216,31 @@ export type StorageAction =/** The Storage section, as `storage.section` returns it (id `storage`). */export type StorageSection = SettingsSection;++/** What the repo cache holds and saved (`cua_sdk::RepoCacheStatus`; words and numbers only, never a repository name). */+export interface RepoCacheView {+ /** The cache is on (`cache.repos`). */+ enabled: boolean;+ /** Repositories held. */+ repos: number;+ /** What they take on disk, in bytes. */+ bytes: number;+ /** The size cap in force, in bytes. */+ capBytes: number;+ /** The size setting: `auto`, or a number of GB. */+ sizeSetting: string;+ /** `Repos: 3, 1.2 GB of 5 GB`. */+ summary: string;+ /** `Last week: 80% of clones came from the cache, about 2 minutes saved`. */+ week: string;+ hits: number;+ misses: number;+ secondsSaved: number;+}++/** A change to the repo cache (`repoCache.set`); a missing field keeps its value. */+export interface RepoCacheChange {+ enabled?: boolean;+ /** GB; null: automatic (the smaller of 5 GB and a tenth of the free disk). */+ sizeGb?: number | null;+}diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex 9ced978b9b..7545123903 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -57,7 +57,7 @@ import type {WizardEnv,} from "./new-space";import type { NotificationInput } from "./notifications";-import type { AboutInput, DriveCheckInput, DriveStorageInput, LoginItemReport, StorageInput, UpdateState } from "./settings";+import type { AboutInput, DriveCheckInput, DriveStorageInput, LoginItemReport, RepoCacheView, StorageInput, UpdateState } from "./settings";import type { ShareEntry, ShareRemoval } from "./share";import type { BulkResult } from "./spaces-page";import type { CreateFix, CreatingElsewhere, SpaceAccess, SpaceProgress, SpaceRow, SpaceSharingFacts } from "./spaces";@@ -408,6 +408,22 @@ const ExperimentsShape = ref(obj<Experiments>()({ cuaVolume: opt(bool), yourCloud: opt(bool), sharing: opt(bool), webUi: opt(bool) }),);+const RepoCacheShape = ref(+ "RepoCacheView",+ obj<RepoCacheView>()({+ enabled: bool,+ repos: num,+ bytes: num,+ capBytes: num,+ sizeSetting: str,+ summary: str,+ week: str,+ hits: num,+ misses: num,+ secondsSaved: num,+ }),+);+const AboutShape = ref("AboutInput",obj<AboutInput>()({@@ -1442,6 +1458,9 @@ export const OP_SHAPES: Record<OpName, Schema> = {"loginItem.openSettings": nul,"runtimes.check": RuntimePathCheckShape,"runtimes.browse": object({ path: nullable(str) }),+ "repoCache.get": RepoCacheShape,+ "repoCache.set": RepoCacheShape,+ "repoCache.clear": RepoCacheShape,"devices.get": DevicesShape,"devices.enroll": obj<EnrollResult>()({ enrolled: bool, code: nullable(str) }),"devices.checkEnrolled": bool,@@ -1806,6 +1825,9 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {"loginItem.openSettings": nul,"runtimes.check": RuntimePathCheckShape,"runtimes.browse": object({ path: nullable(str) }),+ "repoCache.get": RepoCacheShape,+ "repoCache.set": RepoCacheShape,+ "repoCache.clear": RepoCacheShape,"devices.get": DevicesShape,"devices.enroll": OP_SHAPES["devices.enroll"],"devices.checkEnrolled": bool,diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.tsindex a71e298a04..5a8c3abb9b 100644--- a/apps/cua-spaces-web/src/bridge/coverage.ts+++ b/apps/cua-spaces-web/src/bridge/coverage.ts@@ -181,6 +181,9 @@ export const HOST_COVERAGE = {"loginItem.openSettings": { webkit: { methods: ["loginItem.openSettings"] }, tauri: ST["loginItem.openSettings"] },"runtimes.check": { webkit: { methods: ["runtimes.check"] }, tauri: ST["runtimes.check"], unsupported: { tauri: "the Tauri app has no per-kind runtime settings" } },"runtimes.browse": { webkit: { methods: ["runtimes.browse"] }, tauri: ST["runtimes.browse"], unsupported: { tauri: "the Tauri app has no per-kind runtime settings" } },+ "repoCache.get": { webkit: { methods: ["repoCache.get"] }, tauri: ST["repoCache.get"], unsupported: { tauri: "the Tauri app has no repo cache" } },+ "repoCache.set": { webkit: { methods: ["repoCache.set"] }, tauri: ST["repoCache.set"], unsupported: { tauri: "the Tauri app has no repo cache" } },+ "repoCache.clear": { webkit: { methods: ["repoCache.clear"] }, tauri: ST["repoCache.clear"], unsupported: { tauri: "the Tauri app has no repo cache" } },"devices.get": { webkit: { methods: ["devices.get"] }, tauri: ST["devices.get"] },"devices.enroll": { webkit: { methods: ["devices.enroll"] }, tauri: ST["devices.enroll"] },"devices.checkEnrolled": { webkit: { methods: ["devices.checkEnrolled"] }, tauri: ST["devices.checkEnrolled"] },diff --git a/apps/cua-spaces-web/src/bridge/ops/settings.ts b/apps/cua-spaces-web/src/bridge/ops/settings.tsindex ee10188f82..cee357bbe0 100644--- a/apps/cua-spaces-web/src/bridge/ops/settings.ts+++ b/apps/cua-spaces-web/src/bridge/ops/settings.ts@@ -20,6 +20,8 @@ import type {DriveStorageInput,Experiments,LoginItemReport,+ RepoCacheChange,+ RepoCacheView,StorageInput,StorageRequest,UpdateChannelId,@@ -59,6 +61,13 @@ export interface SettingsOperations {/** The host's file panel, to pick a kind's binary (null: cancelled). */"runtimes.browse": { args: { kind: string }; result: { path: string | null } };+ /** The repo cache (Settings, General): on or off, what it holds, what the last week saved. */+ "repoCache.get": { args: Empty; result: RepoCacheView };+ /** Turns it on or off and sets its size; answers the cache after. */+ "repoCache.set": { args: RepoCacheChange; result: RepoCacheView };+ /** Deletes every repository it holds; answers the cache after. */+ "repoCache.clear": { args: Empty; result: RepoCacheView };+/** The account's devices and access log (`devices_snapshot`). */"devices.get": { args: Empty; result: DevicesInput };/** Registers this device: enrolled at once, or a one-time code. */@@ -104,6 +113,9 @@ export const SETTINGS_OPERATIONS = ["loginItem.openSettings","runtimes.check","runtimes.browse",+ "repoCache.get",+ "repoCache.set",+ "repoCache.clear","devices.get","devices.enroll","devices.checkEnrolled",@@ -178,6 +190,9 @@ export function tauriSettingsOps(invoke: Invoke, ui: { read(key: string): string"update.install": () => Promise.reject(new UnsupportedOperationError("tauri", "update.install")),"runtimes.check": () => Promise.reject(new UnsupportedOperationError("tauri", "runtimes.check")),"runtimes.browse": () => Promise.reject(new UnsupportedOperationError("tauri", "runtimes.browse")),+ "repoCache.get": () => Promise.reject(new UnsupportedOperationError("tauri", "repoCache.get")),+ "repoCache.set": () => Promise.reject(new UnsupportedOperationError("tauri", "repoCache.set")),+ "repoCache.clear": () => Promise.reject(new UnsupportedOperationError("tauri", "repoCache.clear")),// The Tauri app keeps the switches in its UI storage, as its own Settings does."experiments.get": async () => readExperiments(),@@ -254,7 +269,7 @@ export function tauriSettingsOps(invoke: Invoke, ui: { read(key: string): string}/** The Tauri updater has one feed and no controls. */-export const TAURI_SETTINGS_UNSUPPORTED = ["about.set", "about.checkNow", "update.get", "update.install", "runtimes.check", "runtimes.browse"] as const satisfies readonly SettingsOpName[];+export const TAURI_SETTINGS_UNSUPPORTED = ["about.set", "about.checkNow", "update.get", "update.install", "runtimes.check", "runtimes.browse", "repoCache.get", "repoCache.set", "repoCache.clear"] as const satisfies readonly SettingsOpName[];/** The Tauri commands each operation calls (`coverage.ts`). */export const SETTINGS_TAURI_COMMANDS = {@@ -270,6 +285,9 @@ export const SETTINGS_TAURI_COMMANDS = {"loginItem.openSettings": ["host_open_settings"],"runtimes.check": [],"runtimes.browse": [],+ "repoCache.get": [],+ "repoCache.set": [],+ "repoCache.clear": [],"devices.get": ["devices_snapshot"],"devices.enroll": ["devices_enroll"],"devices.checkEnrolled": ["devices_check_enrolled"],diff --git a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.tsindex def765dc81..3cb2852f2c 100644--- a/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts+++ b/apps/cua-spaces-web/src/bridge/ops/webkit-pages.ts@@ -77,6 +77,9 @@ export const WEBKIT_PAGE_OPS = ["loginItem.openSettings","runtimes.check","runtimes.browse",+ "repoCache.get",+ "repoCache.set",+ "repoCache.clear","devices.get","devices.enroll","devices.checkEnrolled",@@ -261,6 +264,9 @@ export function webkitPageOps(request: Request, toHostStatus: (h: WkHostState) ="runtimes.check": call("runtimes.check"),// The file panel waits for the person: no timeout."runtimes.browse": async (args) => (await request("runtimes.browse", { ...args }, null)) as { path: string | null },+ "repoCache.get": call("repoCache.get"),+ "repoCache.set": call("repoCache.set"),+ "repoCache.clear": call("repoCache.clear"),"devices.get": call("devices.get"),"devices.enroll": call("devices.enroll"),"devices.checkEnrolled": async () => Boolean(await request("devices.checkEnrolled")),diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex c80e8ea7fc..6a798c718c 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -128,6 +128,9 @@ export const WEBKIT_METHODS = ["loginItem.openSettings","runtimes.check","runtimes.browse",+ "repoCache.get",+ "repoCache.set",+ "repoCache.clear","devices.get","devices.enroll","devices.checkEnrolled",diff --git a/apps/cua-spaces-web/src/components/settings/general-tab.tsx b/apps/cua-spaces-web/src/components/settings/general-tab.tsxindex ceefbdcce7..1f7c943482 100644--- a/apps/cua-spaces-web/src/components/settings/general-tab.tsx+++ b/apps/cua-spaces-web/src/components/settings/general-tab.tsx@@ -9,6 +9,7 @@ import type { HostLimitRow, HostLimits } from "@/bridge/contracts/host";import { chooseSettings, useBridge, useLoginItem, useMachines, useSession, useSettings, useThisMachine, useTips, type GlobalShortcut, type SettingsRow as CoreRow } from "@/bridge";import { SettingsGroup, SettingsRow } from "@/components/settings-group";import { CoreSettingsRow } from "@/components/settings/core-section";+import { RepoCacheGroup } from "@/components/settings/repo-cache-group";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Segmented } from "@/components/ui/segmented";@@ -127,6 +128,7 @@ export function GeneralTab() {) : null}</SettingsGroup><SharingGroup />+ <RepoCacheGroup /></div>);}diff --git a/apps/cua-spaces-web/src/components/settings/repo-cache-group.tsx b/apps/cua-spaces-web/src/components/settings/repo-cache-group.tsxnew file mode 100644index 0000000000..8faa8ee2fc--- /dev/null+++ b/apps/cua-spaces-web/src/components/settings/repo-cache-group.tsx@@ -0,0 +1,151 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useCallback, useEffect, useRef, useState } from "react";++import { isUnsupported, useBridge, useMachines } from "@/bridge";+import type { RepoCacheChange, RepoCacheView } from "@/bridge/contracts/settings";+import { SettingsGroup, SettingsRow } from "@/components/settings-group";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";+import { toastError } from "@/components/ui/toast";++/** How often what the cache holds is read again while Settings is open. */+const REFRESH_MS = 15_000;++/**+ * Settings, General: "Repo and dependency cache". A switch (on by default), the most disk it may use+ * (empty is automatic), "Clear cache", and in plain words what it holds and what the last week saved.+ * The host owns all of it (the repo cache of the Cua daemon); a host without one draws nothing.+ */+export function RepoCacheGroup() {+ const { data: adapter } = useBridge();+ // Sharing above draws once the machines are known: this group waits for the same moment, so it never moves when Sharing arrives.+ const { data: machines } = useMachines();+ const [view, setView] = useState<RepoCacheView | null>(null);+ // Until the host has answered, the group holds the room it takes, so nothing below it moves.+ const [answered, setAnswered] = useState(false);+ const [busy, setBusy] = useState(false);+ const shown = view && view.sizeSetting !== "auto" ? view.sizeSetting : "";+ const [draft, setDraft] = useState(shown);+ const latest = useRef(shown);+ latest.current = shown;+ useEffect(() => setDraft(shown), [shown]);++ const read = useCallback(async () => {+ if (!adapter) return;+ try {+ setView(await adapter.call("repoCache.get", {}));+ } catch (e) {+ // A host without a repo cache has no row; any other failure keeps what is shown.+ if (isUnsupported(e)) setView(null);+ } finally {+ setAnswered(true);+ }+ }, [adapter]);++ useEffect(() => {+ void read();+ const t = setInterval(() => void read(), REFRESH_MS);+ return () => clearInterval(t);+ }, [read]);++ if (!adapter || machines === undefined) return null;+ if (!view) {+ return answered ? null : (+ <SettingsGroup title="Cache" data-settings-group="repo-cache" aria-busy="true">+ <div className="h-[233px]" />+ </SettingsGroup>+ );+ }++ const run = async (op: "repoCache.set" | "repoCache.clear", args: RepoCacheChange, what: string) => {+ if (busy) return;+ setBusy(true);+ try {+ setView(await adapter.call(op, args));+ } catch (e) {+ toastError(what)(e);+ setDraft(latest.current);+ } finally {+ setBusy(false);+ }+ };++ const saveSize = () => {+ const text = draft.trim();+ const n = text === "" ? null : Number(text);+ if (n !== null && (!Number.isFinite(n) || n < 0)) return setDraft(shown);+ if ((n === null ? "" : String(n)) === shown) return setDraft(shown);+ void run("repoCache.set", { sizeGb: n }, "Couldn't change the cache size");+ };++ return (+ <SettingsGroup title="Cache" data-settings-group="repo-cache">+ <SettingsRow+ label="Repo and dependency cache"+ htmlFor="repo-cache"+ description={+ <>+ Keeps copies of public repositories on this machine, so cloning one again in a Space is fast. Nothing private is kept.+ <span className="block" data-repo-cache-summary>+ {view.summary}+ </span>+ <span className="block" data-repo-cache-week>+ {view.week}+ </span>+ </>+ }+ control={+ <Switch+ id="repo-cache"+ data-setting-row="repo-cache"+ checked={view.enabled}+ disabled={busy}+ onCheckedChange={(on) => void run("repoCache.set", { enabled: on }, "Couldn't change the cache")}+ />+ }+ />+ {view.enabled ? (+ <>+ <SettingsRow+ label="Size limit"+ htmlFor="repo-cache-size"+ description="The least recently used repositories go first. Empty is automatic: the smaller of 5 GB and a tenth of the free disk."+ control={+ <span className="flex items-center gap-2">+ <Input+ id="repo-cache-size"+ data-setting-row="repo-cache-size"+ type="number"+ inputMode="decimal"+ min={0}+ className="w-28 text-right"+ placeholder="Automatic"+ value={draft}+ disabled={busy}+ onValueChange={setDraft}+ onBlur={saveSize}+ onKeyDown={(e) => {+ if (e.key === "Enter") (e.target as HTMLInputElement).blur();+ }}+ />+ <span className="w-12 text-[13px] text-muted-foreground">GB</span>+ </span>+ }+ />+ <SettingsRow+ label="Clear cache"+ description="Deletes the copies. They are made again the next time a Space clones them."+ control={+ <Button size="sm" variant="outline" data-setting-row="repo-cache-clear" disabled={busy || view.repos === 0} onClick={() => void run("repoCache.clear", {}, "Couldn't clear the cache")}>+ Clear cache+ </Button>+ }+ />+ </>+ ) : null}+ </SettingsGroup>+ );+}diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lockindex e1d49a6146..a0d45ed36a 100644--- a/apps/cua-spaces/src-tauri/Cargo.lock+++ b/apps/cua-spaces/src-tauri/Cargo.lock@@ -2086,6 +2086,22 @@ dependencies = ["tonic-prost-build",]+[[package]]+name = "cua-repo-cache"+version = "0.9.0"+dependencies = [+ "cua-home",+ "cua-telemetry",+ "hex",+ "libc",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tokio",+ "tracing",+ "url",+]+[[package]]name = "cua-sandbox-core"version = "0.9.0"@@ -2095,6 +2111,7 @@ dependencies = ["bytes","cua-home","cua-image",+ "cua-repo-cache","cua-spacesd-client","cua-vmm","futures-util",diff --git a/docs/content/docs/cua-cli/reference/cli/index.mdx b/docs/content/docs/cua-cli/reference/cli/index.mdxindex 09b0b3f637..af06526d57 100644--- a/docs/content/docs/cua-cli/reference/cli/index.mdx+++ b/docs/content/docs/cua-cli/reference/cli/index.mdx@@ -26,7 +26,7 @@ Your Spaces and machines, unattended access on this machine, devices, teams, you| --- | --- | --- || <span id="cua-spaces"></span><span id="cua-spaces-ls"></span><span id="cua-spaces-add"></span><span id="cua-spaces-create"></span><span id="cua-spaces-prewarm"></span><span id="cua-spaces-egress"></span><span id="cua-spaces-cancel"></span><span id="cua-spaces-gpus"></span><span id="cua-spaces-delete"></span><span id="cua-spaces-stop"></span><span id="cua-spaces-suspend"></span><span id="cua-spaces-resize"></span><span id="cua-spaces-start"></span><span id="cua-spaces-rm"></span><span id="cua-spaces-rename"></span><span id="cua-spaces-share"></span><span id="cua-spaces-unshare"></span><span id="cua-spaces-shares"></span><span id="cua-spaces-relay-register"></span><span id="cua-spaces-relay-unregister"></span>[`cua spaces`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces) | Spaces: registered ones and your computers on the relay. | [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-ls), [`add`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-add), [`create`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-create), [`prewarm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-prewarm), [`egress`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-egress), [`cancel`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-cancel), [`gpus`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-gpus), [`delete`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-delete), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-stop), [`suspend`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-suspend), [`resize`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-resize), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-start), [`rm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rm), [`rename`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rename), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-unshare), [`shares`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-shares), [`relay-register`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-register), [`relay-unregister`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-unregister) || <span id="cua-machines"></span><span id="cua-machines-rm"></span>[`cua machines`](/cua-cli/reference/cli/spaces-and-computers#cua-machines) | Your computers on the relay: remove one that is gone. | [`rm`](/cua-cli/reference/cli/spaces-and-computers#cua-machines-rm) |-| <span id="cua-host"></span><span id="cua-host-setup"></span><span id="cua-host-pair"></span><span id="cua-host-config"></span><span id="cua-host-status"></span><span id="cua-host-stop"></span><span id="cua-host-start"></span><span id="cua-host-share"></span><span id="cua-host-unshare"></span><span id="cua-host-migrate"></span><span id="cua-host-remove"></span>[`cua host`](/cua-cli/reference/cli/spaces-and-computers#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). | [`setup`](/cua-cli/reference/cli/spaces-and-computers#cua-host-setup), [`pair`](/cua-cli/reference/cli/spaces-and-computers#cua-host-pair), [`config`](/cua-cli/reference/cli/spaces-and-computers#cua-host-config), [`status`](/cua-cli/reference/cli/spaces-and-computers#cua-host-status), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-host-stop), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-host-start), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-host-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-host-unshare), [`migrate`](/cua-cli/reference/cli/spaces-and-computers#cua-host-migrate), [`remove`](/cua-cli/reference/cli/spaces-and-computers#cua-host-remove) |+| <span id="cua-host"></span><span id="cua-host-setup"></span><span id="cua-host-pair"></span><span id="cua-host-config"></span><span id="cua-host-cache"></span><span id="cua-host-cache-status"></span><span id="cua-host-cache-fill"></span><span id="cua-host-cache-clear"></span><span id="cua-host-status"></span><span id="cua-host-stop"></span><span id="cua-host-start"></span><span id="cua-host-share"></span><span id="cua-host-unshare"></span><span id="cua-host-migrate"></span><span id="cua-host-remove"></span>[`cua host`](/cua-cli/reference/cli/spaces-and-computers#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). | [`setup`](/cua-cli/reference/cli/spaces-and-computers#cua-host-setup), [`pair`](/cua-cli/reference/cli/spaces-and-computers#cua-host-pair), [`config`](/cua-cli/reference/cli/spaces-and-computers#cua-host-config), [`cache`](/cua-cli/reference/cli/spaces-and-computers#cua-host-cache), [`cache status`](/cua-cli/reference/cli/spaces-and-computers#cua-host-cache-status), [`cache fill`](/cua-cli/reference/cli/spaces-and-computers#cua-host-cache-fill), [`cache clear`](/cua-cli/reference/cli/spaces-and-computers#cua-host-cache-clear), [`status`](/cua-cli/reference/cli/spaces-and-computers#cua-host-status), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-host-stop), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-host-start), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-host-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-host-unshare), [`migrate`](/cua-cli/reference/cli/spaces-and-computers#cua-host-migrate), [`remove`](/cua-cli/reference/cli/spaces-and-computers#cua-host-remove) || <span id="cua-devices"></span><span id="cua-devices-status"></span><span id="cua-devices-enroll"></span><span id="cua-devices-approve"></span><span id="cua-devices-ls"></span><span id="cua-devices-rename"></span><span id="cua-devices-revoke"></span><span id="cua-devices-audit"></span>[`cua devices`](/cua-cli/reference/cli/spaces-and-computers#cua-devices) | This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what. | [`status`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-status), [`enroll`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-enroll), [`approve`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-approve), [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-ls), [`rename`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-rename), [`revoke`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-revoke), [`audit`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-audit) || <span id="cua-team"></span><span id="cua-team-create"></span><span id="cua-team-ls"></span><span id="cua-team-show"></span><span id="cua-team-invite"></span><span id="cua-team-join"></span><span id="cua-team-leave"></span><span id="cua-team-remove-member"></span><span id="cua-team-set-role"></span><span id="cua-team-devices"></span><span id="cua-team-approve"></span><span id="cua-team-deny"></span><span id="cua-team-request"></span><span id="cua-team-add-machine"></span><span id="cua-team-remove-machine"></span><span id="cua-team-audit"></span><span id="cua-team-delete"></span>[`cua team`](/cua-cli/reference/cli/spaces-and-computers#cua-team) | Teams (organizations of your cua.ai account) share computers with every member and their agents. | [`create`](/cua-cli/reference/cli/spaces-and-computers#cua-team-create), [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-team-ls), [`show`](/cua-cli/reference/cli/spaces-and-computers#cua-team-show), [`invite`](/cua-cli/reference/cli/spaces-and-computers#cua-team-invite), [`join`](/cua-cli/reference/cli/spaces-and-computers#cua-team-join), [`leave`](/cua-cli/reference/cli/spaces-and-computers#cua-team-leave), [`remove-member`](/cua-cli/reference/cli/spaces-and-computers#cua-team-remove-member), [`set-role`](/cua-cli/reference/cli/spaces-and-computers#cua-team-set-role), [`devices`](/cua-cli/reference/cli/spaces-and-computers#cua-team-devices), [`approve`](/cua-cli/reference/cli/spaces-and-computers#cua-team-approve), [`deny`](/cua-cli/reference/cli/spaces-and-computers#cua-team-deny), [`request`](/cua-cli/reference/cli/spaces-and-computers#cua-team-request), [`add-machine`](/cua-cli/reference/cli/spaces-and-computers#cua-team-add-machine), [`remove-machine`](/cua-cli/reference/cli/spaces-and-computers#cua-team-remove-machine), [`audit`](/cua-cli/reference/cli/spaces-and-computers#cua-team-audit), [`delete`](/cua-cli/reference/cli/spaces-and-computers#cua-team-delete) || <span id="cua-usage"></span>[`cua usage`](/cua-cli/reference/cli/spaces-and-computers#cua-usage) | Your remote use this month: live sessions, remote hours, and your plan. | |diff --git a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdxindex 8a4c33125a..2ca46986b0 100644--- a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx+++ b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx@@ -38,6 +38,10 @@ description: "Your Spaces and machines, unattended access on this machine, devic| [`cua host setup`](#cua-host-setup) | Set this computer up for unattended access: install cua-spacesd as a service that joins the cua.ai relay as your account (default) or serves on a direct ip:port. || [`cua host pair`](#cua-host-pair) | Make a one-time code (with a link and the install command) that adds another computer to your account: run the command it prints on that computer. || [`cua host config`](#cua-host-config) | Show or change what this computer shares: its own desktop, and whether it creates Spaces for your other devices. |+| [`cua host cache`](#cua-host-cache) | What the repo cache holds, and empty it. |+| [`cua host cache status`](#cua-host-cache-status) | What the repo cache holds: repositories, size and what the last week saved. |+| [`cua host cache fill`](#cua-host-cache-fill) | Copy one public repository into the cache now, instead of when a Space first clones it (or bring a copy up to date). |+| [`cua host cache clear`](#cua-host-cache-clear) | Delete every repository the cache holds. || [`cua host status`](#cua-host-status) | Show whether this computer is set up, the service, and who is connected. || [`cua host stop`](#cua-host-stop) | Stop sharing: disconnect everyone and refuse new connections. || [`cua host start`](#cua-host-start) | Start sharing again after `stop`. |@@ -692,6 +696,8 @@ cua host config [OPTIONS]| <span id="cua-host-config--max-memory"></span>`--max-memory` | integer | | Memory in GB the Spaces other machines create here may use in total (0: no limit). || <span id="cua-host-config--max-disk"></span>`--max-disk` | integer | | Disk in GB the Spaces other machines create here may use in total (0: no limit). || <span id="cua-host-config--max-run-time"></span>`--max-run-time` | integer | | Minutes a Space created here by another machine may run before it is stopped (0: no limit). |+| <span id="cua-host-config--repo-cache"></span>`--repo-cache` | `on` \| `off` | | The repo cache: on \| off. It keeps verified copies of public git repositories on this machine so a repeat `git clone` in a Space starts from one (never private repositories, never anything off this machine's disk). |+| <span id="cua-host-config--repo-cache-size"></span>`--repo-cache-size` | string | | The most disk the repo cache may use, in GB (`auto`: the smaller of 5 GB and a tenth of the free disk). The least recently used repositories go first. |**Examples**@@ -704,6 +710,64 @@ cua host config --max-spaces 6# Give the Spaces other machines create here at most 32 GB of memory and 200 GB of disk in total, and stop each after 8 hours (0: no limit)cua host config --max-memory 32 --max-disk 200 --max-run-time 480++# Keep no copies of public git repositories on this machine, or at most 2 GB+cua host config --repo-cache off+cua host config --repo-cache on --repo-cache-size 2+```++### `cua host cache`++What the repo cache holds, and empty it.++```text output+cua host cache [OPTIONS] <COMMAND>+```++#### `cua host cache status`++What the repo cache holds: repositories, size and what the last week saved.++```text output+cua host cache status [OPTIONS]+```++**Examples**++```bash test="cli-shape" id="ref-cua-host-cache-status"+cua host cache status+```++#### `cua host cache fill`++Copy one public repository into the cache now, instead of when a Space first clones it (or bring a copy up to date). A repository that needs a sign-in is never cached.++```text output+cua host cache fill [OPTIONS] <URL>+```++| Argument | Type | Default | Description |+| --- | --- | --- | --- |+| `<URL>` | string | required | The repository's `https` address. |++**Examples**++```bash test="cli-shape" id="ref-cua-host-cache-fill"+cua host cache fill https://github.com/vitejs/vite+```++#### `cua host cache clear`++Delete every repository the cache holds. They are copied again the next time a Space clones them.++```text output+cua host cache clear [OPTIONS]+```++**Examples**++```bash test="cli-shape" id="ref-cua-host-cache-clear"+cua host cache clear```### `cua host status`diff --git a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdxindex 23d20cb69e..c9c495d993 100644--- a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx+++ b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx@@ -33,6 +33,7 @@ Every event carries: `telemetry_schema_version`, `event_version`, `product`| `cua_agent_run_started` | `harness` (cua-agents id or `other`), `location`, `entry` (`spaces_tool`, `cli`, `sdk`, `persistent`, `routine`), `outcome`, `error_kind` | Agent runs started, and failed starts. || `cua_agent_run_completed` | `harness`, `location`, `entry`, `outcome`, `error_kind`, `duration_bucket` | First agent run, and how reliably runs finish. Once per run. || `cua_agent_join_phase` | `phase` (`posted`, `dispatch_picked`, `host_prepared`, `guest_spawned`, `install_done`, `runner_started`, `agent_spawned`, `acp_initialized`, `acp_authenticated`, `session_ready`, `turn_started`, `first_token`, `turn_ended` or `failed`), `harness`, `runtime`, `cold`, `ms_since_post`, `run` (a per-install salted hash, never the run id), `tool` (`install_done` only), `failure` (`failed` only: `auth`, `install`, `timeout` or `other`) | How long an agent takes to join a Space and answer, step by step, and where joins fail. Never the message, the Space or the account. |+| `cua_repo_cache` | `outcome` (`hit`, `miss` or `fallback`), `source` (`local` or `network`), `bytes_saved`, `seconds_saved`, `reason` (`none`, `disabled`, `no_git`, `unsupported_url`, `host_not_public`, `private`, `unreachable`, `too_big`, `cache_full`, `disk_full`, `verify_failed`, `fill_failed` or `other`) | Whether the repo cache makes repeat `git clone`s in Spaces faster, how often it can be used, and why it cannot. Counts and fixed words only: never a URL, a repository name or a path. || `cua_bench_run_completed` | `taskset` (cua-bench dataset or `custom`), `score_bucket`, `task_count`, `outcome` | Benchmark use and coarse scores. || `cua_daemon_started` | `mode`, `outcome` | Daemon startup reliability. || `cua_daemon_health` | `uptime_bucket`, `sandboxes` | Hourly aggregate health. |diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdxindex 138659b80d..3f1c5b1e75 100644--- a/docs/content/docs/cua-sdk/reference/index.mdx+++ b/docs/content/docs/cua-sdk/reference/index.mdx@@ -27,6 +27,7 @@ The Cua SDK in Python, TypeScript, Swift, Kotlin and Rust, all generated from th| --- | --- || [Cua client and local runtimes](/cua-sdk/reference/cua) | The Cua handle (embedded or daemon client, configuration, SDK version) and the local container and VM runtimes. || [Runtime per kind](/cua-sdk/reference/runtime-kinds) | Which program runs containers, virtual machines and microVMs on this machine, and what a given binary is. |+| [Repo cache](/cua-sdk/reference/repo-cache) | What the repo cache holds and what it saved, and clearing it. || [Sandbox](/cua-sdk/reference/sandbox) | Create, find, connect to and control sandboxes, and their lifecycle: wait, suspend, resume, restart, detach and delete. || [Lifecycle](/cua-sdk/reference/sandbox/lifecycle) | Wait for, keep alive, give a lifetime to, suspend, resume, restart, resize, detach and delete a sandbox. || [Checkpoints and forks](/cua-sdk/reference/sandbox/checkpoints) | Save a local sandbox's state as a named checkpoint and start new sandboxes from it. |@@ -98,4 +99,4 @@ The Cua SDK in Python, TypeScript, Swift, Kotlin and Rust, all generated from th| --- | --- || [Protocol](/cua-sdk/reference/protocol) | The gRPC contracts of cua-spacesd (`cua.env.v1`) and the cua daemon (`cua.daemon.v1`). |-353 items, 437 methods. The [Types](/cua-sdk/reference/types) page lists them.+356 items, 437 methods. The [Types](/cua-sdk/reference/types) page lists them.diff --git a/docs/content/docs/cua-sdk/reference/meta.json b/docs/content/docs/cua-sdk/reference/meta.jsonindex 689d931973..e0a4acba61 100644--- a/docs/content/docs/cua-sdk/reference/meta.json+++ b/docs/content/docs/cua-sdk/reference/meta.json@@ -4,6 +4,7 @@"---Sandboxes---","cua","runtime-kinds",+ "repo-cache","sandbox","share","image",diff --git a/docs/content/docs/cua-sdk/reference/repo-cache.mdx b/docs/content/docs/cua-sdk/reference/repo-cache.mdxnew file mode 100644index 0000000000..c84ed01577--- /dev/null+++ b/docs/content/docs/cua-sdk/reference/repo-cache.mdx@@ -0,0 +1,128 @@+---+title: "Repo cache"+description: "What the repo cache holds and what it saved, and clearing it."+---++{/*+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY+ Generated by: pnpm --dir docs docs:generate:cua-sdk+ Source: cua-bindgen docs (UniFFI metadata of libcua_sdk)+ Version: 0.9.0+*/}++import { Tab, Tabs } from 'fumadocs-ui/components/tabs';++The daemon keeps verified copies of public git repositories so a repeat `git clone` in a Space is fast. `repo_cache_status` reads what it holds and what the last week saved in plain words; `repo_cache_clear` deletes every copy. It is on by default and is turned off, or given a size, with `config_set` on `cache.repos` and `cache.repos_size_gb`.++## `RepoCacheStatus` record++What the repo cache holds and what it saved, in plain words for+Settings (`cache.repos` and `cache.repos_size_gb` are its settings,+changed with `config_set`).++Returned by [`repo_cache_clear`](#repo_cache_clear), [`repo_cache_status`](#repo_cache_status).++| Field | Type | Default | Description |+| --- | --- | --- | --- |+| `enabled` | `bool` | | The cache is on (`cache.repos`). |+| `repos` | `u32` | | Repositories held. |+| `bytes` | `u64` | | What they take on disk. |+| `cap_bytes` / `capBytes` | `u64` | | The size cap in force. |+| `size_setting` / `sizeSetting` | `String` | | The size setting: `auto`, or the number of GB. |+| `summary` | `String` | | `Repos: 3, 1.2 GB of 5 GB`. |+| `week` | `String` | | `Last week: 80% of clones came from the cache, about 2 minutes saved`. |+| `hits` | `u32` | | Clones served from the cache in the last week. |+| `misses` | `u32` | | Clones that downloaded in the last week. |+| `seconds_saved` / `secondsSaved` | `u64` | | Seconds the hits saved. |++## `repo_cache_status`++The repo cache now: on or off, how much it holds of its cap, and what+the last week saved.++<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>+<Tab value="Python">++```python+def repo_cache_status() -> RepoCacheStatus+```++</Tab>+<Tab value="TypeScript">++```ts+function repoCacheStatus(): RepoCacheStatus+```++</Tab>+<Tab value="Swift">++```swift+func repoCacheStatus() throws -> RepoCacheStatus+```++</Tab>+<Tab value="Kotlin">++```kotlin+@Throws(CuaException::class)+fun repoCacheStatus(): RepoCacheStatus+```++</Tab>+<Tab value="Rust">++```rust+pub fn repo_cache_status() -> Result<RepoCacheStatus, CuaError>+```++</Tab>+</Tabs>++**Returns** [`RepoCacheStatus`](#repocachestatus-record) · **Raises** [`CuaError`](/cua-sdk/reference/errors)++## `repo_cache_clear`++Deletes every repository the repo cache holds (they are copied again the+next time a Space clones them). Returns the cache after.++<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>+<Tab value="Python">++```python+def repo_cache_clear() -> RepoCacheStatus+```++</Tab>+<Tab value="TypeScript">++```ts+function repoCacheClear(): RepoCacheStatus+```++</Tab>+<Tab value="Swift">++```swift+func repoCacheClear() throws -> RepoCacheStatus+```++</Tab>+<Tab value="Kotlin">++```kotlin+@Throws(CuaException::class)+fun repoCacheClear(): RepoCacheStatus+```++</Tab>+<Tab value="Rust">++```rust+pub fn repo_cache_clear() -> Result<RepoCacheStatus, CuaError>+```++</Tab>+</Tabs>++**Returns** [`RepoCacheStatus`](#repocachestatus-record) · **Raises** [`CuaError`](/cua-sdk/reference/errors)diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdxindex 127986bb2b..0c151deded 100644--- a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx+++ b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx@@ -18,7 +18,7 @@ The cua SDK: the only `#[uniffi::export]` crate of `libs/cua`.These are the objects, records, enums and functions the language bindings export, documented once in the [Cua SDK reference](/cua-sdk/reference), whose Rust tabs show each signature. Objects are `Arc<T>` handles whose methods are `async fn` returning `Result<_, CuaError>`, records are structs with public fields, and names are snake_case.-[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces/agents#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agent-setup#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agent-setup#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces/agents#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agent-setup#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agent-setup#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agent-setup#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agent-setup#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces/agents#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox/lifecycle#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BakeForkCheck`](/cua-sdk/reference/sandbox/bake#bakeforkcheck-record), [`BakeOptions`](/cua-sdk/reference/sandbox/bake#bakeoptions-record), [`BakeSummary`](/cua-sdk/reference/sandbox/bake#bakesummary-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BuildImageConfig`](/cua-sdk/reference/spaces/build#buildimageconfig-record), [`BuildInfo`](/cua-sdk/reference/spaces/build#buildinfo-record), [`BuildListener`](/cua-sdk/reference/spaces/build#buildlistener), [`BuildOptions`](/cua-sdk/reference/spaces/build#buildoptions-record), [`BuildProgress`](/cua-sdk/reference/spaces/build#buildprogress-record), [`BuildResult`](/cua-sdk/reference/spaces/build#buildresult-record), [`BuildStep`](/cua-sdk/reference/spaces/build#buildstep-enum), [`BuildStepResult`](/cua-sdk/reference/spaces/build#buildstepresult-record), [`BulkResult`](/cua-sdk/reference/spaces/sharing#bulkresult-record), [`BundledSkill`](/cua-sdk/reference/agent-setup#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CheckpointSummary`](/cua-sdk/reference/sandbox/checkpoints#checkpointsummary-record), [`CloudAuditEntry`](/cua-sdk/reference/spaces/persistent-agents#cloudauditentry-record), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudConnectOptions`](/cua-sdk/reference/spaces/persistent-agents#cloudconnectoptions-record), [`CloudCostReport`](/cua-sdk/reference/spaces/persistent-agents#cloudcostreport-record), [`CloudCostRow`](/cua-sdk/reference/spaces/persistent-agents#cloudcostrow-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudNext`](/cua-sdk/reference/spaces/persistent-agents#cloudnext-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`EgressEnforcement`](/cua-sdk/reference/spaces/space#egressenforcement-enum), [`EgressPolicy`](/cua-sdk/reference/spaces#egresspolicy-record), [`ElasticAssignment`](/cua-sdk/reference/spaces/elastic#elasticassignment-record), [`ElasticBudget`](/cua-sdk/reference/spaces/elastic#elasticbudget-record), [`ElasticBudgetUpdate`](/cua-sdk/reference/spaces/elastic#elasticbudgetupdate-record), [`ElasticDecision`](/cua-sdk/reference/spaces/elastic#elasticdecision-record), [`ElasticHost`](/cua-sdk/reference/spaces/elastic#elastichost-record), [`ElasticNewHost`](/cua-sdk/reference/spaces/elastic#elasticnewhost-record), [`ElasticPlan`](/cua-sdk/reference/spaces/elastic#elasticplan-record), [`ElasticPlanRequest`](/cua-sdk/reference/spaces/elastic#elasticplanrequest-record), [`ElasticRemoved`](/cua-sdk/reference/spaces/elastic#elasticremoved-record), [`ElasticUnplaced`](/cua-sdk/reference/spaces/elastic#elasticunplaced-record), [`ForkBatch`](/cua-sdk/reference/sandbox/fork-batch#forkbatch), [`ForkBatchEvent`](/cua-sdk/reference/sandbox/fork-batch#forkbatchevent-enum), [`ForkBatchItem`](/cua-sdk/reference/sandbox/fork-batch#forkbatchitem-record), [`ForkBatchPlacement`](/cua-sdk/reference/sandbox/fork-batch#forkbatchplacement-record), [`ForkBatchResult`](/cua-sdk/reference/sandbox/fork-batch#forkbatchresult-record), [`ForkBatchSummary`](/cua-sdk/reference/sandbox/fork-batch#forkbatchsummary-record), [`ForkGroup`](/cua-sdk/reference/sandbox/fork-batch#forkgroup-record), [`ForkManyOptions`](/cua-sdk/reference/sandbox/fork-batch#forkmanyoptions-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`NamedVolume`](/cua-sdk/reference/spaces/volume#namedvolume-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolCreateOptions`](/cua-sdk/reference/image#poolcreateoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`Prewarm`](/cua-sdk/reference/spaces/elastic#prewarm-record), [`PrewarmOptions`](/cua-sdk/reference/spaces/elastic#prewarmoptions-record), [`PrewarmPlacement`](/cua-sdk/reference/spaces/elastic#prewarmplacement-record), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd/shell#replaymode-enum), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`RuntimeDetected`](/cua-sdk/reference/runtime-kinds#runtimedetected-record), [`RuntimeKindState`](/cua-sdk/reference/runtime-kinds#runtimekindstate-record), [`RuntimePathProbe`](/cua-sdk/reference/runtime-kinds#runtimepathprobe-record), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxPool`](/cua-sdk/reference/image#sandboxpool-record), [`SandboxRefParts`](/cua-sdk/reference/sandbox/lifecycle#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`Share`](/cua-sdk/reference/share#share-record), [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum), [`ShareCheck`](/cua-sdk/reference/share#sharecheck-record), [`SharedBase`](/cua-sdk/reference/spaces/space#sharedbase-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`SnapshotFallbackOptions`](/cua-sdk/reference/sandbox/fork-batch#snapshotfallbackoptions-record), [`SnapshotSyncProgress`](/cua-sdk/reference/sandbox/fork-batch#snapshotsyncprogress-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceCreatingElsewhere`](/cua-sdk/reference/spaces/space#spacecreatingelsewhere-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record), [`SpaceList`](/cua-sdk/reference/spaces/list-watch#spacelist-record), [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/relay-registration#spacerelayregistration-record), [`SpaceResizeReport`](/cua-sdk/reference/spaces/resize#spaceresizereport-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdDownload`](/cua-sdk/reference/spacesd#spacesddownload), [`SpacesdForward`](/cua-sdk/reference/spacesd#spacesdforward), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd/shell#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/sharing#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/sharing#spaceshares-record), [`SpaceSharing`](/cua-sdk/reference/spaces/sharing#spacesharing-record), [`SpacesHost`](/cua-sdk/reference/spaces/host#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/host#spaceshostlimit-record), [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record), [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener), [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch), [`SpacesToolMethod`](/cua-sdk/reference/spaces#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceTeamShare`](/cua-sdk/reference/spaces/sharing#spaceteamshare-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceTransport`](/cua-sdk/reference/spaces/channel#spacetransport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record), [`VolumeMount`](/cua-sdk/reference/spaces/volume#volumemount-record).+[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces/agents#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agent-setup#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agent-setup#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces/agents#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agent-setup#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agent-setup#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agent-setup#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agent-setup#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces/agents#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox/lifecycle#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BakeForkCheck`](/cua-sdk/reference/sandbox/bake#bakeforkcheck-record), [`BakeOptions`](/cua-sdk/reference/sandbox/bake#bakeoptions-record), [`BakeSummary`](/cua-sdk/reference/sandbox/bake#bakesummary-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BuildImageConfig`](/cua-sdk/reference/spaces/build#buildimageconfig-record), [`BuildInfo`](/cua-sdk/reference/spaces/build#buildinfo-record), [`BuildListener`](/cua-sdk/reference/spaces/build#buildlistener), [`BuildOptions`](/cua-sdk/reference/spaces/build#buildoptions-record), [`BuildProgress`](/cua-sdk/reference/spaces/build#buildprogress-record), [`BuildResult`](/cua-sdk/reference/spaces/build#buildresult-record), [`BuildStep`](/cua-sdk/reference/spaces/build#buildstep-enum), [`BuildStepResult`](/cua-sdk/reference/spaces/build#buildstepresult-record), [`BulkResult`](/cua-sdk/reference/spaces/sharing#bulkresult-record), [`BundledSkill`](/cua-sdk/reference/agent-setup#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CheckpointSummary`](/cua-sdk/reference/sandbox/checkpoints#checkpointsummary-record), [`CloudAuditEntry`](/cua-sdk/reference/spaces/persistent-agents#cloudauditentry-record), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudConnectOptions`](/cua-sdk/reference/spaces/persistent-agents#cloudconnectoptions-record), [`CloudCostReport`](/cua-sdk/reference/spaces/persistent-agents#cloudcostreport-record), [`CloudCostRow`](/cua-sdk/reference/spaces/persistent-agents#cloudcostrow-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudNext`](/cua-sdk/reference/spaces/persistent-agents#cloudnext-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`EgressEnforcement`](/cua-sdk/reference/spaces/space#egressenforcement-enum), [`EgressPolicy`](/cua-sdk/reference/spaces#egresspolicy-record), [`ElasticAssignment`](/cua-sdk/reference/spaces/elastic#elasticassignment-record), [`ElasticBudget`](/cua-sdk/reference/spaces/elastic#elasticbudget-record), [`ElasticBudgetUpdate`](/cua-sdk/reference/spaces/elastic#elasticbudgetupdate-record), [`ElasticDecision`](/cua-sdk/reference/spaces/elastic#elasticdecision-record), [`ElasticHost`](/cua-sdk/reference/spaces/elastic#elastichost-record), [`ElasticNewHost`](/cua-sdk/reference/spaces/elastic#elasticnewhost-record), [`ElasticPlan`](/cua-sdk/reference/spaces/elastic#elasticplan-record), [`ElasticPlanRequest`](/cua-sdk/reference/spaces/elastic#elasticplanrequest-record), [`ElasticRemoved`](/cua-sdk/reference/spaces/elastic#elasticremoved-record), [`ElasticUnplaced`](/cua-sdk/reference/spaces/elastic#elasticunplaced-record), [`ForkBatch`](/cua-sdk/reference/sandbox/fork-batch#forkbatch), [`ForkBatchEvent`](/cua-sdk/reference/sandbox/fork-batch#forkbatchevent-enum), [`ForkBatchItem`](/cua-sdk/reference/sandbox/fork-batch#forkbatchitem-record), [`ForkBatchPlacement`](/cua-sdk/reference/sandbox/fork-batch#forkbatchplacement-record), [`ForkBatchResult`](/cua-sdk/reference/sandbox/fork-batch#forkbatchresult-record), [`ForkBatchSummary`](/cua-sdk/reference/sandbox/fork-batch#forkbatchsummary-record), [`ForkGroup`](/cua-sdk/reference/sandbox/fork-batch#forkgroup-record), [`ForkManyOptions`](/cua-sdk/reference/sandbox/fork-batch#forkmanyoptions-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`NamedVolume`](/cua-sdk/reference/spaces/volume#namedvolume-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolCreateOptions`](/cua-sdk/reference/image#poolcreateoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`Prewarm`](/cua-sdk/reference/spaces/elastic#prewarm-record), [`PrewarmOptions`](/cua-sdk/reference/spaces/elastic#prewarmoptions-record), [`PrewarmPlacement`](/cua-sdk/reference/spaces/elastic#prewarmplacement-record), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd/shell#replaymode-enum), [`repo_cache_clear`](/cua-sdk/reference/repo-cache#repo_cache_clear), [`repo_cache_status`](/cua-sdk/reference/repo-cache#repo_cache_status), [`RepoCacheStatus`](/cua-sdk/reference/repo-cache#repocachestatus-record), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`RuntimeDetected`](/cua-sdk/reference/runtime-kinds#runtimedetected-record), [`RuntimeKindState`](/cua-sdk/reference/runtime-kinds#runtimekindstate-record), [`RuntimePathProbe`](/cua-sdk/reference/runtime-kinds#runtimepathprobe-record), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxPool`](/cua-sdk/reference/image#sandboxpool-record), [`SandboxRefParts`](/cua-sdk/reference/sandbox/lifecycle#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`Share`](/cua-sdk/reference/share#share-record), [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum), [`ShareCheck`](/cua-sdk/reference/share#sharecheck-record), [`SharedBase`](/cua-sdk/reference/spaces/space#sharedbase-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`SnapshotFallbackOptions`](/cua-sdk/reference/sandbox/fork-batch#snapshotfallbackoptions-record), [`SnapshotSyncProgress`](/cua-sdk/reference/sandbox/fork-batch#snapshotsyncprogress-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceCreatingElsewhere`](/cua-sdk/reference/spaces/space#spacecreatingelsewhere-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record), [`SpaceList`](/cua-sdk/reference/spaces/list-watch#spacelist-record), [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/relay-registration#spacerelayregistration-record), [`SpaceResizeReport`](/cua-sdk/reference/spaces/resize#spaceresizereport-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdDownload`](/cua-sdk/reference/spacesd#spacesddownload), [`SpacesdForward`](/cua-sdk/reference/spacesd#spacesdforward), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd/shell#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/sharing#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/sharing#spaceshares-record), [`SpaceSharing`](/cua-sdk/reference/spaces/sharing#spacesharing-record), [`SpacesHost`](/cua-sdk/reference/spaces/host#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/host#spaceshostlimit-record), [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record), [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener), [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch), [`SpacesToolMethod`](/cua-sdk/reference/spaces#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceTeamShare`](/cua-sdk/reference/spaces/sharing#spaceteamshare-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceTransport`](/cua-sdk/reference/spaces/channel#spacetransport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record), [`VolumeMount`](/cua-sdk/reference/spaces/volume#volumemount-record).## Typesdiff --git a/docs/content/docs/cua-sdk/reference/types.mdx b/docs/content/docs/cua-sdk/reference/types.mdxindex 5ac30901b0..03d6538d86 100644--- a/docs/content/docs/cua-sdk/reference/types.mdx+++ b/docs/content/docs/cua-sdk/reference/types.mdx@@ -48,7 +48,7 @@ Renamed members: in Kotlin, objects implement `AutoCloseable`, whose `close()` f## All items-325 items. Methods are listed on their object.+328 items. Methods are listed on their object.The 10 items of Batched forks are listed on [its page](/cua-sdk/reference/sandbox/fork-batch#all-items).@@ -261,6 +261,9 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref| [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record) | record | A client device of the account, as the relay lists it. || [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record) | record | A machine of the account's relay directory (`relay:<id>`). || [`ReplayMode`](/cua-sdk/reference/spacesd/shell#replaymode-enum) | enum | Scrollback replay when attaching. |+| [`repo_cache_clear`](/cua-sdk/reference/repo-cache#repo_cache_clear) | function | Deletes every repository the repo cache holds (they are copied again the next time a Space clones them). |+| [`repo_cache_status`](/cua-sdk/reference/repo-cache#repo_cache_status) | function | The repo cache now: on or off, how much it holds of its cap, and what the last week saved. |+| [`RepoCacheStatus`](/cua-sdk/reference/repo-cache#repocachestatus-record) | record | What the repo cache holds and what it saved, in plain words for Settings (`cache.repos` and `cache.repos_size_gb` are its settings, changed with… || [`resolve_image`](/cua-sdk/reference/image#resolve_image) | function | Resolves `reference` for `backend` (`auto`, `local`, `provider`, `container`/`docker`/`gvisor`, `vm`/`qemu`/`kubevirt`, `lume`) on… || [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret) | function | `resolve_image` for a private image: `secret` joins the head of the registry auth chain (it is read in this process and never cached or logged). || [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record) | record | A reference resolved for a backend. |diff --git a/docs/content/docs/spaces/guides/repo-cache.mdx b/docs/content/docs/spaces/guides/repo-cache.mdxnew file mode 100644index 0000000000..355e2bd38e--- /dev/null+++ b/docs/content/docs/spaces/guides/repo-cache.mdx@@ -0,0 +1,86 @@+---+title: Repo cache+description: 'How Cua keeps verified copies of public git repositories on this machine so a repeat git clone in a Space is fast, what it never caches, the setting, how to clear it and what it reports.'+---++import { Callout } from 'fumadocs-ui/components/callout';++The first time a Space clones a public repository, Cua downloads it as usual.+In the background, the Cua daemon on your machine also keeps a verified copy+of that repository. The next Space that clones it starts from that copy, so a+repository that took about 5 seconds to clone takes about a second, and only+what changed since is downloaded. Your agent runs the same `git clone URL` as+always. There is nothing to set up per repository and no list to maintain.++## What is and is not cached++- **Public repositories only.** Cua asks the remote for its branches with no+ credentials at all. If that works, the repository is public and can be+ cached. A repository that needs a sign-in, a token or a key is never cached,+ and a clone of it goes the normal way.+- **`https` addresses on a public host.** Addresses with a user name or token+ in them, other ports, `ssh` addresses and hosts on a private network are+ never cached.+- **Repositories, not dependencies yet.** The row in Settings is called+ **Repo and dependency cache** because it will hold more later. Today it holds+ repositories.+- **This machine's disk only.** Nothing is sent anywhere to fill it, and a+ copy is never shared with another machine.++## How a clone uses it++The copies live in a folder that Linux container Spaces on this machine see+read-only. A small helper that Cua puts next to the Space's git, never the+agent, makes `git clone` ask the remote for its current tip and take the+objects it already has from the copy:++- The clone always ends at the remote's own tip, never an older one. If the+ remote has a new commit, the clone downloads just that.+- Each clone has its own files. It does not depend on the copy afterwards, so+ clearing the cache or removing a repository never breaks a clone.+- The Space can only read the copy. Nothing a Space writes reaches another+ Space or the cache.+- Spaces keep the network access they already had. The cache does not open any.+- If the copy is missing, damaged or the folder is not there, `git clone`+ simply runs the normal way, with no error.++Virtual machine Spaces and macOS Spaces do not see the folder yet, so they+clone the normal way.++## The setting++In **Settings**, **General**, **Repo and dependency cache** has a switch (on by+default), a size limit and **Clear cache**. Under the switch it says in plain+words what it holds, for example `Repos: 3, 1.2 GB of 5 GB`, how many clones+came from it over the last week and about how much time that saved.++The size limit is automatic unless you set it: the smaller of 5 GB and a tenth+of the free disk. When the cache is full, the repository used least recently+goes first. A repository bigger than the limit is not cached.++From a terminal:++```bash test="cli-shape" id="cua-host-cache"+cua host cache status # what it holds and what the last week saved+cua host config --repo-cache off # keep no copies+cua host config --repo-cache on --repo-cache-size 2 # at most 2 GB+cua host config --repo-cache-size auto # the default size+cua host cache clear # delete every copy+```++The same settings are `cache.repos` and `cache.repos_size_gb` in+[`cua config`](/cua-cli/reference).++## Privacy++The cache reports counts and fixed words only: whether a clone was served from+the cache, a miss or a fallback, the bytes and seconds a hit saved, and why a+clone was not served from the cache, from a fixed list such as `private` or+`cache_full`. It never sends a URL, a repository name or a path. See+[Telemetry events](/cua-sdk/concepts/telemetry-events) for the exact event,+`cua_repo_cache`, and how to turn telemetry off.++<Callout type="info">+ Turning the cache off stops new copies and stops Spaces from using the+ existing ones. The copies stay on disk until you press **Clear cache**.+</Callout>diff --git a/docs/content/docs/spaces/meta.json b/docs/content/docs/spaces/meta.jsonindex 1de2f2fdc6..c7d9f70e7c 100644--- a/docs/content/docs/spaces/meta.json+++ b/docs/content/docs/spaces/meta.json@@ -22,6 +22,7 @@"guides/teleport-an-app","guides/keyvault","guides/cua-volume",+ "guides/repo-cache","guides/sandbox-sdks","guides/create-a-space-with-the-sdk","---Agents in a Space---",diff --git a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lockindex 42b0ab2776..00dd5a1c6d 100644--- a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock+++ b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock@@ -2076,6 +2076,22 @@ dependencies = ["tonic-prost-build",]+[[package]]+name = "cua-repo-cache"+version = "0.9.0"+dependencies = [+ "cua-home",+ "cua-telemetry",+ "hex",+ "libc",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tokio",+ "tracing",+ "url",+]+[[package]]name = "cua-sandbox-core"version = "0.9.0"@@ -2085,6 +2101,7 @@ dependencies = ["bytes","cua-home","cua-image",+ "cua-repo-cache","cua-spacesd-client","cua-vmm","futures-util",diff --git a/examples/streaming/rust/Cargo.lock b/examples/streaming/rust/Cargo.lockindex 08b4d8b9bc..cbe6d472c6 100644--- a/examples/streaming/rust/Cargo.lock+++ b/examples/streaming/rust/Cargo.lock@@ -1639,6 +1639,22 @@ dependencies = ["tonic-prost-build",]+[[package]]+name = "cua-repo-cache"+version = "0.9.0"+dependencies = [+ "cua-home",+ "cua-telemetry",+ "hex",+ "libc",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tokio",+ "tracing",+ "url",+]+[[package]]name = "cua-sandbox-core"version = "0.9.0"@@ -1648,6 +1664,7 @@ dependencies = ["bytes","cua-home","cua-image",+ "cua-repo-cache","cua-spacesd-client","cua-vmm","futures-util",diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lockindex 8ae57f7238..058b5d1409 100644--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock@@ -2592,6 +2592,22 @@ dependencies = ["yamux",]+[[package]]+name = "cua-repo-cache"+version = "0.9.0"+dependencies = [+ "cua-home",+ "cua-telemetry",+ "hex",+ "libc",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tokio",+ "tracing",+ "url",+]+[[package]]name = "cua-sandbox-core"version = "0.9.0"@@ -2601,6 +2617,7 @@ dependencies = ["bytes","cua-home","cua-image",+ "cua-repo-cache","cua-spacesd-client","cua-vmm","futures-util",diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lockindex 91f3478e20..b56b6ccbbe 100644--- a/libs/cua/Cargo.lock+++ b/libs/cua/Cargo.lock@@ -2481,6 +2481,7 @@ dependencies = ["cua-host","cua-image","cua-proto",+ "cua-repo-cache","cua-sandbox-core","cua-sdk","cua-spaces",@@ -2978,6 +2979,23 @@ dependencies = ["tonic-prost-build",]+[[package]]+name = "cua-repo-cache"+version = "0.9.0"+dependencies = [+ "cua-home",+ "cua-telemetry",+ "hex",+ "libc",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tempfile",+ "tokio",+ "tracing",+ "url",+]+[[package]]name = "cua-sandbox-core"version = "0.9.0"@@ -2988,6 +3006,7 @@ dependencies = ["bytes","cua-home","cua-image",+ "cua-repo-cache","cua-sandbox-core","cua-spacesd-client","cua-vmm",diff --git a/libs/cua/Cargo.toml b/libs/cua/Cargo.tomlindex 8f3f3db69a..e3c5242a46 100644--- a/libs/cua/Cargo.toml+++ b/libs/cua/Cargo.toml@@ -16,6 +16,9 @@ members = ["crates/cua-image",# Disk accounting, cache budget and garbage collection (`cua cache`)."crates/cua-disk",+ # The repo cache: public git repositories mirrored by the daemon so a+ # repeat clone in a Space is fast (a read-only mount, a git remote helper).+ "crates/cua-repo-cache",# Share a link to anything you run (`cua share`): records, the read-only# file server and the access-checked gateway."crates/cua-share",@@ -185,6 +188,7 @@ cua-image = { path = "crates/cua-image", version = "0.9.0" } # x-release-please-cua-microvm-init = { path = "crates/cua-microvm-init", version = "0.9.0" } # x-release-please-versioncua-vmm = { path = "crates/cua-vmm", version = "0.9.0", default-features = false } # x-release-please-versioncua-disk = { path = "crates/cua-disk", version = "0.9.0" } # x-release-please-version+cua-repo-cache = { path = "crates/cua-repo-cache", version = "0.9.0" } # x-release-please-versioncua-sandbox-core = { path = "crates/cua-sandbox-core", version = "0.9.0" } # x-release-please-versioncua-contrib = { path = "crates/cua-contrib", version = "0.9.0", default-features = false } # x-release-please-versioncua-host = { path = "crates/cua-host", version = "0.9.0" } # x-release-please-versiondiff --git a/libs/cua/bench/README.md b/libs/cua/bench/README.mdindex 829777d6de..7cfafd8337 100644--- a/libs/cua/bench/README.md+++ b/libs/cua/bench/README.md@@ -18,6 +18,7 @@ cua bench check ./mf/result.json --baseline microvm-fork/baseline.json| `microvm-fork` | `microvm-fork/` | macOS on Apple silicon || `fork-fanout` | `fork-fanout/` | macOS (HVF) or Linux with KVM, a source checkout || `fork-batch` | `fork-batch/` | macOS (HVF) or Linux with KVM, the Python SDK |+| `repo-clone` | `repo-clone/` | macOS or Linux with git and the network (`MODE=space`: a Linux container runtime) || `channel` | `channel/` | macOS (HVF) or Linux with KVM || `rollouts` | `rollouts/` | macOS or Linux with gVisor || `pool-sessions` | `pool-sessions/` | your signed-in machines and a test site |diff --git a/libs/cua/bench/bench_result.py b/libs/cua/bench/bench_result.pyindex 984441dfc1..5d63d26370 100644--- a/libs/cua/bench/bench_result.py+++ b/libs/cua/bench/bench_result.py@@ -385,6 +385,43 @@ def convert_pool_sessions(jobs: List[dict]) -> Tuple[Core, Samples]:return core("space_start_ms", "ms", "p50", pct(starts, 50), len(starts), percentiles(starts), extra), indexed(rows)+# --------------------------------------------------------- repo-clone+++def convert_repo_clone(run: dict) -> Tuple[Core, Samples]:+ """repo-clone's JSON: per repository and case, the measured trials+ (a trial that failed a check is counted, not measured). The value is the+ clone p50 of the first repository in the first hit case (`hit`, else+ `hit_lease`, else the first case that ran); every case's p50s go to+ `extra`."""+ repos = run.get("repos") or {}+ rows: Samples = []+ extra: Dict[str, Any] = {"failed": 0}+ headline = None+ for name, r in repos.items():+ for case, c in (r.get("cases") or {}).items():+ extra["failed"] += c.get("failed", 0)+ for i, s in enumerate(c.get("samples") or []):+ rows.append({"repo": name, "case": case, "trial": i + 1, "ok": bool(s.get("ok")), **{k: s.get(k, "") for k in ("space_create_ms", "agent_ready_ms", "first_bash_ms", "clone_ms", "total_ms")}})+ st = (c.get("stats") or {}).get("clone_ms") or {}+ if _num(st.get("p50")):+ extra[f"{name}_{case}_clone_p50_ms"] = st["p50"]+ tot = ((c.get("stats") or {}).get("total_ms") or {}).get("p50")+ if _num(tot):+ extra[f"{name}_{case}_total_p50_ms"] = tot+ good = [s["clone_ms"] for s in c.get("samples", []) if s.get("ok") and _num(s.get("clone_ms"))]+ rank = {"hit": 0, "hit_lease": 1}.get(case, 2)+ if headline is None or rank < headline[0]:+ headline = (rank, good, name, case)+ can = r.get("canary") or {}+ if can.get("ran"):+ extra[f"{name}_canary_ok"] = 1 if can.get("ok") else 0+ if headline is None or not headline[1]:+ raise NoResult("no measured clone")+ good = headline[1]+ return core("clone_ms", "ms", "p50", pct(good, 50), len(good), percentiles(good), extra), indexed(rows)++# ------------------------------------------------------------ dispatch@@ -422,6 +459,7 @@ CONVERTERS: Dict[str, Callable[[str], Tuple[Core, Samples]]] = {read_jsonl(os.path.join(raw, "raw.jsonl")) if os.path.exists(os.path.join(raw, "raw.jsonl")) else [],),"pool-sessions": lambda raw: convert_pool_sessions(_json(_one(raw, "jobs.json"))),+ "repo-clone": lambda raw: convert_repo_clone(_json(_one(raw, "repo-clone.json"))),}diff --git a/libs/cua/bench/cuabench.py b/libs/cua/bench/cuabench.pyindex 42222c55bf..53224fcc78 100644--- a/libs/cua/bench/cuabench.py+++ b/libs/cua/bench/cuabench.py@@ -175,6 +175,21 @@ BENCHES: List[Bench] = [guard="fork-batch/check.py",host_class={"darwin": "macos-hvf-m2max", "linux": "linux-kvm-gh"},),+ Bench(+ name="repo-clone",+ measures="A fresh agent in a fresh Space runs git clone as its first bash call: Space create, first bash call and clone timed apart, with the repo cache off, empty (miss), holding a mirror (hit) and holding one verified a moment ago (hit_lease), for a small, a medium and a large repository",+ host="macOS or Linux with git and the network; real Spaces (MODE=space) need a Linux container runtime",+ slug="repo-clone",+ kind="container",+ method="Each trial makes a Space (MODE=sim: a directory with the git config, helper and mirrors a container Space sees; MODE=space: `cua spaces create` and `cua sb exec`), runs a no-op, then `git clone` of the repository. REPOS (small, medium, large or URLs) and CASES (off, miss, hit, hit_lease) pick what runs. A trial whose clone is not the remote's HEAD, fails `git fsck`, keeps an alternate or a credential, or does not come from the cache in a hit case is counted as failed and not measured; the canary check shows an object written in one clone is not in another or in the mirror. The value is the clone p50 of the first repository in the first hit case (hit if it runs).",+ files=["repo-clone/bench.py", "repo-clone/README.md"],+ n_help="trials per repository and case (N, default 5)",+ default_n=5,+ caveats=[+ "MODE=sim runs the clone as a container Space does (the same git config, helper and mirror files) on this machine, without a Space: it measures the clone, not the Space.",+ "agent_ready_ms is empty unless AGENT_CMD names a command that returns when the agent is ready: this bench starts no model.",+ ],+ ),Bench(name="channel",measures="The coordinator-to-Space channel through the SDK: a no-op call, exec round trips, file upload and download, streamed stdout",@@ -546,6 +561,35 @@ def execute(b: Bench, n: Optional[int], raw: str, env: dict, args) -> int:raw,log,)+ if b.name == "repo-clone":+ mode = os.environ.get("MODE", "sim")+ if mode not in ("sim", "space"):+ raise Usage("MODE is sim or space")+ cmd = [+ sys.executable,+ os.path.join(HERE, "repo-clone", "bench.py"),+ "--mode",+ mode,+ "--repos",+ os.environ.get("REPOS", "small,medium"),+ "--cases",+ os.environ.get("CASES", "off,miss,hit,hit_lease"),+ "--n",+ str(n or b.default_n),+ "--cua",+ cua,+ "--home",+ env["CUA_HOME"],+ "--canary",+ "--out",+ os.path.join(raw, "repo-clone.json"),+ ]+ if os.environ.get("AGENT_CMD"):+ cmd += ["--agent-cmd", os.environ["AGENT_CMD"]]+ if mode == "space":+ with Daemon(cua, env, os.path.join(raw, "daemon.log")):+ return run_script(cmd, env, raw, log)+ return run_script(cmd, env, raw, log)if b.name == "channel":bench = need_env("CHANNEL_BENCH", "channel_bench")label = "macos-m2max-qemu" if IS_MAC else "ci-ubuntu-24.04-kvm-lane"diff --git a/libs/cua/bench/repo-clone/README.md b/libs/cua/bench/repo-clone/README.mdnew file mode 100644index 0000000000..7e5fdcac29--- /dev/null+++ b/libs/cua/bench/repo-clone/README.md@@ -0,0 +1,53 @@+# repo-clone++A fresh agent in a fresh Space runs `git clone` as its first bash call. This+bench times what the repo cache changes about that: every trial reports the+Space create, the first no-op bash call, the clone and the total apart, for a+small, a medium and a large public repository, in four cases:++| Case | What the cache holds when the Space clones |+|---|---|+| `off` | the cache is off |+| `miss` | the cache is on and empty: the clone downloads |+| `hit` | a verified mirror; the helper asks the remote for its tip, so the clone is never older than the remote |+| `hit_lease` | a mirror verified a moment ago: the clone needs no network |++```bash+cua bench run repo-clone # MODE=sim: small and medium, 5 trials each+REPOS=small,medium,large N=10 cua bench run repo-clone+MODE=space cua bench run repo-clone # real Spaces (a Linux container runtime)+CASES=off,hit cua bench run repo-clone --n 3+AGENT_CMD='true' cua bench run repo-clone # also time "the agent is ready"+```++`MODE=sim` (the default) makes no Space: a temporary directory carries the git+config, helper and mirror a container Space sees, so the clone runs exactly as+it does in one. It measures the clone, not the Space (`space_create_ms` is the+directory). `MODE=space` uses `cua spaces create` and `cua sb exec` with a+daemon of the same `cua` binary and a Spaces home of the run's own.++## What is checked++A trial that fails a check is counted as failed and is not measured:++- the clone's `HEAD` is the remote's `HEAD` (never stale);+- `git fsck --connectivity-only` passes;+- the clone has no alternate (it does not depend on the mirror) and no+ credential in `.git/config`, and the environment holds no token;+- a `hit` or `hit_lease` clone was served from the cache, and an `off` or+ `miss` clone was not.++The canary check (`--canary`, on under `cua bench run`) writes an object in one+clone and requires that another clone, and the mirror, never see it.++## The loop's use++`bench.py` writes `repo-clone.json` (schema `cua.repo-clone/v1`): per+repository and case the raw trials, the failed count and p50, p95, min and max+of every phase. `cua bench run repo-clone` converts it to the shared result+format. A loop that changes the cache (clone strategy, lease, mirror refresh)+runs it before and after and keeps the change only if the medians improve+beyond the run to run spread and no check fails.++The value is the clone p50 of the first repository in the first hit case. It+has no perf guard: the targets are not set yet.diff --git a/libs/cua/bench/repo-clone/bench.py b/libs/cua/bench/repo-clone/bench.pynew file mode 100644index 0000000000..beb96dc3f9--- /dev/null+++ b/libs/cua/bench/repo-clone/bench.py@@ -0,0 +1,360 @@+#!/usr/bin/env python3+"""A fresh agent in a fresh Space clones a repository (the repo cache).++Scenario: create a Space, get an agent ready, run `git clone <url>` as the+agent's first bash call. Every trial is timed in four parts and in total:++ space_create_ms the Space exists and its cua-spacesd answers+ agent_ready_ms the agent process is ready (only with --agent-cmd; null+ otherwise: this harness starts no model)+ first_bash_ms the first no-op command's round trip+ clone_ms `git clone` of the repository, to the end+ total_ms from the create request to the end of the clone++Cases (what the repo cache holds when the Space clones):++ off the cache is off+ miss the cache is on and empty: the clone downloads (the daemon+ starts filling the cache from it)+ hit a verified mirror is held; the helper asks the remote for its+ tip (the lease is off), so the clone is never older than it+ hit_lease a mirror verified a moment ago: no network at all++Every trial is also checked, and a trial that fails any check is counted as+failed and is not measured: the clone's HEAD is the remote's HEAD, `git fsck`+passes, the clone has no alternate and no credential in its config, and a hit+really came from the cache. With `--canary` an object written in one clone is+never visible in another clone or in the mirror.++Modes:++ sim no Space: a temporary directory with the git config, helper and+ mirror a container Space sees, so the clone runs exactly as in a+ Space, on this machine (what `cua bench` can run anywhere with git+ and the network).+ space real Spaces: `cua spaces create` and `cua sb exec` (needs a Linux+ container runtime); the daemon of the same `cua` binary and its own+ CUA_HOME.++Usage:+ CUA=/path/to/cua python3 bench.py --mode sim --repos small,medium --n 5 \\+ --out raw/repo-clone.json+"""++from __future__ import annotations++import argparse+import json+import math+import os+import shutil+import subprocess+import sys+import tempfile+import time+import uuid+from typing import Dict, List, Optional++REPOS = {+ "small": "https://github.com/octocat/Hello-World",+ "medium": "https://github.com/vitejs/vite",+ "large": "https://github.com/trycua/cua",+}+CASES = ("off", "miss", "hit", "hit_lease")+SCHEMA = "cua.repo-clone/v1"+PHASES = ("space_create_ms", "agent_ready_ms", "first_bash_ms", "clone_ms", "total_ms")+++def ms(a: float, b: float) -> float:+ return round((b - a) * 1000, 1)+++def pct(values: List[float], p: float) -> Optional[float]:+ v = sorted(values)+ if not v:+ return None+ k = (len(v) - 1) * p / 100+ f = int(math.floor(k))+ c = min(f + 1, len(v) - 1)+ return round(v[f] + (v[c] - v[f]) * (k - f), 1)+++def stats(values: List[float]) -> Dict[str, float]:+ if not values:+ return {}+ return {"p50": pct(values, 50), "p95": pct(values, 95), "min": round(min(values), 1), "max": round(max(values), 1)}+++def run(cmd, env=None, cwd=None, timeout=1800) -> subprocess.CompletedProcess:+ return subprocess.run(cmd, env=env, cwd=cwd, capture_output=True, text=True, timeout=timeout)+++class Cua:+ """The `cua` binary with a Spaces home of its own."""++ def __init__(self, binary: str, home: str):+ self.binary = binary+ self.home = home+ self.env = dict(os.environ, CUA_HOME=home, DO_NOT_TRACK="1", CUA_TELEMETRY="0")+ self.root = os.path.join(home, "job-cache", "repos")++ def __call__(self, *args, timeout=1800) -> subprocess.CompletedProcess:+ return run([self.binary, *args], env=self.env, timeout=timeout)++ def set_cache(self, on: bool) -> None:+ self("host", "config", "--repo-cache", "on" if on else "off")++ def fill(self, url: str) -> bool:+ return self("host", "cache", "fill", url).returncode == 0++ def clear(self) -> None:+ self("host", "cache", "clear")+++class SimSpace:+ """What a container Space sees, without the container: the cache's git+ config as the system config, the helper on PATH, the mirrors where the+ helper looks."""++ def __init__(self, cua: Cua, case: str):+ self.cua = cua+ self.case = case+ self.dir = tempfile.mkdtemp(prefix="repo-clone-sim-")+ self.log = os.path.join(self.dir, "helper.log")++ def create(self) -> None:+ os.makedirs(os.path.join(self.dir, "work"), exist_ok=True)++ def env(self) -> dict:+ # What a Space has, not what this machine has: no token of the host's.+ keep = ("PATH", "LANG", "TERM", "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "NO_PROXY", "no_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR")+ e = {k: os.environ[k] for k in keep if k in os.environ}+ e.update(HOME=self.dir, GIT_CONFIG_GLOBAL="/dev/null", GIT_TERMINAL_PROMPT="0", CUA_REPO_CACHE_LOG=self.log)+ if self.case != "off":+ root = self.cua.root+ e.update(+ GIT_CONFIG_SYSTEM=os.path.join(root, "gitconfig"),+ CUA_REPO_CACHE_ROOT=root,+ PATH=os.path.join(root, "bin") + os.pathsep + e["PATH"],+ )+ if self.case == "hit":+ e["CUA_REPO_CACHE_LEASE"] = "0"+ else:+ e["GIT_CONFIG_SYSTEM"] = "/dev/null"+ return e++ def exec(self, command: str) -> subprocess.CompletedProcess:+ return run(["sh", "-c", command], env=self.env(), cwd=os.path.join(self.dir, "work"))++ def helper_log(self) -> str:+ try:+ return open(self.log).read()+ except OSError:+ return ""++ def delete(self) -> None:+ shutil.rmtree(self.dir, ignore_errors=True)+++class RealSpace:+ """A Linux container Space through the real CLI."""++ def __init__(self, cua: Cua, case: str, image: str, kind: str):+ self.cua = cua+ self.case = case+ self.name = f"bench-clone-{uuid.uuid4().hex[:8]}"+ self.image = image+ self.kind = kind++ def create(self) -> None:+ r = self.cua("spaces", "create", self.image, "--name", self.name, "--kind", self.kind, timeout=900)+ if r.returncode != 0:+ raise RuntimeError(f"cua spaces create failed: {r.stderr.strip()[-400:]}")++ def exec(self, command: str) -> subprocess.CompletedProcess:+ return self.cua("sb", "exec", self.name, command, timeout=1800)++ def helper_log(self) -> str:+ return self.exec("cat /tmp/.cua-repo-cache.log 2>/dev/null; true").stdout++ def delete(self) -> None:+ self.cua("spaces", "delete", self.name, timeout=300)+++def remote_head(url: str) -> Optional[str]:+ r = run(["git", "ls-remote", url, "HEAD"], env=dict(os.environ, GIT_TERMINAL_PROMPT="0"), timeout=120)+ return r.stdout.split()[0] if r.returncode == 0 and r.stdout.strip() else None+++def prepare(cua: Cua, case: str, url: str, first: bool) -> None:+ """What the cache holds before one trial."""+ if case == "off":+ if first:+ cua.set_cache(False)+ return+ if first:+ cua.set_cache(True)+ if case == "miss":+ cua.clear()+ elif case in ("hit", "hit_lease"):+ # A hit needs a mirror; `hit_lease` also needs it verified a moment+ # ago, so it is filled (or confirmed) right before every trial.+ if case == "hit_lease" or first or not os.path.isdir(cua.root):+ if not cua.fill(url):+ raise RuntimeError(f"the cache could not hold {url} (private, too big, or unreachable)")+++def trial(make_space, cua: Cua, case: str, url: str, agent_cmd: Optional[str]) -> dict:+ space = make_space()+ out: dict = {"ok": False}+ t0 = time.perf_counter()+ try:+ space.create()+ t1 = time.perf_counter()+ t2 = t1+ if agent_cmd:+ space.exec(agent_cmd)+ t2 = time.perf_counter()+ space.exec("true")+ t3 = time.perf_counter()+ where = f"/tmp/bench-clone-{uuid.uuid4().hex[:8]}"+ r = space.exec(f"git clone --quiet {url} {where} 2>&1")+ t4 = time.perf_counter()+ out.update(+ space_create_ms=ms(t0, t1),+ agent_ready_ms=ms(t1, t2) if agent_cmd else None,+ first_bash_ms=ms(t2, t3),+ clone_ms=ms(t3, t4),+ total_ms=ms(t0, t4),+ )+ if r.returncode != 0:+ out["error"] = (r.stdout + r.stderr).strip()[-300:]+ return out+ head = space.exec(f"git -C {where} rev-parse HEAD").stdout.strip()+ want = remote_head(url)+ log = space.helper_log()+ checks = {+ "head_matches_remote": bool(want) and head == want,+ "fsck_ok": space.exec(f"git -C {where} fsck --connectivity-only >/dev/null 2>&1").returncode == 0,+ "no_alternate": space.exec(f"test ! -e {where}/.git/objects/info/alternates").returncode == 0,+ "no_credentials_in_config": space.exec(f"! grep -qE '://[^/]*@' {where}/.git/config").returncode == 0,+ "no_token_in_env": space.exec("env | grep -qiE '(token|secret|password|api_key)=' && exit 1 || exit 0").returncode == 0,+ }+ if case in ("hit", "hit_lease"):+ checks["served_from_cache"] = "hit_" in log+ if case in ("off", "miss"):+ checks["not_served_from_cache"] = "hit_" not in log+ out["checks"] = checks+ out["ok"] = all(checks.values())+ return out+ except Exception as e: # a failed trial is recorded, never hidden+ out["error"] = str(e)[-300:]+ return out+ finally:+ space.exec("rm -rf /tmp/bench-clone-*")+ space.delete()+++def canary(make_space, cua: Cua, url: str) -> dict:+ """An object written in one clone is not visible in another clone, and+ never reaches the mirror."""+ a, b = make_space(), make_space()+ try:+ a.create()+ b.create()+ where_a = f"/tmp/bench-canary-{uuid.uuid4().hex[:8]}"+ where_b = f"/tmp/bench-canary-{uuid.uuid4().hex[:8]}"+ for s, where in ((a, where_a), (b, where_b)):+ if s.exec(f"git clone --quiet {url} {where}").returncode != 0:+ return {"ran": False}+ h = a.exec(f"echo canary-$$-$(date +%s) | git -C {where_a} hash-object -w --stdin").stdout.strip()+ seen_b = b.exec(f"git -C {where_b} cat-file -e {h}").returncode == 0+ mirror_has = False+ if isinstance(a, SimSpace):+ for name in os.listdir(os.path.join(cua.root, "m")):+ if name.endswith(".git"):+ d = os.path.join(cua.root, "m", name)+ if run(["git", "-C", d, "cat-file", "-e", h]).returncode == 0:+ mirror_has = True+ return {"ran": True, "other_clone_sees_it": seen_b, "mirror_has_it": mirror_has, "ok": not seen_b and not mirror_has}+ finally:+ for s in (a, b):+ s.exec("rm -rf /tmp/bench-canary-*")+ s.delete()+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ ap.add_argument("--mode", choices=("sim", "space"), default="sim")+ ap.add_argument("--repos", default="small,medium", help="small, medium, large or URLs, comma separated")+ ap.add_argument("--cases", default=",".join(CASES))+ ap.add_argument("--n", type=int, default=5, help="trials per repository and case")+ ap.add_argument("--cua", default=os.environ.get("CUA", "cua"))+ ap.add_argument("--home", default=None, help="the Spaces home (default: a temporary one)")+ ap.add_argument("--image", default="linux")+ ap.add_argument("--kind", default="container")+ ap.add_argument("--agent-cmd", default=None, help="a command that returns once the agent is ready")+ ap.add_argument("--canary", action="store_true", help="also check isolation between two clones")+ ap.add_argument("--out", required=True, help="the native result file (JSON)")+ args = ap.parse_args(argv)++ home = args.home or tempfile.mkdtemp(prefix="repo-clone-home-")+ cua = Cua(args.cua, home)+ cases = [c for c in args.cases.split(",") if c]+ bad = [c for c in cases if c not in CASES]+ if bad:+ ap.error(f"unknown case {bad}; cases: {', '.join(CASES)}")+ repos = {}+ for r in [x for x in args.repos.split(",") if x]:+ repos[r] = REPOS.get(r, r)++ def make(case):+ if args.mode == "sim":+ return lambda: SimSpace(cua, case)+ return lambda: RealSpace(cua, case, args.image, args.kind)++ result: dict = {+ "schema": SCHEMA,+ "mode": args.mode,+ "n": args.n,+ "agent_ready": "measured" if args.agent_cmd else "not measured",+ "repos": {},+ }+ for name, url in repos.items():+ entry = {"cases": {}}+ for case in cases:+ samples = []+ for i in range(args.n):+ try:+ prepare(cua, case, url, i == 0)+ except RuntimeError as e:+ samples.append({"ok": False, "error": str(e)})+ continue+ samples.append(trial(make(case), cua, case, url, args.agent_cmd))+ good = [s for s in samples if s.get("ok")]+ entry["cases"][case] = {+ "samples": samples,+ "failed": len(samples) - len(good),+ "stats": {p: stats([s[p] for s in good if s.get(p) is not None]) for p in PHASES},+ }+ print(+ f"{name} {case}: clone p50 {entry['cases'][case]['stats']['clone_ms'].get('p50')} ms, "+ f"total p50 {entry['cases'][case]['stats']['total_ms'].get('p50')} ms, failed {entry['cases'][case]['failed']}",+ file=sys.stderr,+ )+ if args.canary:+ prepare(cua, "hit", url, True)+ entry["canary"] = canary(make("hit"), cua, url)+ result["repos"][name] = {"url": url if name not in REPOS else name, **entry}+ os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)+ with open(args.out, "w") as f:+ json.dump(result, f, indent=2)+ f.write("\n")+ if not args.home:+ shutil.rmtree(home, ignore_errors=True)+ failed = sum(c["failed"] for r in result["repos"].values() for c in r["cases"].values())+ return 1 if failed else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/libs/cua/bench/test_bench_result.py b/libs/cua/bench/test_bench_result.pyindex 2feecf2f0e..36eed6e614 100644--- a/libs/cua/bench/test_bench_result.py+++ b/libs/cua/bench/test_bench_result.py@@ -206,6 +206,46 @@ class Writing(unittest.TestCase):br.core("m", "ms", "p50", None, 3, {}, {})+class RepoClone(unittest.TestCase):+ RUN = {+ "schema": "cua.repo-clone/v1",+ "repos": {+ "small": {+ "url": "small",+ "cases": {+ "off": {"failed": 0, "samples": [{"ok": True, "clone_ms": 1000.0, "total_ms": 1010.0}, {"ok": True, "clone_ms": 1200.0, "total_ms": 1210.0}], "stats": {"clone_ms": {"p50": 1100.0}, "total_ms": {"p50": 1110.0}}},+ "hit": {"failed": 1, "samples": [{"ok": True, "clone_ms": 300.0, "total_ms": 320.0}, {"ok": False, "error": "head"}], "stats": {"clone_ms": {"p50": 300.0}, "total_ms": {"p50": 320.0}}},+ "hit_lease": {"failed": 0, "samples": [{"ok": True, "clone_ms": 200.0, "total_ms": 210.0}], "stats": {"clone_ms": {"p50": 200.0}, "total_ms": {"p50": 210.0}}},+ },+ "canary": {"ran": True, "ok": True},+ }+ },+ }++ def test_the_value_is_the_first_hit_cases_clone_and_failures_are_counted_not_measured(self):+ c, rows = br.convert_repo_clone(self.RUN)+ self.assertEqual((c["metric"], c["value"], c["n"]), ("clone_ms", 300.0, 1))+ self.assertEqual(c["extra"]["failed"], 1)+ self.assertEqual(c["extra"]["small_off_clone_p50_ms"], 1100.0)+ self.assertEqual(c["extra"]["small_canary_ok"], 1)+ self.assertEqual(len(rows), 5)+ self.assertEqual([r["ok"] for r in rows if r["case"] == "hit"], [True, False])++ def test_no_measured_clone_is_no_result(self):+ bad = {"repos": {"small": {"cases": {"hit": {"failed": 2, "samples": [{"ok": False}, {"ok": False}], "stats": {}}}}}}+ with self.assertRaises(br.NoResult):+ br.convert_repo_clone(bad)++ def test_the_bench_stats_are_the_same_percentiles(self):+ sys.path.insert(0, os.path.join(HERE, "repo-clone"))+ import importlib++ rc = importlib.import_module("bench")+ self.assertEqual(rc.stats([1.0, 2.0, 3.0, 4.0]), {"p50": 2.5, "p95": 3.9, "min": 1.0, "max": 4.0})+ self.assertEqual(rc.stats([]), {})+ self.assertEqual(rc.CASES, ("off", "miss", "hit", "hit_lease"))++class Runner(unittest.TestCase):def test_every_bench_has_a_converter_and_its_files(self):for b in cuabench.BENCHES:diff --git a/libs/cua/crates/cua-cli/Cargo.toml b/libs/cua/crates/cua-cli/Cargo.tomlindex 9ba0bb97e6..e3da734d0e 100644--- a/libs/cua/crates/cua-cli/Cargo.toml+++ b/libs/cua/crates/cua-cli/Cargo.toml@@ -43,6 +43,7 @@ cua-image.workspace = truecua-disk.workspace = truecua-vmm = { path = "../cua-vmm" }cua-sandbox-core.workspace = true+cua-repo-cache.workspace = trueimage = { version = "0.25", default-features = false, features = ["png", "jpeg"] }pbjson-types.workspace = truehumantime.workspace = truediff --git a/libs/cua/crates/cua-cli/src/bench_cmd.rs b/libs/cua/crates/cua-cli/src/bench_cmd.rsindex b11cd91cd6..03e26d2a21 100644--- a/libs/cua/crates/cua-cli/src/bench_cmd.rs+++ b/libs/cua/crates/cua-cli/src/bench_cmd.rs@@ -109,6 +109,8 @@ pub(crate) const FILES: &[(&str, &str)] = embed!["fork-batch/bench.py","fork-batch/check.py","fork-batch/baseline.json",+ "repo-clone/bench.py",+ "repo-clone/README.md","channel/run.sh","channel/check.py","channel/baselines/macos-m2max-qemu.json",diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex 503f65eff9..a56f53cb23 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -195,7 +195,10 @@ pub enum HostCmd {cua host config --max-spaces 6# Give the Spaces other machines create here at most 32 GB of memory and# 200 GB of disk in total, and stop each after 8 hours (0: no limit)- cua host config --max-memory 32 --max-disk 200 --max-run-time 480")]+ cua host config --max-memory 32 --max-disk 200 --max-run-time 480+ # Keep no copies of public git repositories on this machine, or at most 2 GB+ cua host config --repo-cache off+ cua host config --repo-cache on --repo-cache-size 2")]Config {/// Share this computer's own desktop: on | off.#[arg(long, value_parser = ["on", "off"])]@@ -221,7 +224,21 @@ pub enum HostCmd {/// it is stopped (0: no limit).#[arg(long, value_name = "MINUTES")]max_run_time: Option<u32>,+ /// The repo cache: on | off. It keeps verified copies of public git+ /// repositories on this machine so a repeat `git clone` in a Space+ /// starts from one (never private repositories, never anything off+ /// this machine's disk).+ #[arg(long, value_parser = ["on", "off"])]+ repo_cache: Option<String>,+ /// The most disk the repo cache may use, in GB (`auto`: the smaller+ /// of 5 GB and a tenth of the free disk). The least recently used+ /// repositories go first.+ #[arg(long, value_name = "GB")]+ repo_cache_size: Option<String>,},+ /// What the repo cache holds, and empty it.+ #[command(subcommand)]+ Cache(HostCacheCmd),/// Show whether this computer is set up, the service, and who is/// connected.#[command(after_help = "Examples:@@ -2201,6 +2218,30 @@ pub async fn run_host(.await}+/// `cua host cache`.+#[derive(Subcommand, Debug, Clone)]+pub enum HostCacheCmd {+ /// What the repo cache holds: repositories, size and what the last week+ /// saved.+ #[command(after_help = "Examples:+ cua host cache status")]+ Status,+ /// Copy one public repository into the cache now, instead of when a Space+ /// first clones it (or bring a copy up to date). A repository that needs+ /// a sign-in is never cached.+ #[command(after_help = "Examples:+ cua host cache fill https://github.com/vitejs/vite")]+ Fill {+ /// The repository's `https` address.+ url: String,+ },+ /// Delete every repository the cache holds. They are copied again the+ /// next time a Space clones them.+ #[command(after_help = "Examples:+ cua host cache clear")]+ Clear,+}+/// [`run_host`] with an explicit stderr stream (warnings under `--json`) and/// the runner `auto` detects on this machine.#[allow(clippy::too_many_arguments)]@@ -2519,8 +2560,18 @@ pub async fn run_host_to(max_memory,max_disk,max_run_time,+ repo_cache,+ repo_cache_size,} => {let on = |v: Option<String>| v.map(|v| v == "on");+ let repo_flags = repo_cache.is_some() || repo_cache_size.is_some();+ if repo_flags {+ crate::repo_cache_cmd::set(+ home,+ repo_cache.as_deref(),+ repo_cache_size.as_deref(),+ )?;+ }let change = cua_host::HostSettingsChange {share_desktop: on(desktop),provide_spaces: on(provide_spaces),@@ -2531,6 +2582,11 @@ pub async fn run_host_to(max_run_minutes: max_run_time,cua_bin: None,};+ if repo_flags && change == cua_host::HostSettingsChange::default() {+ // Only the repo cache changed: that needs no host setup.+ crate::repo_cache_cmd::status(home, json, out);+ return Ok(0);+ }let s = if change == cua_host::HostSettingsChange::default() {host.status().await.map_err(host_err)?} else {@@ -2543,9 +2599,19 @@ pub async fn run_host_to(return Ok(1);} else {render_settings(&s, out);+ for l in crate::repo_cache_cmd::lines(&crate::repo_cache_cmd::cache_for(home)) {+ line(out, l);+ }render_provided(&s, now_ms(), out);}}+ HostCmd::Cache(cmd) => match cmd {+ HostCacheCmd::Status => crate::repo_cache_cmd::status(home, json, out),+ HostCacheCmd::Clear => crate::repo_cache_cmd::clear(home, json, out),+ HostCacheCmd::Fill { url } => {+ return crate::repo_cache_cmd::fill(home, &url, json, out).await;+ }+ },HostCmd::Stop => emit(&host.stop_sharing().await.map_err(host_err)?, json, out)?,HostCmd::Start => emit(&host.start_sharing().await.map_err(host_err)?, json, out)?,HostCmd::Share {diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rsindex 05febcc42b..68ea5935c3 100644--- a/libs/cua/crates/cua-cli/src/lib.rs+++ b/libs/cua/crates/cua-cli/src/lib.rs@@ -56,6 +56,7 @@ pub mod onboard;mod persistent_cmd;pub mod prewarm;mod providers;+mod repo_cache_cmd;mod resources_view;mod risky;mod runs;diff --git a/libs/cua/crates/cua-cli/src/repo_cache_cmd.rs b/libs/cua/crates/cua-cli/src/repo_cache_cmd.rsnew file mode 100644index 0000000000..38afebb88a--- /dev/null+++ b/libs/cua/crates/cua-cli/src/repo_cache_cmd.rs@@ -0,0 +1,256 @@+//! `cua host config --repo-cache` / `--repo-cache-size` and `cua host cache`:+//! the repo cache's settings, what it holds, and clearing it.++use crate::util::line;+use cua_repo_cache::{Config, RepoCache};+use cua_sandbox_core::settings::{Settings, key};+use cua_sdk::CuaError;+use std::io::Write;+use std::path::Path;++/// The cache under `home` with the settings in `home`'s config file (and+/// the environment).+pub fn cache_for(home: &Path) -> RepoCache {+ let (enabled, cap_bytes) =+ Settings::load_with(home.join("config.toml"), |k| std::env::var(k).ok())+ .map(|s| s.repo_cache())+ .unwrap_or((true, None));+ RepoCache::new(+ home.join("job-cache").join("repos"),+ Config { enabled, cap_bytes },+ )+}++/// Saves `--repo-cache` and `--repo-cache-size` (a missing one keeps its+/// value).+pub fn set(home: &Path, on: Option<&str>, size: Option<&str>) -> Result<(), CuaError> {+ let mut s = Settings::load_with(home.join("config.toml"), |k| std::env::var(k).ok())+ .map_err(|e| CuaError::InvalidArgument(e.to_string()))?;+ for (name, v) in [("cache.repos", on), ("cache.repos_size_gb", size)] {+ if let Some(v) = v {+ let k = key(name).map_err(|e| CuaError::Internal(e.to_string()))?;+ s.set(k, v)+ .map_err(|e| CuaError::InvalidArgument(e.to_string()))?;+ }+ }+ Ok(())+}++/// What the cache holds, in plain words.+pub fn lines(c: &RepoCache) -> Vec<String> {+ let st = c.status();+ if !st.enabled {+ return vec![+ "repo cache: off".to_string(),+ format!(" {}", st.size_line()),+ ];+ }+ vec![+ "repo cache: on".to_string(),+ format!(" {}", st.size_line()),+ format!(" {}", st.week_line()),+ ]+}++/// The status as JSON.+pub fn json(c: &RepoCache) -> serde_json::Value {+ let s = c.status();+ serde_json::json!({+ "enabled": s.enabled,+ "repos": s.repos,+ "bytes": s.bytes,+ "cap_bytes": s.cap_bytes,+ "hits_last_week": s.hits,+ "misses_last_week": s.misses,+ "seconds_saved_last_week": s.seconds_saved,+ "bytes_saved_last_week": s.bytes_saved,+ })+}++/// `cua host cache status`.+pub fn status(home: &Path, as_json: bool, out: &mut dyn Write) {+ let c = cache_for(home);+ c.sync_config();+ if as_json {+ line(out, json(&c).to_string());+ } else {+ for l in lines(&c) {+ line(out, l);+ }+ }+}++/// `cua host cache fill URL`: exit 0 when the repository is in the cache+/// now, 1 when it is not (and why, in words).+pub async fn fill(+ home: &Path,+ url: &str,+ as_json: bool,+ out: &mut dyn Write,+) -> Result<i32, CuaError> {+ use cua_repo_cache::{Outcome, Reason};+ let repo = cua_repo_cache::url::parse(url).map_err(|_| {+ CuaError::InvalidArgument(+ "the repo cache holds public repositories by their plain https address \+ (no user name or token in it, no port)"+ .into(),+ )+ })?;+ let c = cache_for(home);+ if let Err(e) = c.prepare() {+ return Err(CuaError::Internal(format!("the repo cache folder: {e}")));+ }+ let outcome = c.ensure(&repo).await;+ let (held, said) = match outcome {+ Outcome::Filled { bytes, secs } => (+ true,+ format!(+ "Cached: {} in {secs:.1} seconds.",+ cua_repo_cache::size_words(bytes)+ ),+ ),+ Outcome::Refreshed { changed } => (+ true,+ if changed {+ "Brought the cached copy up to date.".to_string()+ } else {+ "The cached copy is already up to date.".to_string()+ },+ ),+ Outcome::Skipped(r) => (+ false,+ match r {+ Reason::Disabled => "The repo cache is off (`cua host config --repo-cache on`).",+ Reason::NoGit => "git is not installed on this machine.",+ Reason::UnsupportedUrl | Reason::HostNotPublic => {+ "Only repositories on a public https host are cached."+ }+ Reason::Private => {+ "Not cached: the repository needs a sign-in, so it is not public."+ }+ Reason::Unreachable => "Not cached: the repository could not be reached.",+ Reason::TooBig => {+ "Not cached: the repository is larger than the cache's size limit."+ }+ Reason::CacheFull => {+ "Not cached: no room, and everything in the cache was used a moment ago."+ }+ Reason::DiskFull => "Not cached: this machine's disk has no room for it.",+ Reason::VerifyFailed => "Not cached: the copy did not pass its checks.",+ Reason::FillFailed => "Not cached: the copy could not be made.",+ }+ .to_string(),+ ),+ };+ if as_json {+ let reason = match outcome {+ Outcome::Skipped(r) => r.word(),+ _ => "none",+ };+ line(+ out,+ serde_json::json!({"cached": held, "reason": reason, "message": said}).to_string(),+ );+ } else {+ line(out, said);+ }+ Ok(if held { 0 } else { 1 })+}++/// `cua host cache clear`.+pub fn clear(home: &Path, as_json: bool, out: &mut dyn Write) {+ let c = cache_for(home);+ let before = c.status();+ c.clear();+ if as_json {+ line(+ out,+ serde_json::json!({"cleared": before.repos, "freed_bytes": before.bytes}).to_string(),+ );+ } else if before.repos == 0 {+ line(out, "The repo cache is already empty.");+ } else {+ line(+ out,+ format!(+ "Cleared the repo cache: {} repo{}, {}.",+ before.repos,+ if before.repos == 1 { "" } else { "s" },+ cua_repo_cache::size_words(before.bytes)+ ),+ );+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn text(f: impl FnOnce(&mut Vec<u8>)) -> String {+ let mut out = Vec::new();+ f(&mut out);+ String::from_utf8(out).unwrap()+ }++ #[test]+ fn the_flags_save_to_the_config_file_and_show_in_the_status() {+ let home = tempfile::tempdir().unwrap();+ let on = text(|o| status(home.path(), false, o));+ assert!(on.starts_with("repo cache: on\n"), "{on}");+ assert!(on.contains("Repos: 0, 0 MB of "), "{on}");+ set(home.path(), Some("off"), Some("2")).unwrap();+ let toml = std::fs::read_to_string(home.path().join("config.toml")).unwrap();+ assert!(+ toml.contains("repos = \"off\"") && toml.contains("repos_size_gb = \"2\""),+ "{toml}"+ );+ let off = text(|o| status(home.path(), false, o));+ assert_eq!(off, "repo cache: off\n Repos: 0, 0 MB of 2 GB\n");+ let j: serde_json::Value =+ serde_json::from_str(&text(|o| status(home.path(), true, o))).unwrap();+ assert_eq!(+ (j["enabled"].as_bool(), j["cap_bytes"].as_u64()),+ (Some(false), Some(2 << 30))+ );+ // A bad value is refused with the setting's name, and nothing changes.+ let e = set(home.path(), None, Some("lots")).unwrap_err();+ assert!(e.to_string().contains("cache.repos_size_gb"), "{e}");+ }++ #[tokio::test]+ async fn fill_refuses_what_the_cache_never_holds_and_says_why_when_it_is_off() {+ let home = tempfile::tempdir().unwrap();+ let mut out = Vec::new();+ for bad in [+ "http://github.com/o/r",+ "https://[email protected]/o/r",+ "[email protected]:o/r.git",+ ] {+ let e = fill(home.path(), bad, false, &mut out).await.unwrap_err();+ assert!(+ e.to_string()+ .contains("public repositories by their plain https address"),+ "{bad}: {e}"+ );+ }+ set(home.path(), Some("off"), None).unwrap();+ let rc = fill(home.path(), "https://github.com/o/r", false, &mut out)+ .await+ .unwrap();+ assert_eq!(rc, 1);+ assert_eq!(+ String::from_utf8(out).unwrap(),+ "The repo cache is off (`cua host config --repo-cache on`).\n"+ );+ }++ #[test]+ fn clear_says_what_it_removed() {+ let home = tempfile::tempdir().unwrap();+ let first = text(|o| clear(home.path(), false, o));+ assert_eq!(first, "The repo cache is already empty.\n");+ let j: serde_json::Value =+ serde_json::from_str(&text(|o| clear(home.path(), true, o))).unwrap();+ assert_eq!(j["cleared"], 0);+ }+}diff --git a/libs/cua/crates/cua-daemon/src/local.rs b/libs/cua/crates/cua-daemon/src/local.rsindex 9c6274cf01..bd6363d4e6 100644--- a/libs/cua/crates/cua-daemon/src/local.rs+++ b/libs/cua/crates/cua-daemon/src/local.rs@@ -497,6 +497,33 @@ async fn resolve_placement_inner(})}+/// Set once an engine refused a start because of the repo cache's mount:+/// the daemon offers it no more (until it restarts).+static REPO_CACHE_MOUNT_REFUSED: std::sync::atomic::AtomicBool =+ std::sync::atomic::AtomicBool::new(false);++/// Whether `e` (a refused start of `s`) is about the repo cache's mount.+fn is_repo_cache_mount_error(s: &StartSpec, e: &VmmError) -> bool {+ if !s+ .mounts+ .iter()+ .any(|m| m.guest == cua_sandbox_core::repo_cache::GUEST_ROOT)+ {+ return false;+ }+ let text = e.to_string().to_ascii_lowercase();+ [+ "mount",+ "bind",+ "not shared",+ "file sharing",+ "denied",+ "no such file",+ ]+ .iter()+ .any(|w| text.contains(w))+}+fn os_of(s: &str) -> GuestOs {match s.to_ascii_lowercase().as_str() {"macos" | "darwin" => GuestOs::Macos,@@ -868,6 +895,27 @@ impl VmmLocal {/// The engine local Linux Spaces use ([`managed::choose`]): this Mac's/// own, or the built-in runtime. Chosen on first use, without booting/// anything.+ /// The repo cache as a read-only mount of a Linux container Space (see+ /// `cua-repo-cache`): only where the engine can bind this machine's+ /// directory, and only while the cache is on.+ async fn repo_cache_mount(&self, backend: BackendKind, os: &str) -> Option<cua_vmm::Mount> {+ if backend != BackendKind::Container+ || os_of(os) != GuestOs::Linux+ || REPO_CACHE_MOUNT_REFUSED.load(std::sync::atomic::Ordering::SeqCst)+ {+ return None;+ }+ let root = cua_sandbox_core::repo_cache::current().mount_source()?;+ // The built-in runtime's VM shares only cua's job directories (the+ // cache lives in one), and not before it booted sharing them.+ if let Ok(Engine::Builtin(_)) = self.engine().await+ && !(managed::is_shared(&root) && (!managed::running() || managed::shares_job_dirs()))+ {+ return None;+ }+ Some(cua_sandbox_core::repo_cache::mount(root))+ }+async fn engine(&self) -> std::result::Result<Engine, VmmError> {let source = LinuxSource::current();let mut slot = self.container.lock().await;@@ -1659,6 +1707,11 @@ impl VmmLocal {s.egress = spec.egress.clone();s.disk_size_gb = spec.disk_size_gb;s.mounts = spec.mounts.clone();+ if let Some(m) = self.repo_cache_mount(p.backend, &spec.os).await+ && !s.mounts.iter().any(|x| x.guest == m.guest)+ {+ s.mounts.push(m);+ }// The layers from the manifest: progress knows the total, and the// layers the engine already has, from the first byte.s.pull_layers = r@@ -1889,7 +1942,7 @@ impl LocalRuntime for VmmLocal {) -> RuntimeResult<(LocalInstance, Option<cua_sandbox_core::ImageInfo>)> {let started = std::time::Instant::now();let Prepared {- spec: s,+ spec: mut s,backend,rt,image,@@ -1931,7 +1984,20 @@ impl LocalRuntime for VmmLocal {));}let start_at = std::time::Instant::now();- let inst = rt.start(&s).await.map_err(rt_err)?;+ let inst = match rt.start(&s).await {+ Ok(i) => i,+ // The repo cache is an extra: a start that this engine refuses+ // because of its mount (a directory it does not share) runs+ // again without it, and the daemon stops offering it.+ Err(e) if is_repo_cache_mount_error(&s, &e) => {+ tracing::warn!(error = %e, "repo cache mount refused; starting without it");+ REPO_CACHE_MOUNT_REFUSED.store(true, std::sync::atomic::Ordering::SeqCst);+ s.mounts+ .retain(|m| m.guest != cua_sandbox_core::repo_cache::GUEST_ROOT);+ rt.start(&s).await.map_err(rt_err)?+ }+ Err(e) => return Err(rt_err(e)),+ };// Behind a port forward (the probe on cua-spacesd's port says so),// ready once it serves an authenticated call with the Space's// token: see `guest_identity::wait_accepts`.diff --git a/libs/cua/crates/cua-daemon/src/server.rs b/libs/cua/crates/cua-daemon/src/server.rsindex ca7c2f4c39..1250b664e6 100644--- a/libs/cua/crates/cua-daemon/src/server.rs+++ b/libs/cua/crates/cua-daemon/src/server.rs@@ -213,6 +213,30 @@ const MAINTENANCE_EVERY: Duration = Duration::from_secs(3600);/// once a minute after start, then hourly while no request is in flight/// and none arrived for five minutes. `CUA_DAEMON_MAINTENANCE=0` turns it/// off.+/// How often the repo cache is tidied and its mirrors refreshed, and how+/// old a mirror used in the last week may get before it is.+const REPO_CACHE_EVERY: Duration = Duration::from_secs(15 * 60);+const REPO_CACHE_REFRESH_AFTER: Duration = Duration::from_secs(60 * 60);++/// Keeps the repo cache within its cap and its mirrors up to date, in the+/// background and one repository at a time (`cua-repo-cache`). Nothing+/// happens while the cache is off.+async fn repo_cache_loop(mut shutdown: watch::Receiver<bool>) {+ let mut next = tokio::time::Instant::now() + Duration::from_secs(120);+ loop {+ tokio::select! {+ _ = shutdown.changed() => return,+ _ = tokio::time::sleep_until(next) => {}+ }+ let cache = cua_sandbox_core::repo_cache::current();+ tokio::select! {+ _ = shutdown.changed() => return,+ () = cache.maintain(REPO_CACHE_REFRESH_AFTER) => {}+ }+ next = tokio::time::Instant::now() + REPO_CACHE_EVERY;+ }+}+async fn maintenance_loop(shared: Arc<Shared>, mut shutdown: watch::Receiver<bool>) {use std::sync::atomic::Ordering::SeqCst;let Ok(vmm) = shared.runtime.vmm().cloned() else {@@ -672,6 +696,7 @@ pub async fn start(runtime: Runtime, config: ServerConfig) -> Result<DaemonHandlshared.clone(),shared.shutdown.subscribe(),)));+ tasks.push(tokio::spawn(repo_cache_loop(shared.shutdown.subscribe())));}// The automatic cloud sweep (`CUA_CLOUD_SWEEP_SECS`, 0: off).#[cfg(feature = "byoc")]diff --git a/libs/cua/crates/cua-repo-cache/Cargo.toml b/libs/cua/crates/cua-repo-cache/Cargo.tomlnew file mode 100644index 0000000000..85261c4f13--- /dev/null+++ b/libs/cua/crates/cua-repo-cache/Cargo.toml@@ -0,0 +1,25 @@+[package]+name = "cua-repo-cache"+description = "A transparent, size-bounded cache of public git repositories owned by the cua daemon: bare mirrors on this machine's disk, a read-only mount and a git remote helper that give a Space's plain `git clone` the mirror's objects, with the remote's tip always checked."+version.workspace = true+edition.workspace = true+rust-version.workspace = true+authors.workspace = true+license.workspace = true+repository.workspace = true++[dependencies]+cua-home.workspace = true+cua-telemetry.workspace = true+hex.workspace = true+libc = "0.2"+serde.workspace = true+serde_json.workspace = true+sha2.workspace = true+tokio = { workspace = true, features = ["fs", "io-util", "process", "rt", "sync", "time", "macros"] }+tracing.workspace = true+url.workspace = true++[dev-dependencies]+tempfile.workspace = true+tokio = { workspace = true, features = ["full"] }diff --git a/libs/cua/crates/cua-repo-cache/assets/git-remote-cuarepo b/libs/cua/crates/cua-repo-cache/assets/git-remote-cuareponew file mode 100644index 0000000000..f1765ecb9e--- /dev/null+++ b/libs/cua/crates/cua-repo-cache/assets/git-remote-cuarepo@@ -0,0 +1,133 @@+#!/bin/sh+# git-remote-cuarepo: Cua's repo cache as a git remote helper.+#+# Installed in a Space by the Cua daemon (never by the agent). The system git+# config in the read-only cache mount rewrites the URL of a repo the daemon+# holds a verified mirror of to `cuarepo::<key>::<url>`, so a plain+# `git clone <url>` runs this helper. The helper only ever reads the mount.+#+# fresh clone, mirror verified within the lease: the mirror's packs are+# copied into the clone and git talks to `git upload-pack` on the mirror+# (no network).+# fresh clone otherwise: the mirror is an alternate while git runs the real+# `git remote-https`, so only what the remote has on top of the mirror is+# downloaded and the remote's own tip is what the clone gets; the mirror's+# packs are then copied into the clone and the alternate is removed+# (`--reference --dissociate`), so the clone never depends on the mirror.+# anything else (no mirror, a mirror that fails its checks, a repo that+# already has objects, push): plain `git remote-https`, byte for byte.+#+# Every step that fails falls back to the plain path.++remote=$1+spec=$2+key=${spec%%::*}+url=${spec#*::}+root=${CUA_REPO_CACHE_ROOT:-/cua/repo-cache}+log=${CUA_REPO_CACHE_LOG:-/tmp/.cua-repo-cache.log}+lease=${CUA_REPO_CACHE_LEASE:-20}+mirror=$root/m/$key.git+started=$(date +%s 2>/dev/null || echo 0)++plain() {+ exec git remote-https "$remote" "$url"+}++note() {+ printf '%s %s %s %s\n' "$(date +%s 2>/dev/null || echo 0)" "$1" "$key" "$2" >>"$log" 2>/dev/null || :+}++# Only a 16 hex digit key names a mirror.+case $key in+ *[!0-9a-f]*) plain ;;+esac+[ ${#key} -eq 16 ] || plain++# A clone that is just starting: git's own directory has no objects yet.+[ -n "$GIT_DIR" ] && [ -d "$GIT_DIR/objects" ] || plain+[ -z "$(ls "$GIT_DIR/objects" 2>/dev/null | grep -v -E '^(info|pack)$')" ] || plain+[ -z "$(ls "$GIT_DIR/objects/pack" 2>/dev/null)" ] || plain+[ -f "$GIT_DIR/shallow" ] && plain++# The daemon's verification stamp: the mirror's url, and the size of every+# pack it verified. Anything missing or different: plain.+[ -f "$root/m/$key.ok" ] && [ -d "$mirror/objects" ] || plain+recorded=$(cat "$root/m/$key.url" 2>/dev/null)+got=${url%/}+got=${got%.git}+got=${got%/}+[ -n "$recorded" ] && [ "$got" = "$recorded" ] || plain+packs=0+while read -r size name; do+ [ -n "$name" ] || continue+ actual=$(wc -c <"$mirror/objects/pack/$name" 2>/dev/null) || plain+ [ "$((actual + 0))" -eq "$size" ] 2>/dev/null || { note skipped 0; plain; }+ packs=$((packs + 1))+done <"$root/m/$key.ok"+[ "$packs" -gt 0 ] || plain++# From here the mirror is an alternate of the clone.+mkdir -p "$GIT_DIR/objects/info" 2>/dev/null || plain+printf '%s\n' "$mirror/objects" >"$GIT_DIR/objects/info/alternates" 2>/dev/null || plain++# Copy the mirror's packs into the clone and let go of the alternate. A+# shallow or filtered clone repacks instead (it must not take every object).+dissociate() {+ if [ -f "$GIT_DIR/shallow" ] || [ -f "$GIT_DIR/objects/info/promisor" ] || git -C "$GIT_DIR" config --get remote.origin.promisor >/dev/null 2>&1; then+ git --git-dir="$GIT_DIR" repack -a -d -q 2>/dev/null && rm -f "$GIT_DIR/objects/info/alternates" && return 0+ return 1+ fi+ dst=$GIT_DIR/objects/pack+ mkdir -p "$dst" || return 1+ ok=1+ while read -r size name; do+ [ -n "$name" ] || continue+ base=${name%.pack}+ if cp "$mirror/objects/pack/$base.pack" "$dst/tmp_cuarepo_$$_$base.pack" 2>/dev/null \+ && cp "$mirror/objects/pack/$base.idx" "$dst/tmp_cuarepo_$$_$base.idx" 2>/dev/null; then+ mv "$dst/tmp_cuarepo_$$_$base.pack" "$dst/$base.pack" && mv "$dst/tmp_cuarepo_$$_$base.idx" "$dst/$base.idx" || ok=0+ else+ ok=0+ fi+ rm -f "$dst/tmp_cuarepo_$$_$base.pack" "$dst/tmp_cuarepo_$$_$base.idx" 2>/dev/null+ done <"$root/m/$key.ok"+ [ $ok -eq 1 ] || return 1+ rm -f "$GIT_DIR/objects/info/alternates"+}++finish() {+ rc=$1+ kind=$2+ if [ "$rc" -ne 0 ]; then+ rm -f "$GIT_DIR/objects/info/alternates" 2>/dev/null+ note failed 0+ exit "$rc"+ fi+ if dissociate; then+ now=$(date +%s 2>/dev/null || echo 0)+ note "$kind" "$((now - started))"+ else+ # Could not copy (a full disk): the clone keeps the alternate, which+ # works while the mount does.+ note kept 0+ fi+ exit 0+}++fresh=$(cat "$root/m/$key.fresh" 2>/dev/null || echo 0)+now=$(date +%s 2>/dev/null || echo 0)+if [ "$((fresh + 0))" -le "$now" ] 2>/dev/null && [ "$((now - fresh))" -lt "$lease" ] 2>/dev/null; then+ read -r _caps+ printf 'connect\n\n'+ read -r service+ case $service in+ "connect git-upload-pack"*) ;;+ *) rm -f "$GIT_DIR/objects/info/alternates"; exit 1 ;;+ esac+ printf '\n'+ git upload-pack "$mirror"+ finish $? hit_lease+fi++git remote-https "$remote" "$url"+finish $? hit_checkeddiff --git a/libs/cua/crates/cua-repo-cache/src/fill.rs b/libs/cua/crates/cua-repo-cache/src/fill.rsnew file mode 100644index 0000000000..7f887083bd--- /dev/null+++ b/libs/cua/crates/cua-repo-cache/src/fill.rs@@ -0,0 +1,661 @@+//! Filling, refreshing, verifying and evicting mirrors.++use std::path::{Path, PathBuf};+use std::time::{Duration, Instant};++use crate::git::{self, GitError};+use crate::store::{self, Entry, Pack, now_ms};+use crate::url::{self, RepoUrl};+use crate::{EVICTION_GRACE, RepoCache, shim, state};++const LS_REMOTE_LIMIT: Duration = Duration::from_secs(25);+const FILL_LIMIT: Duration = Duration::from_secs(20 * 60);+const VERIFY_LIMIT: Duration = Duration::from_secs(10 * 60);+/// A repository found private is not asked again for this long; one that+/// could not be reached, for less.+const PRIVATE_FOR: Duration = Duration::from_secs(30 * 60);+const UNREACHABLE_FOR: Duration = Duration::from_secs(60);+/// A mirror confirmed this recently is not asked about again.+const CONFIRMED_FOR_SECS: u64 = 5;+/// Packs a mirror may hold before it is repacked into one.+const MAX_PACKS: usize = 8;+/// Free disk the cache leaves alone.+const KEEP_FREE_BYTES: u64 = 1 << 30;++/// What [`RepoCache::ensure`] did.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Outcome {+ /// A new mirror: its size, and what the network clone took.+ Filled { bytes: u64, secs: f64 },+ /// An existing mirror, checked against the remote's refs: whether the+ /// remote had changed.+ Refreshed { changed: bool },+ /// Nothing cached, and why.+ Skipped(Reason),+}++/// Why a repository is not cached or a mirror was not used: a fixed list+/// (these are the words telemetry sends).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Reason {+ Disabled,+ NoGit,+ UnsupportedUrl,+ HostNotPublic,+ /// Needs a credential, or is not found without one.+ Private,+ Unreachable,+ /// Larger than the cache may hold.+ TooBig,+ /// No room, with everything in it recently used.+ CacheFull,+ DiskFull,+ VerifyFailed,+ FillFailed,+}++impl Reason {+ /// The fixed word.+ pub fn word(self) -> &'static str {+ match self {+ Reason::Disabled => "disabled",+ Reason::NoGit => "no_git",+ Reason::UnsupportedUrl => "unsupported_url",+ Reason::HostNotPublic => "host_not_public",+ Reason::Private => "private",+ Reason::Unreachable => "unreachable",+ Reason::TooBig => "too_big",+ Reason::CacheFull => "cache_full",+ Reason::DiskFull => "disk_full",+ Reason::VerifyFailed => "verify_failed",+ Reason::FillFailed => "fill_failed",+ }+ }+}++/// The refs of a remote, as `ls-remote` lists them.+#[derive(Debug, Default, PartialEq, Eq)]+struct Refs {+ /// `refs/heads/x` and `refs/tags/x` with their object ids (sorted).+ refs: Vec<(String, String)>,+ /// What `HEAD` points at (`refs/heads/main`), when the remote says.+ head: Option<String>,+}++fn parse_ls_remote(out: &str) -> Refs {+ let mut r = Refs::default();+ for l in out.lines() {+ if let Some(rest) = l.strip_prefix("ref: ") {+ if let Some((target, name)) = rest.split_once('\t')+ && name == "HEAD"+ {+ r.head = Some(target.to_string());+ }+ continue;+ }+ let Some((oid, name)) = l.split_once('\t') else {+ continue;+ };+ if name.ends_with("^{}") {+ continue;+ }+ if (name.starts_with("refs/heads/") || name.starts_with("refs/tags/"))+ && oid.len() >= 40+ && oid.bytes().all(|b| b.is_ascii_hexdigit())+ {+ r.refs.push((name.to_string(), oid.to_string()));+ }+ }+ r.refs.sort();+ r.refs.dedup();+ r+}++fn skip(c: &RepoCache, r: Reason) -> Outcome {+ tracing::debug!(reason = r.word(), root = %c.root().display(), "repo cache: skipped");+ Outcome::Skipped(r)+}++pub(crate) async fn ensure(c: &RepoCache, repo: &RepoUrl) -> Outcome {+ if !c.cfg.enabled {+ return skip(c, Reason::Disabled);+ }+ let Some(bin) = git::binary() else {+ return skip(c, Reason::NoGit);+ };+ let cap = c.cap_bytes();+ if cap == 0 {+ return skip(c, Reason::CacheFull);+ }+ let neg_key = (c.root.clone(), repo.key.clone());+ if let Ok(n) = state().negative.lock()+ && n.get(&neg_key).is_some_and(|until| *until > Instant::now())+ {+ return skip(c, Reason::Private);+ }+ if c.prepare().is_err() {+ return skip(c, Reason::DiskFull);+ }+ let _gate = state().gate.lock().await;++ // Confirmed a moment ago (another clone of the same repository).+ if store::entry(&c.root, &repo.key).is_some()+ && std::fs::read_to_string(store::side(&c.root, &repo.key, "fresh"))+ .ok()+ .and_then(|t| t.trim().parse::<u64>().ok())+ .is_some_and(|s| (now_ms() / 1000).saturating_sub(s) < CONFIRMED_FOR_SECS)+ {+ return Outcome::Refreshed { changed: false };+ }++ if c.policy.check_host && !url::host_is_public(&repo.host).await {+ return skip(c, Reason::HostNotPublic);+ }+ let home = store::home_dir(&c.root);+ let remote = match ls_remote(&bin, &home, c.policy.allow, repo).await {+ Ok(r) => r,+ Err(reason) => {+ let for_ = if reason == Reason::Private {+ PRIVATE_FOR+ } else {+ UNREACHABLE_FOR+ };+ if let Ok(mut n) = state().negative.lock() {+ n.insert(neg_key, Instant::now() + for_);+ }+ // A mirror of a repository that turned private is not served.+ if reason == Reason::Private && store::entry(&c.root, &repo.key).is_some() {+ store::drop_entry(&c.root, &repo.key);+ let _ = shim::write_config(&c.root);+ }+ return skip(c, reason);+ }+ };+ if remote.refs.is_empty() {+ // An empty repository: nothing to mirror.+ return skip(c, Reason::FillFailed);+ }++ match store::entry(&c.root, &repo.key) {+ Some(e) => refresh(c, &bin, repo, e, &remote).await,+ None => fill(c, &bin, repo, &remote, cap).await,+ }+}++async fn ls_remote(bin: &Path, home: &Path, allow: &str, repo: &RepoUrl) -> Result<Refs, Reason> {+ let mut cmd = git::command(bin, home, allow);+ cmd.args([+ "ls-remote",+ "--symref",+ "--",+ &repo.url,+ "HEAD",+ "refs/heads/*",+ "refs/tags/*",+ ]);+ match git::run(cmd, LS_REMOTE_LIMIT).await {+ Ok(r) if r.ok => Ok(parse_ls_remote(&r.stdout)),+ Ok(r) => {+ let e = r.stderr.to_ascii_lowercase();+ let needs_credentials = [+ "authentication failed",+ "could not read username",+ "terminal prompts disabled",+ "repository not found",+ "returned error: 40",+ "invalid credentials",+ ]+ .iter()+ .any(|w| e.contains(w));+ Err(if needs_credentials {+ Reason::Private+ } else {+ Reason::Unreachable+ })+ }+ Err(GitError::Missing) => Err(Reason::NoGit),+ Err(GitError::Spawn(why)) => {+ tracing::debug!(%why, "repo cache: git could not be started");+ Err(Reason::Unreachable)+ }+ Err(GitError::TimedOut) => Err(Reason::Unreachable),+ }+}++async fn local_refs(bin: &Path, home: &Path, allow: &str, dir: &Path) -> Option<Refs> {+ let mut cmd = git::command(bin, home, allow);+ cmd.arg("-C").arg(dir).args([+ "for-each-ref",+ "--format=%(objectname)\t%(refname)",+ "refs/heads",+ "refs/tags",+ ]);+ let r = git::run(cmd, Duration::from_secs(60)).await.ok()?;+ if !r.ok {+ return None;+ }+ let mut refs: Vec<(String, String)> = r+ .stdout+ .lines()+ .filter_map(|l| {+ let (oid, name) = l.split_once('\t')?;+ Some((name.to_string(), oid.to_string()))+ })+ .collect();+ refs.sort();+ // A tag object's own id is what `for-each-ref` lists and what `ls-remote`+ // lists (the peeled `^{}` lines are left out of both).+ Some(Refs { refs, head: None })+}++fn random_name() -> String {+ format!("{:016x}", rand_u64())+}++fn rand_u64() -> u64 {+ // No `rand` dependency for one unpredictable-enough directory name.+ use std::hash::{BuildHasher as _, Hasher as _};+ let mut h = std::collections::hash_map::RandomState::new().build_hasher();+ h.write_u128(u128::from(now_ms()) << 32 | u128::from(std::process::id()));+ h.finish()+}++async fn fill(c: &RepoCache, bin: &Path, repo: &RepoUrl, remote: &Refs, cap: u64) -> Outcome {+ let home = store::home_dir(&c.root);+ if store::free_bytes(&c.root).is_some_and(|f| f < KEEP_FREE_BYTES) {+ return skip(c, Reason::DiskFull);+ }+ let tmp_root = store::tmp_dir(&c.root);+ if std::fs::create_dir_all(&tmp_root).is_err() {+ return skip(c, Reason::DiskFull);+ }+ let tmp = tmp_root.join(format!("{}.git", random_name()));+ let started = Instant::now();+ let mut cmd = git::command(bin, &home, c.policy.allow);+ // Packs only: a Space copies packs, never loose objects.+ cmd.args(["-c", "transfer.unpackLimit=1", "-c", "fetch.unpackLimit=1"])+ .args(["clone", "--bare", "--quiet", "--"])+ .arg(&repo.url)+ .arg(&tmp);+ // The cache's cap is the most one repository may take.+ let budget = cap.saturating_sub(held_by_others(c, &repo.key));+ let ran = run_bounded(cmd, &tmp, budget, FILL_LIMIT).await;+ let secs = started.elapsed().as_secs_f64();+ match ran {+ Ok(true) => {}+ Ok(false) => {+ let _ = std::fs::remove_dir_all(&tmp);+ return skip(c, Reason::FillFailed);+ }+ Err(r) => {+ let _ = std::fs::remove_dir_all(&tmp);+ return skip(c, r);+ }+ }+ // Later refreshes fetch heads and tags only.+ for (k, v) in [+ ("remote.origin.fetch", "+refs/heads/*:refs/heads/*"),+ ("transfer.unpackLimit", "1"),+ ("fetch.unpackLimit", "1"),+ ("gc.auto", "0"),+ ] {+ let mut cmd = git::command(bin, &home, c.policy.allow);+ cmd.arg("-C").arg(&tmp).args(["config", k, v]);+ let _ = git::run(cmd, Duration::from_secs(30)).await;+ }+ let verified = verify(c, bin, &tmp, true).await;+ let (head, packs) = match verified {+ Ok(v) => v,+ Err(r) => {+ let _ = std::fs::remove_dir_all(&tmp);+ return skip(c, r);+ }+ };+ let bytes = store::dir_size(&tmp);+ if !make_room(c, bytes, &repo.key, cap) {+ let _ = std::fs::remove_dir_all(&tmp);+ return skip(c, Reason::CacheFull);+ }+ let dest = store::mirror_dir(&c.root, &repo.key);+ // A damaged leftover of the same key is replaced.+ if dest.exists() {+ store::drop_entry(&c.root, &repo.key);+ }+ if std::fs::rename(&tmp, &dest).is_err() {+ let _ = std::fs::remove_dir_all(&tmp);+ return skip(c, Reason::DiskFull);+ }+ let _ = remote;+ let now = now_ms();+ let entry = Entry {+ url: repo.url.clone(),+ key: repo.key.clone(),+ filled_ms: now,+ refreshed_ms: now,+ used_ms: now,+ bytes,+ fill_secs: secs,+ head,+ packs,+ };+ if store::publish(&c.root, &entry, true).is_err() {+ store::drop_entry(&c.root, &repo.key);+ return skip(c, Reason::DiskFull);+ }+ let _ = shim::write_config(&c.root);+ Outcome::Filled { bytes, secs }+}++fn held_by_others(c: &RepoCache, key: &str) -> u64 {+ store::entries(&c.root)+ .iter()+ .filter(|e| e.key != key)+ .map(|e| e.bytes)+ .sum()+}++/// Runs `cmd` (which writes `dir`) until it ends, stopping it when `dir`+/// grows past `budget` or `limit` passes. `Ok(true)`: it succeeded.+async fn run_bounded(+ mut cmd: tokio::process::Command,+ dir: &Path,+ budget: u64,+ limit: Duration,+) -> Result<bool, Reason> {+ use std::process::Stdio;+ cmd.stdout(Stdio::null()).stderr(Stdio::null());+ let mut child = cmd.spawn().map_err(|e| {+ if e.kind() == std::io::ErrorKind::NotFound {+ Reason::NoGit+ } else {+ Reason::FillFailed+ }+ })?;+ let deadline = Instant::now() + limit;+ loop {+ tokio::select! {+ status = child.wait() => {+ return Ok(status.is_ok_and(|s| s.success()));+ }+ () = tokio::time::sleep(Duration::from_millis(400)) => {+ if store::dir_size(dir) > budget {+ let _ = child.kill().await;+ return Err(Reason::TooBig);+ }+ if Instant::now() > deadline {+ let _ = child.kill().await;+ return Err(Reason::FillFailed);+ }+ }+ }+ }+}++/// Frees what `needed` bytes more (for `key`) take beyond `cap` by dropping+/// the least recently used mirrors that were not used within the grace+/// period. `false` when that is not enough.+fn make_room(c: &RepoCache, needed: u64, key: &str, cap: u64) -> bool {+ let others = held_by_others(c, key);+ if needed > cap {+ return false;+ }+ if others + needed <= cap {+ return true;+ }+ let mut held = others;+ let now = now_ms();+ for e in store::entries(&c.root) {+ if held + needed <= cap {+ break;+ }+ if e.key == key || now.saturating_sub(e.used_ms) < EVICTION_GRACE.as_millis() as u64 {+ continue;+ }+ store::drop_entry(&c.root, &e.key);+ held = held.saturating_sub(e.bytes);+ }+ let _ = shim::write_config(&c.root);+ held + needed <= cap+}++/// Drops least recently used mirrors until the cache fits its cap.+pub(crate) fn enforce_cap(c: &RepoCache, keep: Option<&str>) {+ let cap = c.cap_bytes();+ let total: u64 = store::entries(&c.root).iter().map(|e| e.bytes).sum();+ if total > cap {+ let _ = make_room(c, 0, keep.unwrap_or(""), cap);+ }+}++async fn refresh(+ c: &RepoCache,+ bin: &Path,+ repo: &RepoUrl,+ mut entry: Entry,+ remote: &Refs,+) -> Outcome {+ let home = store::home_dir(&c.root);+ let dir = store::mirror_dir(&c.root, &repo.key);+ let local = local_refs(bin, &home, c.policy.allow, &dir).await;+ let head_now = current_head(bin, &home, c.policy.allow, &dir).await;+ let same = local.as_ref().is_some_and(|l| l.refs == remote.refs)+ && remote+ .head+ .as_ref()+ .is_none_or(|h| head_now.as_deref() == Some(h.as_str()));+ if same && local.is_some() {+ let _ = store::stamp_fresh(&c.root, &repo.key);+ entry.refreshed_ms = now_ms();+ entry.used_ms = now_ms();+ let _ = store::publish(&c.root, &entry, false);+ return Outcome::Refreshed { changed: false };+ }++ // Fetch what changed. Packs only, so a Space can copy them.+ let mut cmd = git::command(bin, &home, c.policy.allow);+ cmd.arg("-C").arg(&dir).args([+ "-c",+ "transfer.unpackLimit=1",+ "-c",+ "fetch.unpackLimit=1",+ "fetch",+ "--quiet",+ "--prune",+ "--no-write-fetch-head",+ "--force",+ "--no-auto-gc",+ "--",+ &repo.url,+ "+refs/heads/*:refs/heads/*",+ "+refs/tags/*:refs/tags/*",+ ]);+ let cap = c.cap_bytes();+ let budget = cap.saturating_sub(held_by_others(c, &repo.key));+ match run_bounded(cmd, &dir, budget, FILL_LIMIT).await {+ Ok(true) => {}+ Ok(false) => return skip(c, Reason::Unreachable),+ Err(r) => {+ // The mirror may hold a partial fetch past the cap: what is+ // not verified is not kept.+ if r == Reason::TooBig {+ store::drop_entry(&c.root, &repo.key);+ let _ = shim::write_config(&c.root);+ }+ return skip(c, r);+ }+ }+ if let Some(h) = &remote.head {+ let mut cmd = git::command(bin, &home, c.policy.allow);+ cmd.arg("-C").arg(&dir).args(["symbolic-ref", "HEAD", h]);+ let _ = git::run(cmd, Duration::from_secs(30)).await;+ }+ // Idle mirrors are tidied; one a Space may be reading is left as it is+ // (a new pack beside the old ones is safe, removing the old is not).+ let idle = now_ms().saturating_sub(entry.used_ms) > EVICTION_GRACE.as_millis() as u64;+ match verify(c, bin, &dir, idle).await {+ Ok((head, packs)) => {+ entry.head = head;+ entry.packs = packs;+ entry.bytes = store::dir_size(&dir);+ entry.refreshed_ms = now_ms();+ entry.used_ms = now_ms();+ if store::publish(&c.root, &entry, true).is_err() {+ store::drop_entry(&c.root, &repo.key);+ let _ = shim::write_config(&c.root);+ return skip(c, Reason::DiskFull);+ }+ if entry.bytes > cap {+ enforce_cap(c, Some(&repo.key));+ }+ let _ = shim::write_config(&c.root);+ Outcome::Refreshed { changed: true }+ }+ Err(r) => {+ store::drop_entry(&c.root, &repo.key);+ let _ = shim::write_config(&c.root);+ skip(c, r)+ }+ }+}++async fn current_head(bin: &Path, home: &Path, allow: &str, dir: &Path) -> Option<String> {+ let mut cmd = git::command(bin, home, allow);+ cmd.arg("-C").arg(dir).args(["symbolic-ref", "HEAD"]);+ let r = git::run(cmd, Duration::from_secs(30)).await.ok()?;+ r.ok.then(|| r.stdout.trim().to_string())+}++/// Checks a mirror before a Space may use it: no loose objects (a Space+/// copies packs; they are packed first when `may_repack`), every pack with+/// its index and a matching trailer, `git fsck --connectivity-only`, and a+/// `HEAD` that resolves. The packs, with their sizes, are what the Space's+/// helper checks on each use.+pub(crate) async fn verify(+ c: &RepoCache,+ bin: &Path,+ dir: &Path,+ may_repack: bool,+) -> Result<(String, Vec<Pack>), Reason> {+ let home = store::home_dir(&c.root);+ let git_in = |args: &[&str]| {+ let mut cmd = git::command(bin, &home, c.policy.allow);+ cmd.arg("-C").arg(dir).args(args);+ cmd+ };+ let loose = || -> bool {+ std::fs::read_dir(dir.join("objects"))+ .map(|rd| {+ rd.flatten().any(|e| {+ let n = e.file_name().to_string_lossy().into_owned();+ n.len() == 2 && n.bytes().all(|b| b.is_ascii_hexdigit())+ })+ })+ .unwrap_or(true)+ };+ let pack_count = || packs_of(dir).len();+ if loose() || (may_repack && pack_count() > MAX_PACKS) {+ if !may_repack && loose() {+ return Err(Reason::VerifyFailed);+ }+ let r = git::run(git_in(&["repack", "-a", "-d", "-q"]), VERIFY_LIMIT).await;+ if !r.is_ok_and(|r| r.ok) || loose() {+ // `repack -a -d` leaves loose objects that are unreachable.+ let _ = git::run(git_in(&["prune-packed"]), VERIFY_LIMIT).await;+ if loose() {+ return Err(Reason::VerifyFailed);+ }+ }+ }+ let fsck = git::run(+ git_in(&[+ "fsck",+ "--connectivity-only",+ "--no-dangling",+ "--no-progress",+ ]),+ VERIFY_LIMIT,+ )+ .await;+ if !fsck.is_ok_and(|r| r.ok) {+ return Err(Reason::VerifyFailed);+ }+ let head = git::run(+ git_in(&["rev-parse", "--verify", "HEAD"]),+ Duration::from_secs(30),+ )+ .await+ .map_err(|_| Reason::VerifyFailed)?;+ if !head.ok {+ return Err(Reason::VerifyFailed);+ }+ let packs = packs_of(dir);+ if packs.is_empty() || !packs.iter().all(|p| pack_trailer_matches(dir, &p.name)) {+ return Err(Reason::VerifyFailed);+ }+ Ok((head.stdout.trim().to_string(), packs))+}++fn packs_of(dir: &Path) -> Vec<Pack> {+ let Ok(rd) = std::fs::read_dir(dir.join("objects/pack")) else {+ return Vec::new();+ };+ let mut v: Vec<Pack> = rd+ .flatten()+ .filter_map(|e| {+ let name = e.file_name().to_string_lossy().into_owned();+ name.ends_with(".pack").then(|| Pack {+ size: e.metadata().map_or(0, |m| m.len()),+ name,+ })+ })+ .collect();+ v.sort_by(|a, b| a.name.cmp(&b.name));+ v+}++/// A pack's last 20 bytes (its checksum) are the first 20 of the last 40 of+/// its index; a truncated or swapped file does not match.+fn pack_trailer_matches(dir: &Path, pack: &str) -> bool {+ use std::io::{Read as _, Seek as _, SeekFrom};+ let base = pack.trim_end_matches(".pack");+ let read_tail = |p: PathBuf, n: i64| -> Option<Vec<u8>> {+ let mut f = std::fs::File::open(p).ok()?;+ f.seek(SeekFrom::End(-n)).ok()?;+ let mut b = vec![0u8; n as usize];+ f.read_exact(&mut b).ok()?;+ Some(b)+ };+ let d = dir.join("objects/pack");+ let (Some(pk), Some(ix)) = (+ read_tail(d.join(format!("{base}.pack")), 20),+ read_tail(d.join(format!("{base}.idx")), 40),+ ) else {+ return false;+ };+ pk == ix[..20]+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ls_remote_output_parses_to_heads_tags_and_head() {+ let oid = |c: char| c.to_string().repeat(40);+ let out = format!(+ "ref: refs/heads/main\tHEAD\n{a}\tHEAD\n{a}\trefs/heads/main\n{b}\trefs/tags/v1\n{c}\trefs/tags/v1^{{}}\n",+ a = oid('a'),+ b = oid('b'),+ c = oid('c'),+ );+ let r = parse_ls_remote(&out);+ assert_eq!(r.head.as_deref(), Some("refs/heads/main"));+ assert_eq!(+ r.refs,+ vec![+ ("refs/heads/main".to_string(), oid('a')),+ ("refs/tags/v1".to_string(), oid('b')),+ ]+ );+ }+}diff --git a/libs/cua/crates/cua-repo-cache/src/git.rs b/libs/cua/crates/cua-repo-cache/src/git.rsnew file mode 100644index 0000000000..b382ac61c3--- /dev/null+++ b/libs/cua/crates/cua-repo-cache/src/git.rs@@ -0,0 +1,125 @@+//! Running `git` for the cache: always unauthenticated, never interactive,+//! never reading the user's own git configuration, credentials or `~/.netrc`.++use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::time::Duration;+use tokio::process::Command;++/// What a git run produced.+#[derive(Debug)]+pub struct Run {+ pub ok: bool,+ pub stdout: String,+ pub stderr: String,+}++/// A git run that did not produce a result.+#[derive(Debug)]+pub enum GitError {+ /// No `git` on this machine.+ Missing,+ /// It did not finish in time (and was stopped).+ TimedOut,+ /// It could not be started.+ Spawn(String),+}++/// The `git` binary: `CUA_REPO_CACHE_GIT`, else the first on `PATH`.+pub fn binary() -> Option<PathBuf> {+ if let Some(p) = std::env::var_os("CUA_REPO_CACHE_GIT").filter(|p| !p.is_empty()) {+ let p = PathBuf::from(p);+ return p.is_file().then_some(p);+ }+ let path = std::env::var_os("PATH")?;+ std::env::split_paths(&path)+ .map(|d| d.join("git"))+ .find(|p| p.is_file())+}++/// A `git` command that cannot use anything of the user's: a home with+/// nothing in it (so no `~/.netrc`, no credential helper, no config), no+/// system config, no prompts, `https` only, and a redirect followed only+/// from the first request.+pub fn command(bin: &Path, home: &Path, allow: &str) -> Command {+ let mut c = Command::new(bin);+ c.env_clear();+ for k in [+ "PATH",+ "HTTPS_PROXY",+ "https_proxy",+ "HTTP_PROXY",+ "http_proxy",+ "ALL_PROXY",+ "all_proxy",+ "NO_PROXY",+ "no_proxy",+ "SSL_CERT_FILE",+ "SSL_CERT_DIR",+ "GIT_SSL_CAINFO",+ "GIT_SSL_CAPATH",+ "TMPDIR",+ ] {+ if let Some(v) = std::env::var_os(k) {+ c.env(k, v);+ }+ }+ c.env("HOME", home)+ .env("XDG_CONFIG_HOME", home)+ .env("LC_ALL", "C")+ .env("GIT_TERMINAL_PROMPT", "0")+ .env("GIT_ASKPASS", "true")+ .env("SSH_ASKPASS", "true")+ .env("GCM_INTERACTIVE", "never")+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .env("GIT_CONFIG_SYSTEM", "/dev/null")+ .env("GIT_CONFIG_NOSYSTEM", "1")+ .env("GIT_ALLOW_PROTOCOL", allow.replace(',', ":"))+ .env("GIT_OPTIONAL_LOCKS", "0")+ .args([+ "-c",+ "credential.helper=",+ "-c",+ "core.askPass=",+ "-c",+ "protocol.allow=never",+ "-c",+ "http.followRedirects=initial",+ "-c",+ "http.lowSpeedLimit=1000",+ "-c",+ "http.lowSpeedTime=30",+ "-c",+ "gc.auto=0",+ "-c",+ "core.fsmonitor=false",+ ])+ .stdin(Stdio::null())+ .kill_on_drop(true);+ for p in allow.split(',') {+ c.arg("-c").arg(format!("protocol.{p}.allow=always"));+ }+ c+}++/// Runs `cmd` to the end within `limit`.+pub async fn run(mut cmd: Command, limit: Duration) -> Result<Run, GitError> {+ cmd.stdout(Stdio::piped()).stderr(Stdio::piped());+ let child = cmd.spawn().map_err(|e| {+ if e.kind() == std::io::ErrorKind::NotFound {+ GitError::Missing+ } else {+ GitError::Spawn(e.to_string())+ }+ })?;+ match tokio::time::timeout(limit, child.wait_with_output()).await {+ Ok(Ok(o)) => Ok(Run {+ ok: o.status.success(),+ stdout: String::from_utf8_lossy(&o.stdout).into_owned(),+ stderr: String::from_utf8_lossy(&o.stderr).into_owned(),+ }),+ Ok(Err(e)) => Err(GitError::Spawn(e.to_string())),+ // `kill_on_drop` stops it.+ Err(_) => Err(GitError::TimedOut),+ }+}diff --git a/libs/cua/crates/cua-repo-cache/src/lib.rs b/libs/cua/crates/cua-repo-cache/src/lib.rsnew file mode 100644index 0000000000..80b62dbf10--- /dev/null+++ b/libs/cua/crates/cua-repo-cache/src/lib.rs@@ -0,0 +1,453 @@+//! The repo cache: public git repositories mirrored on this machine's disk by+//! the cua daemon, so a repeat `git clone <url>` inside a Space does not+//! download the repository again. The agent's command never changes.+//!+//! How it works:+//!+//! - The daemon sees a `git clone <https url>` (a command it runs or relays,+//! or one reported by a Space's helper), asks the remote for its refs with+//! no credentials at all, and, when that works, keeps a bare **mirror** of+//! the repository under `$CUA_HOME/job-cache/repos`: filled by one normal clone,+//! verified (`git fsck` connectivity and each pack's trailer), then+//! refreshed in the background. Repositories that need a credential, hosts+//! on a private network, and anything else that is not plainly public are+//! never cached.+//! - The directory is mounted **read-only** into container Spaces at+//! [`GUEST_ROOT`] (the same host-directory mount a Space gets for any+//! mount). A system git config in it rewrites a mirrored repository's URL to+//! a small remote helper ([`shim::HELPER`]) that the daemon installs next+//! to the Space's git. The helper makes the clone's objects come from the+//! mirror and asks the remote itself for the tip, so a clone is never+//! older than the remote; it copies the mirror's packs into the clone, so+//! the clone never depends on the mirror; and any failure runs the plain+//! `git remote-https` instead.+//! - The cache is bounded ([`Config::cap_bytes`], default the smaller of 5 GB+//! and a tenth of the free disk), evicts the least recently used mirror+//! first, can be turned off and cleared.+//!+//! Counters only ([`Status`], and `cua_repo_cache` telemetry with fixed+//! words): never a URL, a repository name or a path.++mod fill;+mod git;+pub mod shim;+mod stats;+mod store;+#[cfg(all(test, unix))]+mod tests;+pub mod url;++pub use fill::{Outcome, Reason};+pub use store::{Entry, Pack};+pub use url::RepoUrl;++use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex, OnceLock};+use std::time::Duration;++/// Where a Space sees the cache.+pub const GUEST_ROOT: &str = "/cua/repo-cache";++/// The size cap when nothing sets one, at most (it is also at most a tenth+/// of the free disk, see [`RepoCache::cap_bytes`]).+pub const DEFAULT_CAP_BYTES: u64 = 5 << 30;++/// How long a mirror stays untouched by automatic eviction after it was+/// used: a clone that has just started may still be reading it.+pub const EVICTION_GRACE: Duration = Duration::from_secs(120);++/// The settings of the cache.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Config {+ /// The cache is on (default).+ pub enabled: bool,+ /// The total size it may use; `None`: the default+ /// (see [`RepoCache::cap_bytes`]).+ pub cap_bytes: Option<u64>,+}++impl Default for Config {+ fn default() -> Self {+ Self {+ enabled: true,+ cap_bytes: None,+ }+ }+}++/// What Settings shows.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct Status {+ /// The cache is on.+ pub enabled: bool,+ /// Repositories held.+ pub repos: u32,+ /// What they take on disk.+ pub bytes: u64,+ /// The cap in force.+ pub cap_bytes: u64,+ /// Clones served from a mirror in the last week.+ pub hits: u32,+ /// Clones that went the normal way in the last week (no mirror yet, or+ /// one that could not be used).+ pub misses: u32,+ /// Seconds those hits saved.+ pub seconds_saved: u64,+ /// Bytes they did not download.+ pub bytes_saved: u64,+}++/// `bytes` in words: `0 MB`, `340 MB`, `1.2 GB` (powers of 1024).+pub fn size_words(bytes: u64) -> String {+ const MB: f64 = 1024.0 * 1024.0;+ const GB: f64 = MB * 1024.0;+ let b = bytes as f64;+ if b >= GB {+ let g = b / GB;+ if g >= 10.0 || (g - g.round()).abs() < 0.05 {+ format!("{} GB", g.round() as u64)+ } else {+ format!("{g:.1} GB")+ }+ } else {+ format!("{} MB", (b / MB).round() as u64)+ }+}++/// `seconds` in words: `20 seconds`, `about 2 minutes`, `about 3 hours`.+pub fn time_words(seconds: u64) -> String {+ match seconds {+ 0..=59 => format!("{seconds} second{}", if seconds == 1 { "" } else { "s" }),+ 60..=5399 => {+ let m = (seconds as f64 / 60.0).round() as u64;+ format!("about {m} minute{}", if m == 1 { "" } else { "s" })+ }+ _ => {+ let h = (seconds as f64 / 3600.0).round() as u64;+ format!("about {h} hour{}", if h == 1 { "" } else { "s" })+ }+ }+}++impl Status {+ /// What is held, in plain words: `Repos: 3, 1.2 GB of 5 GB`.+ pub fn size_line(&self) -> String {+ format!(+ "Repos: {}, {} of {}",+ self.repos,+ size_words(self.bytes),+ size_words(self.cap_bytes)+ )+ }++ /// What the last week saved, in plain words. Empty until a clone was+ /// seen.+ pub fn week_line(&self) -> String {+ let total = self.hits + self.misses;+ if total == 0 {+ return "No clones yet this week".to_string();+ }+ let pct = (f64::from(self.hits) * 100.0 / f64::from(total)).round() as u32;+ if self.hits == 0 {+ return format!(+ "Last week: {total} clone{} downloaded, none from the cache yet",+ if total == 1 { "" } else { "s" }+ );+ }+ format!(+ "Last week: {pct}% of clones came from the cache, {} saved",+ time_words(self.seconds_saved)+ )+ }+}++/// The cache of one machine: a directory and its settings. Cheap to make;+/// what is shared between calls (one fill at a time, which repositories+/// were just found private) is process-wide.+#[derive(Clone, Debug)]+pub struct RepoCache {+ root: PathBuf,+ cfg: Config,+ pub(crate) policy: Policy,+}++/// Which protocols the daemon's own git runs may use and whether the host+/// must be public.+#[derive(Clone, Copy, Debug)]+pub(crate) struct Policy {+ pub allow: &'static str,+ pub check_host: bool,+}++pub(crate) const STRICT: Policy = Policy {+ allow: "https",+ check_host: true,+};++pub(crate) struct State {+ /// One fill or refresh at a time.+ pub gate: tokio::sync::Mutex<()>,+ /// Repositories found not public (or unreachable), until when.+ pub negative: Mutex<std::collections::HashMap<(PathBuf, String), std::time::Instant>>,+ /// Roots whose leftovers were swept.+ pub swept: Mutex<std::collections::HashSet<PathBuf>>,+}++pub(crate) fn state() -> &'static State {+ static S: OnceLock<State> = OnceLock::new();+ S.get_or_init(|| State {+ gate: tokio::sync::Mutex::new(()),+ negative: Mutex::new(Default::default()),+ swept: Mutex::new(Default::default()),+ })+}++impl RepoCache {+ /// The cache in `root`.+ pub fn new(root: impl Into<PathBuf>, cfg: Config) -> Self {+ Self {+ root: root.into(),+ cfg,+ policy: STRICT,+ }+ }++ /// Unit tests mirror local repositories.+ #[cfg(all(test, unix))]+ pub(crate) fn allowing_local_repos(mut self) -> Self {+ self.policy = Policy {+ allow: "file,https",+ check_host: false,+ };+ self+ }++ /// `$CUA_HOME/job-cache/repos`: under the one directory of the cua home+ /// that the built-in Linux runtime of a Mac already shares into its VM+ /// (a container there can only bind what the VM sees).+ pub fn default_root() -> PathBuf {+ cua_home::cua_home().join("job-cache").join("repos")+ }++ /// The cache in [`RepoCache::default_root`].+ pub fn at_default(cfg: Config) -> Self {+ Self::new(Self::default_root(), cfg)+ }++ pub fn root(&self) -> &Path {+ &self.root+ }++ pub fn config(&self) -> Config {+ self.cfg+ }++ /// The size cap in force: [`Config::cap_bytes`], else the smaller of+ /// [`DEFAULT_CAP_BYTES`] and a tenth of the disk that is free plus what+ /// the cache itself holds (so using the cache does not shrink it).+ pub fn cap_bytes(&self) -> u64 {+ if let Some(c) = self.cfg.cap_bytes {+ return c;+ }+ let held: u64 = store::entries(&self.root).iter().map(|e| e.bytes).sum();+ let free = store::free_bytes(if self.root.exists() {+ &self.root+ } else {+ self.root.parent().unwrap_or(&self.root)+ })+ .unwrap_or(DEFAULT_CAP_BYTES.saturating_mul(10));+ DEFAULT_CAP_BYTES.min(free.saturating_add(held) / 10)+ }++ /// Creates what a Space reads (the helper, the git config) and removes+ /// what an interrupted run left. Call before mounting.+ pub fn prepare(&self) -> std::io::Result<()> {+ std::fs::create_dir_all(store::m_dir(&self.root))?;+ std::fs::create_dir_all(store::home_dir(&self.root))?;+ let first = state()+ .swept+ .lock()+ .map(|mut s| s.insert(self.root.clone()))+ .unwrap_or(false);+ if first {+ store::sweep_leftovers(&self.root);+ std::fs::create_dir_all(store::m_dir(&self.root))?;+ }+ shim::write_helper(&self.root)?;+ if !self.root.join("gitconfig").exists() || first {+ shim::write_config(&self.root)?;+ }+ Ok(())+ }++ /// The directory to mount read-only at [`GUEST_ROOT`] in a container+ /// Space: `Some` while the cache is on and ready.+ pub fn mount_source(&self) -> Option<PathBuf> {+ (self.cfg.enabled && self.prepare().is_ok()).then(|| self.root.clone())+ }++ /// Makes the git config Spaces include match the setting: with the cache+ /// off it names no repository (running Spaces stop using their mirrors),+ /// on it names every verified one. Cheap; run after the setting changed.+ pub fn sync_config(&self) {+ if !self.root.exists() {+ return;+ }+ let _ = if self.cfg.enabled {+ shim::write_config(&self.root)+ } else {+ store::write_atomic(+ &self.root.join("gitconfig"),+ shim::config_text(&[]).as_bytes(),+ )+ };+ }++ /// What Settings shows.+ pub fn status(&self) -> Status {+ let entries = store::entries(&self.root);+ let w = stats::week(&self.root);+ Status {+ enabled: self.cfg.enabled,+ repos: entries.len() as u32,+ bytes: entries.iter().map(|e| e.bytes).sum(),+ cap_bytes: self.cap_bytes(),+ hits: w.hits,+ misses: w.misses,+ seconds_saved: w.seconds_saved,+ bytes_saved: w.bytes_saved,+ }+ }++ /// Removes every mirror (the counters stay).+ pub fn clear(&self) {+ store::clear(&self.root);+ let _ = shim::write_config(&self.root);+ }++ /// The mirrors, least recently used first.+ pub fn entries(&self) -> Vec<Entry> {+ store::entries(&self.root)+ }++ /// What a command line clones: counts a repeat of a mirrored repository+ /// as used, a repository with no mirror as a miss, and in a running+ /// tokio runtime starts filling or refreshing each in the background.+ /// Never waits, never fails; nothing happens while the cache is off.+ pub fn learn(&self, text: &str) {+ if !self.cfg.enabled {+ return;+ }+ let repos = url::urls_in(text);+ if repos.is_empty() {+ return;+ }+ let Ok(rt) = tokio::runtime::Handle::try_current() else {+ return;+ };+ for r in repos {+ if store::entry(&self.root, &r.key).is_some() {+ store::touch(&self.root, &r.key);+ } else {+ self.note_miss();+ }+ let me = self.clone();+ rt.spawn(async move {+ let _ = me.ensure(&r).await;+ });+ }+ }++ /// A clone that went the normal way.+ pub fn note_miss(&self) {+ stats::miss(&self.root);+ cua_telemetry::global().repo_cache("miss", "network", 0, 0, "none");+ }++ /// Takes what a Space's helper logged (see+ /// [`shim::take_log_command`]): counts the hits, with what each saved,+ /// and the mirrors it could not use.+ pub fn ingest_guest_log(&self, text: &str) {+ for l in shim::parse_log(text) {+ match l.kind {+ shim::LogKind::HitLease | shim::LogKind::HitChecked => {+ let Some(e) = store::entry(&self.root, &l.key) else {+ continue;+ };+ store::touch(&self.root, &l.key);+ let saved = (e.fill_secs - f64::from(l.secs)).max(0.0);+ stats::hit(&self.root, saved, e.bytes);+ cua_telemetry::global().repo_cache(+ "hit",+ "local",+ e.bytes,+ saved.round() as u64,+ "none",+ );+ }+ shim::LogKind::Skipped | shim::LogKind::Failed | shim::LogKind::Kept => {+ stats::fallback(&self.root);+ let reason = match l.kind {+ shim::LogKind::Skipped => "verify_failed",+ shim::LogKind::Kept => "disk_full",+ _ => "other",+ };+ cua_telemetry::global().repo_cache("fallback", "network", 0, 0, reason);+ // A mirror whose packs changed under us is not served+ // again.+ if l.kind == shim::LogKind::Skipped {+ self.drop_if_damaged(&l.key);+ }+ }+ }+ }+ }++ /// Checks one mirror again and removes it when it does not pass.+ fn drop_if_damaged(&self, key: &str) {+ let Some(e) = store::entry(&self.root, key) else {+ return;+ };+ let dir = store::mirror_dir(&self.root, key);+ let intact = e.packs.iter().all(|p| {+ std::fs::metadata(dir.join("objects/pack").join(&p.name))+ .is_ok_and(|m| m.len() == p.size)+ });+ if !intact {+ store::drop_entry(&self.root, key);+ let _ = shim::write_config(&self.root);+ }+ }++ /// Fills or refreshes the mirror of `repo` (see [`Outcome`]); one at a+ /// time. Never touches anything outside the cache directory.+ pub async fn ensure(&self, repo: &RepoUrl) -> Outcome {+ fill::ensure(self, repo).await+ }++ /// Keeps the cache within its cap, drops mirrors that no longer verify,+ /// and refreshes the ones used in the last week that were not refreshed+ /// for `older_than`, one at a time.+ pub async fn maintain(&self, older_than: Duration) {+ if !self.cfg.enabled {+ self.sync_config();+ return;+ }+ let _ = self.prepare();+ fill::enforce_cap(self, None);+ let now = store::now_ms();+ for e in store::entries(&self.root).into_iter().rev() {+ let used_recently = now.saturating_sub(e.used_ms) < 7 * 24 * 3600 * 1000;+ let stale = now.saturating_sub(e.refreshed_ms) > older_than.as_millis() as u64;+ if used_recently+ && stale+ && let Ok(repo) = url::parse(&e.url)+ {+ let _ = self.ensure(&repo).await;+ }+ }+ }+}++/// A shared handle for the daemon.+pub type Shared = Arc<RepoCache>;diff --git a/libs/cua/crates/cua-repo-cache/src/shim.rs b/libs/cua/crates/cua-repo-cache/src/shim.rsnew file mode 100644index 0000000000..3994e29995--- /dev/null+++ b/libs/cua/crates/cua-repo-cache/src/shim.rs@@ -0,0 +1,205 @@+//! What a Space sees: the helper, the system git config that routes a+//! mirrored repository's URL to it, the script that installs both, and the+//! log the helper keeps.++use std::path::Path;++use crate::GUEST_ROOT;+use crate::store::{self, Entry};++/// The helper a Space runs for a mirrored repository.+pub const HELPER: &str = include_str!("../assets/git-remote-cuarepo");++/// The helper's file name (`git remote-<name>` finds it).+pub const HELPER_NAME: &str = "git-remote-cuarepo";++/// What the install script prints when the Space uses the cache now.+pub const INSTALLED_MARKER: &str = "cua-repo-cache-installed";++/// Where the helper keeps its log in the Space.+pub const GUEST_LOG: &str = "/tmp/.cua-repo-cache.log";++/// Writes the helper into `<root>/bin`.+pub fn write_helper(root: &Path) -> std::io::Result<()> {+ let dir = root.join("bin");+ std::fs::create_dir_all(&dir)?;+ let p = dir.join(HELPER_NAME);+ if std::fs::read_to_string(&p).is_ok_and(|t| t == HELPER) {+ return Ok(());+ }+ store::write_atomic(&p, HELPER.as_bytes())?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755))?;+ }+ Ok(())+}++/// The system git config a Space includes: one rewrite per verified mirror.+/// `<url>` (and `<url>.git`, which it is a prefix of) goes to the helper,+/// which checks everything again and falls back to plain `https`.+pub fn config_text(entries: &[Entry]) -> String {+ let mut out =+ String::from("# Written by the Cua daemon from its repo cache. Read-only in a Space.\n");+ for e in entries {+ // Keys and URLs are normalized (hex and a restricted alphabet).+ out.push_str(&format!(+ "[url \"cuarepo::{key}::{url}\"]\n\tinsteadOf = {url}\n",+ key = e.key,+ url = e.url+ ));+ }+ out+}++/// Rewrites `<root>/gitconfig` for the mirrors there now.+pub fn write_config(root: &Path) -> std::io::Result<()> {+ store::write_atomic(+ &root.join("gitconfig"),+ config_text(&store::entries(root)).as_bytes(),+ )+}++/// The script that makes a Space use the cache, run in the Space by the+/// daemon once it is up (as root, through the Space's own daemon): it+/// installs the helper where git finds it and includes the cache's git+/// config in the system config. It does nothing, quietly, in a Space+/// without the mount, without git, or without the rights.+pub fn install_script() -> String {+ format!(+ r#"root={GUEST_ROOT}+[ -f "$root/gitconfig" ] && [ -f "$root/bin/{HELPER_NAME}" ] || exit 0+command -v git >/dev/null 2>&1 || exit 0+for dir in "$(git --exec-path 2>/dev/null)" /usr/local/bin; do+ [ -n "$dir" ] && [ -d "$dir" ] && [ -w "$dir" ] || continue+ if cmp -s "$root/bin/{HELPER_NAME}" "$dir/{HELPER_NAME}" 2>/dev/null; then ok=1; break; fi+ if cp "$root/bin/{HELPER_NAME}" "$dir/{HELPER_NAME}.tmp$$" 2>/dev/null \+ && chmod 0755 "$dir/{HELPER_NAME}.tmp$$" \+ && mv "$dir/{HELPER_NAME}.tmp$$" "$dir/{HELPER_NAME}"; then ok=1; break; fi+ rm -f "$dir/{HELPER_NAME}.tmp$$"+done+[ "${{ok:-0}}" = 1 ] || exit 0+git config --system --get-all include.path 2>/dev/null | grep -qx "$root/gitconfig" \+ || git config --system --add include.path "$root/gitconfig" 2>/dev/null+git config --system --get-all include.path 2>/dev/null | grep -qx "$root/gitconfig" && echo {INSTALLED_MARKER}+exit 0+"#+ )+}++/// The command that hands the helper's log to the daemon and empties it.+pub fn take_log_command() -> String {+ format!(+ "f={GUEST_LOG}; [ -s \"$f\" ] && mv \"$f\" \"$f.read\" 2>/dev/null && head -c 65536 \"$f.read\"; rm -f \"$f.read\"; exit 0"+ )+}++/// One line the helper logged.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct LogLine {+ pub kind: LogKind,+ pub key: String,+ pub secs: u32,+}++/// What the helper did.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LogKind {+ /// The clone came from the mirror within its lease: no network.+ HitLease,+ /// The remote was asked, the mirror supplied what it already had.+ HitChecked,+ /// A mirror failed a check; the clone went the normal way.+ Skipped,+ /// The clone failed.+ Failed,+ /// The copy into the clone failed: it keeps the mirror as an alternate.+ Kept,+}++/// Parses what a Space wrote (never trusted: unknown or malformed lines are+/// ignored, and only the first 1000 count).+pub fn parse_log(text: &str) -> Vec<LogLine> {+ text.lines()+ .take(1000)+ .filter_map(|l| {+ let mut w = l.split_whitespace();+ let _epoch = w.next()?.parse::<u64>().ok()?;+ let kind = match w.next()? {+ "hit_lease" => LogKind::HitLease,+ "hit_checked" => LogKind::HitChecked,+ "skipped" => LogKind::Skipped,+ "failed" => LogKind::Failed,+ "kept" => LogKind::Kept,+ _ => return None,+ };+ let key = w.next()?;+ if key.len() != 16+ || !key+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+ {+ return None;+ }+ let secs = w.next()?.parse::<u32>().ok()?.min(3600);+ w.next().is_none().then(|| LogLine {+ kind,+ key: key.to_string(),+ secs,+ })+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_guest_log_is_parsed_strictly() {+ let l = parse_log(+ "1700000000 hit_lease 0123456789abcdef 0\n\+ 1700000001 hit_checked 0123456789abcdef 1\n\+ 1700000002 failed 0123456789abcdef 0\n\+ garbage\n\+ 1700000003 hit_lease ../../etc/passwd 0\n\+ 1700000004 hit_lease 0123456789abcdef 0 extra\n\+ 1700000005 evil 0123456789abcdef 0\n",+ );+ assert_eq!(+ l.iter().map(|x| x.kind).collect::<Vec<_>>(),+ [LogKind::HitLease, LogKind::HitChecked, LogKind::Failed]+ );+ }++ #[test]+ fn the_config_rewrites_each_mirror_to_the_helper() {+ let e = Entry {+ url: "https://github.com/o/r".into(),+ key: "0123456789abcdef".into(),+ filled_ms: 0,+ refreshed_ms: 0,+ used_ms: 0,+ bytes: 0,+ fill_secs: 0.0,+ head: String::new(),+ packs: vec![],+ };+ let t = config_text(&[e]);+ assert!(t.contains("[url \"cuarepo::0123456789abcdef::https://github.com/o/r\"]"));+ assert!(t.contains("insteadOf = https://github.com/o/r\n"));+ }++ #[cfg(unix)]+ #[test]+ fn the_install_script_does_nothing_without_the_mount() {+ // Syntax check with the shell, in a place with no mount.+ let out = std::process::Command::new("sh")+ .arg("-c")+ .arg(install_script())+ .output()+ .unwrap();+ assert!(out.status.success(), "{out:?}");+ }+}diff --git a/libs/cua/crates/cua-repo-cache/src/stats.rs b/libs/cua/crates/cua-repo-cache/src/stats.rsnew file mode 100644index 0000000000..91887d9576--- /dev/null+++ b/libs/cua/crates/cua-repo-cache/src/stats.rs@@ -0,0 +1,144 @@+//! What the cache saved over the last week, for Settings: counts and+//! numbers only, never a URL or a name (the file is `stats.jsonl`, one line+//! per event).++use serde::{Deserialize, Serialize};+use std::io::Write as _;+use std::path::{Path, PathBuf};++use crate::store::now_ms;++const WEEK_MS: u64 = 7 * 24 * 3600 * 1000;+/// The file is rewritten without what is older than a week when it is+/// larger than this.+const TRIM_AT: u64 = 256 * 1024;++#[derive(Clone, Debug, Serialize, Deserialize)]+struct Line {+ /// Unix ms.+ t: u64,+ /// `hit`, `miss` or `fallback`.+ k: String,+ /// Seconds a hit saved.+ #[serde(default)]+ s: f64,+ /// Bytes a hit did not download.+ #[serde(default)]+ b: u64,+}++/// What the last week shows.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct Week {+ pub hits: u32,+ pub misses: u32,+ pub seconds_saved: u64,+ pub bytes_saved: u64,+}++fn path(root: &Path) -> PathBuf {+ root.join("stats.jsonl")+}++fn append(root: &Path, line: &Line) {+ let _ = std::fs::create_dir_all(root);+ let p = path(root);+ if std::fs::metadata(&p).is_ok_and(|m| m.len() > TRIM_AT) {+ trim(root);+ }+ if let Ok(mut f) = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(&p)+ && let Ok(mut s) = serde_json::to_string(line)+ {+ s.push('\n');+ let _ = f.write_all(s.as_bytes());+ }+}++fn trim(root: &Path) {+ let p = path(root);+ let Ok(text) = std::fs::read_to_string(&p) else {+ return;+ };+ let from = now_ms().saturating_sub(WEEK_MS);+ let kept: String = text+ .lines()+ .filter(|l| {+ serde_json::from_str::<Line>(l)+ .map(|l| l.t >= from)+ .unwrap_or(false)+ })+ .flat_map(|l| [l, "\n"])+ .collect();+ let _ = crate::store::write_atomic(&p, kept.as_bytes());+}++/// A clone served from a mirror.+pub fn hit(root: &Path, seconds_saved: f64, bytes_saved: u64) {+ append(+ root,+ &Line {+ t: now_ms(),+ k: "hit".into(),+ s: seconds_saved.max(0.0),+ b: bytes_saved,+ },+ );+}++/// A clone of a repository with no usable mirror.+pub fn miss(root: &Path) {+ append(+ root,+ &Line {+ t: now_ms(),+ k: "miss".into(),+ s: 0.0,+ b: 0,+ },+ );+}++/// A mirror that could not be used (the clone went the normal way).+pub fn fallback(root: &Path) {+ append(+ root,+ &Line {+ t: now_ms(),+ k: "fallback".into(),+ s: 0.0,+ b: 0,+ },+ );+}++/// The last week.+pub fn week(root: &Path) -> Week {+ let Ok(text) = std::fs::read_to_string(path(root)) else {+ return Week::default();+ };+ let from = now_ms().saturating_sub(WEEK_MS);+ let mut w = Week::default();+ let mut secs = 0.0;+ for l in text.lines() {+ let Ok(l) = serde_json::from_str::<Line>(l) else {+ continue;+ };+ if l.t < from {+ continue;+ }+ match l.k.as_str() {+ "hit" => {+ w.hits += 1;+ secs += l.s;+ w.bytes_saved += l.b;+ }+ "miss" | "fallback" => w.misses += 1,+ _ => {}+ }+ }+ w.seconds_saved = secs.round() as u64;+ w+}diff --git a/libs/cua/crates/cua-repo-cache/src/store.rs b/libs/cua/crates/cua-repo-cache/src/store.rsnew file mode 100644index 0000000000..cfe73199b0--- /dev/null+++ b/libs/cua/crates/cua-repo-cache/src/store.rs@@ -0,0 +1,265 @@+//! The cache on disk: one bare mirror per repository, a record of it, and+//! the files the Space reads (`.ok`, `.url`, `.fresh`, `gitconfig`, the+//! helper).+//!+//! ```text+//! <root>/m/<key>.git the mirror (heads and tags)+//! <root>/m/<key>.json its record (Entry)+//! <root>/m/<key>.url the normalized URL it mirrors+//! <root>/m/<key>.ok the size of each pack that passed verification+//! <root>/m/<key>.fresh unix seconds the remote's tip was last confirmed+//! <root>/gitconfig the system git config a Space includes+//! <root>/bin/git-remote-cuarepo+//! <root>/tmp/ fills in progress+//! <root>/home/ an empty home for the daemon's own git runs+//! <root>/stats.jsonl what the last week saved+//! ```++use serde::{Deserialize, Serialize};+use std::path::{Path, PathBuf};++/// One verified pack of a mirror.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct Pack {+ /// `pack-<hash>.pack`.+ pub name: String,+ /// Its size in bytes when it was verified.+ pub size: u64,+}++/// What the cache knows of one mirror.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct Entry {+ /// The normalized URL.+ pub url: String,+ /// The key (16 hex digits).+ pub key: String,+ /// When the first fill finished (Unix ms).+ pub filled_ms: u64,+ /// When the remote's tip was last confirmed and the delta fetched.+ pub refreshed_ms: u64,+ /// When it was last used (a clone seen or reported; Unix ms): what+ /// least-recently-used eviction orders by.+ pub used_ms: u64,+ /// The mirror's size on disk.+ pub bytes: u64,+ /// How long the network clone that filled it took: what a repeat clone+ /// is credited with saving.+ pub fill_secs: f64,+ /// The commit `HEAD` pointed at when verified.+ pub head: String,+ /// The packs that passed verification.+ pub packs: Vec<Pack>,+}++pub fn now_ms() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| d.as_millis() as u64)+}++pub fn m_dir(root: &Path) -> PathBuf {+ root.join("m")+}++pub fn mirror_dir(root: &Path, key: &str) -> PathBuf {+ m_dir(root).join(format!("{key}.git"))+}++pub fn side(root: &Path, key: &str, ext: &str) -> PathBuf {+ m_dir(root).join(format!("{key}.{ext}"))+}++pub fn tmp_dir(root: &Path) -> PathBuf {+ root.join("tmp")+}++pub fn home_dir(root: &Path) -> PathBuf {+ root.join("home")+}++/// Writes `data` to `path` through a rename, so a reader (a Space on the+/// read-only mount) never sees half a file.+pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {+ let tmp = path.with_extension(format!("tmp{}", std::process::id()));+ std::fs::write(&tmp, data)?;+ std::fs::rename(&tmp, path).inspect_err(|_| {+ let _ = std::fs::remove_file(&tmp);+ })+}++/// The size of everything under `path` (symlinks are not followed).+pub fn dir_size(path: &Path) -> u64 {+ let Ok(rd) = std::fs::read_dir(path) else {+ return 0;+ };+ let mut total = 0;+ for e in rd.flatten() {+ let Ok(t) = e.file_type() else { continue };+ if t.is_dir() {+ total += dir_size(&e.path());+ } else if let Ok(m) = e.metadata() {+ total += m.len();+ }+ }+ total+}++/// Every mirror with a record and a verification stamp, least recently used+/// first.+pub fn entries(root: &Path) -> Vec<Entry> {+ let Ok(rd) = std::fs::read_dir(m_dir(root)) else {+ return Vec::new();+ };+ let mut out: Vec<Entry> = rd+ .flatten()+ .filter_map(|e| {+ let name = e.file_name().to_string_lossy().into_owned();+ let key = name.strip_suffix(".json")?;+ let text = std::fs::read_to_string(e.path()).ok()?;+ let entry: Entry = serde_json::from_str(&text).ok()?;+ (entry.key == key && mirror_dir(root, key).is_dir() && side(root, key, "ok").is_file())+ .then_some(entry)+ })+ .collect();+ out.sort_by_key(|e| e.used_ms);+ out+}++pub fn entry(root: &Path, key: &str) -> Option<Entry> {+ entries(root).into_iter().find(|e| e.key == key)+}++/// Records `e` and the stamps a Space checks, last the `.ok` stamp (a mirror+/// without it is not used).+pub fn publish(root: &Path, e: &Entry, fresh: bool) -> std::io::Result<()> {+ let key = &e.key;+ write_atomic(&side(root, key, "url"), e.url.as_bytes())?;+ write_atomic(+ &side(root, key, "json"),+ serde_json::to_string(e)+ .map_err(std::io::Error::other)?+ .as_bytes(),+ )?;+ let ok: String = e+ .packs+ .iter()+ .map(|p| format!("{} {}\n", p.size, p.name))+ .collect();+ write_atomic(&side(root, key, "ok"), ok.as_bytes())?;+ if fresh {+ stamp_fresh(root, key)?;+ }+ Ok(())+}++pub fn stamp_fresh(root: &Path, key: &str) -> std::io::Result<()> {+ write_atomic(+ &side(root, key, "fresh"),+ format!("{}\n", now_ms() / 1000).as_bytes(),+ )+}++/// Records that `key` was used now.+pub fn touch(root: &Path, key: &str) {+ if let Some(mut e) = entry(root, key) {+ e.used_ms = now_ms();+ let _ = write_atomic(+ &side(root, key, "json"),+ serde_json::to_string(&e).unwrap_or_default().as_bytes(),+ );+ }+}++/// Removes one mirror and everything beside it. The stamp goes first, so a+/// Space stops using it before its files go.+pub fn drop_entry(root: &Path, key: &str) {+ let _ = std::fs::remove_file(side(root, key, "ok"));+ let _ = std::fs::remove_file(side(root, key, "fresh"));+ let trash = root.join("trash").join(format!("{key}-{}", now_ms()));+ let moved = std::fs::create_dir_all(root.join("trash"))+ .and_then(|()| std::fs::rename(mirror_dir(root, key), &trash))+ .is_ok();+ let _ = std::fs::remove_file(side(root, key, "json"));+ let _ = std::fs::remove_file(side(root, key, "url"));+ if moved {+ let _ = std::fs::remove_dir_all(&trash);+ } else {+ let _ = std::fs::remove_dir_all(mirror_dir(root, key));+ }+}++/// Removes every mirror, unfinished fill and stamp. The daemon's counters+/// stay.+pub fn clear(root: &Path) {+ if let Ok(rd) = std::fs::read_dir(m_dir(root)) {+ // Stamps first: nothing is used while it goes.+ let all: Vec<_> = rd.flatten().map(|e| e.path()).collect();+ for p in all+ .iter()+ .filter(|p| p.extension().is_some_and(|x| x == "ok"))+ {+ let _ = std::fs::remove_file(p);+ }+ for p in all {+ if p.is_dir() {+ let _ = std::fs::remove_dir_all(&p);+ } else {+ let _ = std::fs::remove_file(&p);+ }+ }+ }+ for d in ["tmp", "trash"] {+ let _ = std::fs::remove_dir_all(root.join(d));+ }+}++/// Removes what an interrupted fill or eviction left.+pub fn sweep_leftovers(root: &Path) {+ for d in ["tmp", "trash"] {+ let _ = std::fs::remove_dir_all(root.join(d));+ }+ // A record or stamp without its mirror, a mirror without a record.+ let Ok(rd) = std::fs::read_dir(m_dir(root)) else {+ return;+ };+ let names: Vec<String> = rd+ .flatten()+ .map(|e| e.file_name().to_string_lossy().into_owned())+ .collect();+ for n in &names {+ let Some((key, ext)) = n.split_once('.') else {+ continue;+ };+ let has_mirror = names.iter().any(|m| *m == format!("{key}.git"));+ let has_record = names.iter().any(|m| *m == format!("{key}.json"));+ let orphan = match ext {+ "git" => !has_record,+ _ => !has_mirror,+ };+ if orphan {+ let p = m_dir(root).join(n);+ let _ = if p.is_dir() {+ std::fs::remove_dir_all(&p)+ } else {+ std::fs::remove_file(&p)+ };+ }+ }+}++/// Free bytes on the disk `path` is on.+pub fn free_bytes(path: &Path) -> Option<u64> {+ #[cfg(unix)]+ {+ use std::os::unix::ffi::OsStrExt as _;+ let c = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;+ // SAFETY: `c` is a valid C string and `s` is written by statvfs.+ let mut s: libc::statvfs = unsafe { std::mem::zeroed() };+ if unsafe { libc::statvfs(c.as_ptr(), &mut s) } == 0 {+ return Some(s.f_bavail as u64 * s.f_frsize as u64);+ }+ }+ let _ = path;+ None+}diff --git a/libs/cua/crates/cua-repo-cache/src/tests.rs b/libs/cua/crates/cua-repo-cache/src/tests.rsnew file mode 100644index 0000000000..77a5735579--- /dev/null+++ b/libs/cua/crates/cua-repo-cache/src/tests.rs@@ -0,0 +1,568 @@+//! The cache against real git: local repositories stand in for remotes, and+//! the helper runs as a Space runs it.++use std::path::{Path, PathBuf};+use std::process::Command;++use crate::{Config, EVICTION_GRACE, Outcome, Reason, RepoCache, RepoUrl, shim, store};++fn git(dir: &Path, args: &[&str]) -> String {+ let out = Command::new("git")+ .current_dir(dir)+ .args(args)+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .env("GIT_CONFIG_SYSTEM", "/dev/null")+ .env("GIT_AUTHOR_NAME", "t")+ .env("GIT_AUTHOR_EMAIL", "[email protected]")+ .env("GIT_COMMITTER_NAME", "t")+ .env("GIT_COMMITTER_EMAIL", "[email protected]")+ .output()+ .unwrap();+ assert!(out.status.success(), "git {args:?}: {out:?}");+ String::from_utf8_lossy(&out.stdout).trim().to_string()+}++/// A repository with `n` commits, each adding a file of `kb` KiB of+/// pseudo-random bytes.+fn source(dir: &Path, name: &str, n: usize, kb: usize) -> RepoUrl {+ let path = dir.join(name);+ std::fs::create_dir_all(&path).unwrap();+ git(&path, &["init", "-q", "-b", "main"]);+ for i in 0..n {+ add_commit(&path, i, kb);+ }+ repo_url(&path)+}++fn add_commit(path: &Path, i: usize, kb: usize) {+ let mut x: u64 = 0x9e37_79b9_7f4a_7c15 ^ (i as u64 + 1).wrapping_mul(0xff51_afd7_ed55_8ccd);+ let bytes: Vec<u8> = (0..kb * 1024)+ .map(|_| {+ x ^= x << 13;+ x ^= x >> 7;+ x ^= x << 17;+ (x >> 24) as u8+ })+ .collect();+ std::fs::write(path.join(format!("f{i}.bin")), bytes).unwrap();+ git(path, &["add", "."]);+ git(path, &["commit", "-q", "-m", &format!("c{i}")]);+}++fn repo_url(path: &Path) -> RepoUrl {+ let url = format!("file://{}", path.display());+ let key = hex::encode(&<sha2::Sha256 as sha2::Digest>::digest(url.as_bytes())[..8]);+ RepoUrl {+ url,+ key,+ host: "example.com".into(),+ }+}++/// Git writes packs read-only.+fn make_writable(p: &Path) {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o644)).unwrap();+}++fn cache(root: &Path, cap: Option<u64>) -> RepoCache {+ RepoCache::new(+ root,+ Config {+ enabled: true,+ cap_bytes: cap,+ },+ )+ .allowing_local_repos()+}++fn dirs() -> (tempfile::TempDir, PathBuf, PathBuf) {+ let t = tempfile::tempdir().unwrap();+ let src = t.path().join("src");+ let root = t.path().join("cache");+ std::fs::create_dir_all(&src).unwrap();+ (t, src, root)+}++#[tokio::test]+async fn the_first_sight_fills_a_verified_mirror_and_a_repeat_is_confirmed() {+ let (_t, src, root) = dirs();+ let repo = source(&src, "a", 3, 64);+ let c = cache(&root, Some(1 << 30));+ let out = c.ensure(&repo).await;+ let Outcome::Filled { bytes, .. } = out else {+ panic!("not filled: {out:?}");+ };+ assert!(bytes > 0);+ let e = c.entries();+ assert_eq!(e.len(), 1);+ assert_eq!(e[0].head, git(&src.join("a"), &["rev-parse", "HEAD"]));+ assert!(!e[0].packs.is_empty());+ // The Space-facing files are all there.+ for ext in ["ok", "url", "fresh", "json"] {+ assert!(store::side(&root, &repo.key, ext).is_file(), "{ext}");+ }+ assert!(+ std::fs::read_to_string(root.join("gitconfig"))+ .unwrap()+ .contains(&format!("cuarepo::{}::{}", repo.key, repo.url))+ );+ // A repeat within seconds is confirmed without asking the remote again.+ assert_eq!(c.ensure(&repo).await, Outcome::Refreshed { changed: false });+}++#[tokio::test]+async fn a_new_commit_on_the_remote_reaches_the_mirror_and_is_never_served_stale() {+ let (_t, src, root) = dirs();+ let repo = source(&src, "a", 2, 16);+ let c = cache(&root, Some(1 << 30));+ assert!(matches!(c.ensure(&repo).await, Outcome::Filled { .. }));+ let before = c.entries()[0].head.clone();+ add_commit(&src.join("a"), 99, 16);+ git(&src.join("a"), &["tag", "v1"]);+ // The lease stamp of the first fill is still fresh: age it, as time does.+ std::fs::write(store::side(&root, &repo.key, "fresh"), "1\n").unwrap();+ assert_eq!(c.ensure(&repo).await, Outcome::Refreshed { changed: true });+ let e = c.entries();+ assert_ne!(e[0].head, before);+ assert_eq!(e[0].head, git(&src.join("a"), &["rev-parse", "HEAD"]));+ // The mirror has the tag and the commit.+ let mirror = store::mirror_dir(&root, &repo.key);+ assert_eq!(+ git(&mirror, &["rev-parse", "v1"]),+ git(&src.join("a"), &["rev-parse", "v1"])+ );+ // No loose objects: a Space copies packs.+ assert!(+ std::fs::read_dir(mirror.join("objects"))+ .unwrap()+ .flatten()+ .all(|e| e.file_name().to_string_lossy().len() != 2),+ "loose objects in a mirror"+ );+}++#[tokio::test]+async fn a_mirror_that_stopped_verifying_is_dropped_and_not_served() {+ let (_t, src, root) = dirs();+ let repo = source(&src, "a", 2, 32);+ let c = cache(&root, Some(1 << 30));+ assert!(matches!(c.ensure(&repo).await, Outcome::Filled { .. }));+ // A pack loses its tail.+ let pack = &c.entries()[0].packs[0].name;+ let p = store::mirror_dir(&root, &repo.key)+ .join("objects/pack")+ .join(pack);+ let len = std::fs::metadata(&p).unwrap().len();+ make_writable(&p);+ std::fs::OpenOptions::new()+ .write(true)+ .open(&p)+ .unwrap()+ .set_len(len - 10)+ .unwrap();+ // The helper in a Space reports it skipped the mirror; the daemon checks+ // and drops it.+ c.ingest_guest_log(&format!("1700000000 skipped {} 0\n", repo.key));+ assert!(c.entries().is_empty());+ assert!(!store::mirror_dir(&root, &repo.key).exists());+ assert!(+ !std::fs::read_to_string(root.join("gitconfig"))+ .unwrap()+ .contains(&repo.key)+ );+ // A fill after that makes a new one.+ assert!(matches!(c.ensure(&repo).await, Outcome::Filled { .. }));+}++#[tokio::test]+async fn the_cache_stays_within_its_cap_under_churn_and_drops_the_least_recently_used() {+ let (_t, src, root) = dirs();+ let cap: u64 = 700 * 1024;+ let c = cache(&root, Some(cap));+ let mut repos = Vec::new();+ for i in 0..8 {+ repos.push(source(&src, &format!("r{i}"), 2, 100));+ }+ for r in &repos {+ let _ = c.ensure(r).await;+ // Pretend each was last used long ago, so eviction may take it.+ for e in c.entries() {+ let mut e = e;+ e.used_ms = e+ .used_ms+ .saturating_sub(EVICTION_GRACE.as_millis() as u64 * 2)+ .min(store::now_ms() - 1_000_000);+ store::publish(&root, &e, false).unwrap();+ }+ let on_disk = store::dir_size(&store::m_dir(&root));+ let held: u64 = c.entries().iter().map(|e| e.bytes).sum();+ assert!(held <= cap, "held {held} over cap {cap}");+ // Everything under m/ (mirrors plus their small side files).+ assert!(+ on_disk <= cap + 16 * 1024,+ "on disk {on_disk} over cap {cap}"+ );+ }+ assert!(!c.entries().is_empty());+ assert!(c.entries().len() < 8);+}++#[tokio::test]+async fn nothing_is_taken_in_while_the_cache_is_full_of_recently_used_mirrors() {+ let (_t, src, root) = dirs();+ let a = source(&src, "a", 2, 100);+ let b = source(&src, "b", 2, 100);+ let c = cache(&root, Some(300 * 1024));+ assert!(matches!(c.ensure(&a).await, Outcome::Filled { .. }));+ // `a` was just used: it is not evicted for `b`, and `b` is not taken.+ assert_eq!(c.ensure(&b).await, Outcome::Skipped(Reason::CacheFull));+ assert_eq!(c.entries().len(), 1);+ assert!(std::fs::read_dir(store::tmp_dir(&root)).map_or(true, |mut d| d.next().is_none()));+}++#[tokio::test]+async fn a_repository_bigger_than_the_cache_is_not_cached() {+ let (_t, src, root) = dirs();+ let a = source(&src, "a", 3, 200);+ let c = cache(&root, Some(100 * 1024));+ assert!(matches!(+ c.ensure(&a).await,+ Outcome::Skipped(Reason::TooBig | Reason::CacheFull)+ ));+ assert!(c.entries().is_empty());+ assert!(store::dir_size(&root.join("tmp")) == 0);+}++#[tokio::test]+async fn off_means_nothing_is_cached_and_clear_empties_the_cache() {+ let (_t, src, root) = dirs();+ let a = source(&src, "a", 2, 16);+ let off = RepoCache::new(+ &root,+ Config {+ enabled: false,+ cap_bytes: None,+ },+ )+ .allowing_local_repos();+ assert_eq!(off.ensure(&a).await, Outcome::Skipped(Reason::Disabled));+ assert!(off.mount_source().is_none());+ let c = cache(&root, Some(1 << 30));+ assert!(matches!(c.ensure(&a).await, Outcome::Filled { .. }));+ assert_eq!(c.status().repos, 1);+ c.clear();+ assert_eq!(c.status().repos, 0);+ assert!(c.entries().is_empty());+ assert_eq!(+ store::dir_size(&store::m_dir(&root)),+ std::fs::metadata(root.join("m/..")).map(|_| 0).unwrap()+ );+}++#[tokio::test]+async fn an_unreachable_remote_is_a_quiet_skip() {+ let (_t, _src, root) = dirs();+ let c = cache(&root, Some(1 << 30));+ let missing = repo_url(Path::new("/nonexistent/cua-repo-cache-test"));+ assert!(matches!(+ c.ensure(&missing).await,+ Outcome::Skipped(Reason::Unreachable | Reason::Private)+ ));+ assert!(c.entries().is_empty());+}++#[tokio::test]+async fn hits_reported_by_a_space_show_in_the_week() {+ let (_t, src, root) = dirs();+ let a = source(&src, "a", 2, 16);+ let c = cache(&root, Some(1 << 30));+ assert!(matches!(c.ensure(&a).await, Outcome::Filled { .. }));+ c.ingest_guest_log(&format!(+ "1700000000 hit_lease {k} 0\n1700000001 hit_checked {k} 1\n1700000002 failed {k} 0\n",+ k = a.key+ ));+ let s = c.status();+ assert_eq!((s.hits, s.misses, s.repos), (2, 1, 1));+ assert!(s.bytes_saved > 0 && s.bytes > 0);+}++/// A clone made the way a Space makes it: the cache's system git config, the+/// helper on PATH, the mirror under the cache root.+fn clone_like_a_space(root: &Path, url: &str, dest: &Path, extra: &[&str]) -> std::process::Output {+ Command::new("git")+ .args(["clone", "-q"])+ .args(extra)+ .arg(url)+ .arg(dest)+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .env("GIT_CONFIG_SYSTEM", root.join("gitconfig"))+ .env("CUA_REPO_CACHE_ROOT", root)+ .env("CUA_REPO_CACHE_LOG", root.join("guest.log"))+ .env(+ "PATH",+ format!(+ "{}:{}",+ root.join("bin").display(),+ std::env::var("PATH").unwrap()+ ),+ )+ .output()+ .unwrap()+}++#[tokio::test]+async fn a_clone_through_the_helper_is_complete_independent_and_matches_the_remote() {+ let (t, src, root) = dirs();+ let repo = source(&src, "a", 4, 64);+ let c = cache(&root, Some(1 << 30));+ assert!(matches!(c.ensure(&repo).await, Outcome::Filled { .. }));+ // Within the lease the helper serves from the mirror with no remote.+ let dest = t.path().join("clone");+ let out = clone_like_a_space(&root, &repo.url, &dest, &[]);+ assert!(out.status.success(), "{out:?}");+ assert_eq!(+ git(&dest, &["rev-parse", "HEAD"]),+ git(&src.join("a"), &["rev-parse", "HEAD"])+ );+ assert_eq!(git(&dest, &["fsck", "--connectivity-only"]), "");+ // Own objects: no alternate, and the packs are the clone's own files.+ assert!(!dest.join(".git/objects/info/alternates").exists());+ assert!(+ std::fs::read_dir(dest.join(".git/objects/pack"))+ .unwrap()+ .flatten()+ .count()+ >= 2+ );+ // The clone keeps the remote's own URL.+ assert_eq!(git(&dest, &["config", "remote.origin.url"]), repo.url);+ // The helper logged a lease hit that the daemon can read.+ let log = std::fs::read_to_string(root.join("guest.log")).unwrap();+ assert!(log.contains(&format!("hit_lease {}", repo.key)), "{log}");+ c.ingest_guest_log(&log);+ assert_eq!(c.status().hits, 1);+ // Removing the mirror afterwards leaves the clone whole.+ c.clear();+ assert_eq!(git(&dest, &["fsck", "--full"]), "");+ assert_eq!(git(&dest, &["log", "--oneline"]).lines().count(), 4);+}++#[tokio::test]+async fn a_clone_past_the_lease_without_a_remote_goes_the_plain_way_and_is_never_stale() {+ let (t, src, root) = dirs();+ let repo = source(&src, "a", 2, 16);+ let c = cache(&root, Some(1 << 30));+ assert!(matches!(c.ensure(&repo).await, Outcome::Filled { .. }));+ // New commit upstream, the mirror not yet refreshed, the lease over.+ add_commit(&src.join("a"), 50, 16);+ std::fs::write(store::side(&root, &repo.key, "fresh"), "1\n").unwrap();+ // The helper hands over to `git remote-https`, which cannot reach a+ // file remote: the clone fails the same way a plain clone of this URL+ // would, and nothing stale is served.+ let dest = t.path().join("clone");+ let out = clone_like_a_space(&root, &repo.url, &dest, &[]);+ let plain = Command::new("git")+ .args(["clone", "-q", &repo.url])+ .arg(t.path().join("plain"))+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .env("GIT_CONFIG_SYSTEM", "/dev/null")+ .output()+ .unwrap();+ assert!(plain.status.success());+ assert!(+ !out.status.success(),+ "a stale mirror must not be served past the lease"+ );+ assert!(!dest.join(".git/objects/info/alternates").exists());+}++#[tokio::test]+async fn a_mirror_that_fails_the_helper_checks_is_skipped_and_the_clone_is_plain() {+ let (t, src, root) = dirs();+ let repo = source(&src, "a", 2, 16);+ let c = cache(&root, Some(1 << 30));+ assert!(matches!(c.ensure(&repo).await, Outcome::Filled { .. }));+ // Tamper: the pack is no longer the size that was verified.+ let pack = &c.entries()[0].packs[0].name;+ let p = store::mirror_dir(&root, &repo.key)+ .join("objects/pack")+ .join(pack);+ let mut data = std::fs::read(&p).unwrap();+ make_writable(&p);+ data.push(0);+ std::fs::write(&p, data).unwrap();+ let dest = t.path().join("clone");+ // Plain path: `git remote-https` cannot take a file URL, so this clone+ // fails; what matters is that the helper did not use the mirror.+ let _ = clone_like_a_space(&root, &repo.url, &dest, &[]);+ let log = std::fs::read_to_string(root.join("guest.log")).unwrap_or_default();+ assert!(!log.contains("hit_"), "{log}");+ assert!(log.contains(&format!("skipped {}", repo.key)), "{log}");+}++#[tokio::test]+async fn a_missing_mount_means_no_config_and_a_plain_clone() {+ let (t, src, root) = dirs();+ let repo = source(&src, "a", 2, 16);+ let c = cache(&root, Some(1 << 30));+ assert!(matches!(c.ensure(&repo).await, Outcome::Filled { .. }));+ // The Space's system config includes a file that is gone.+ let sys = t.path().join("etc-gitconfig");+ std::fs::write(+ &sys,+ format!("[include]\n\tpath = {}/missing/gitconfig\n", root.display()),+ )+ .unwrap();+ let dest = t.path().join("clone");+ let out = Command::new("git")+ .args(["clone", "-q", &repo.url])+ .arg(&dest)+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .env("GIT_CONFIG_SYSTEM", &sys)+ .output()+ .unwrap();+ assert!(out.status.success(), "{out:?}");+}++#[test]+fn the_helper_text_is_written_executable_and_is_valid_shell() {+ let (_t, _src, root) = dirs();+ let c = cache(&root, None);+ c.prepare().unwrap();+ let p = root.join("bin").join(shim::HELPER_NAME);+ use std::os::unix::fs::PermissionsExt as _;+ assert_eq!(+ std::fs::metadata(&p).unwrap().permissions().mode() & 0o111,+ 0o111+ );+ let out = Command::new("sh").arg("-n").arg(&p).output().unwrap();+ assert!(out.status.success(), "{out:?}");+}++#[test]+fn the_summary_is_plain_words() {+ use crate::{Status, size_words, time_words};+ assert_eq!(size_words(0), "0 MB");+ assert_eq!(size_words(340 * 1024 * 1024), "340 MB");+ assert_eq!(size_words(1_288_490_189), "1.2 GB");+ assert_eq!(size_words(5 << 30), "5 GB");+ assert_eq!(size_words(12 << 30), "12 GB");+ assert_eq!(time_words(20), "20 seconds");+ assert_eq!(time_words(125), "about 2 minutes");+ assert_eq!(time_words(3 * 3600), "about 3 hours");+ let s = Status {+ enabled: true,+ repos: 3,+ bytes: 1_288_490_189,+ cap_bytes: 5 << 30,+ hits: 8,+ misses: 2,+ seconds_saved: 125,+ bytes_saved: 0,+ };+ assert_eq!(s.size_line(), "Repos: 3, 1.2 GB of 5 GB");+ assert_eq!(+ s.week_line(),+ "Last week: 80% of clones came from the cache, about 2 minutes saved"+ );+ assert_eq!(Status::default().week_line(), "No clones yet this week");+ // No dot separators and no word the product avoids.+ for l in [s.size_line(), s.week_line()] {+ assert!(+ !l.contains('\u{b7}') && !l.to_lowercase().contains("device"),+ "{l}"+ );+ }+}++#[tokio::test]+async fn turning_the_cache_off_stops_spaces_using_what_it_holds() {+ let (_t, src, root) = dirs();+ let repo = source(&src, "a", 2, 16);+ let on = cache(&root, Some(1 << 30));+ assert!(matches!(on.ensure(&repo).await, Outcome::Filled { .. }));+ assert!(+ std::fs::read_to_string(root.join("gitconfig"))+ .unwrap()+ .contains(&repo.key)+ );+ let off = RepoCache::new(+ &root,+ Config {+ enabled: false,+ cap_bytes: None,+ },+ );+ off.sync_config();+ assert!(+ !std::fs::read_to_string(root.join("gitconfig"))+ .unwrap()+ .contains(&repo.key)+ );+ // The mirrors stay until they are cleared, and come back when it is on again.+ assert_eq!(on.entries().len(), 1);+ on.sync_config();+ assert!(+ std::fs::read_to_string(root.join("gitconfig"))+ .unwrap()+ .contains(&repo.key)+ );+}++#[tokio::test]+async fn a_repository_the_cache_does_not_hold_clones_the_plain_way_without_the_helper() {+ let (t, src, root) = dirs();+ let held = source(&src, "held", 2, 16);+ let other = source(&src, "other", 2, 16);+ let c = cache(&root, Some(1 << 30));+ assert!(matches!(c.ensure(&held).await, Outcome::Filled { .. }));+ // `other` has no mirror: its URL is not rewritten, the helper never runs.+ let dest = t.path().join("clone");+ let out = clone_like_a_space(&root, &other.url, &dest, &[]);+ assert!(out.status.success(), "{out:?}");+ assert!(+ !root.join("guest.log").exists(),+ "the helper ran for an unmirrored repository"+ );+ assert_eq!(+ git(&dest, &["rev-parse", "HEAD"]),+ git(&src.join("other"), &["rev-parse", "HEAD"])+ );+}++#[tokio::test]+async fn an_object_written_in_one_clone_is_in_no_other_clone_and_not_in_the_mirror() {+ let (t, src, root) = dirs();+ let repo = source(&src, "a", 2, 16);+ let c = cache(&root, Some(1 << 30));+ assert!(matches!(c.ensure(&repo).await, Outcome::Filled { .. }));+ let (a, b) = (t.path().join("a"), t.path().join("b"));+ for d in [&a, &b] {+ let out = clone_like_a_space(&root, &repo.url, d, &[]);+ assert!(out.status.success(), "{out:?}");+ }+ let canary = Command::new("sh")+ .current_dir(&a)+ .arg("-c")+ .arg("echo canary-object | git hash-object -w --stdin")+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .output()+ .unwrap();+ let h = String::from_utf8(canary.stdout).unwrap().trim().to_string();+ let seen = |dir: &Path| {+ Command::new("git")+ .current_dir(dir)+ .args(["cat-file", "-e", &h])+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .status()+ .unwrap()+ .success()+ };+ assert!(seen(&a));+ assert!(!seen(&b), "another clone sees it");+ assert!(+ !seen(&store::mirror_dir(&root, &repo.key)),+ "the mirror has it"+ );+}diff --git a/libs/cua/crates/cua-repo-cache/src/url.rs b/libs/cua/crates/cua-repo-cache/src/url.rsnew file mode 100644index 0000000000..d3e643a5da--- /dev/null+++ b/libs/cua/crates/cua-repo-cache/src/url.rs@@ -0,0 +1,253 @@+//! Which repositories the cache will mirror: public `https` repositories on a+//! public host, named by a normalized URL, and how a command line names+//! them.++use sha2::{Digest, Sha256};+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};++/// A repository the cache can hold: its normalized URL and the key its+/// mirror is stored under.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct RepoUrl {+ /// `https://host/path`: lowercase host, no port, userinfo, query,+ /// fragment, trailing slash or `.git`.+ pub url: String,+ /// 16 hex digits of the SHA-256 of [`RepoUrl::url`].+ pub key: String,+ /// The host.+ pub host: String,+}++/// Why a URL is not one the cache holds.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Unsupported;++/// The most URLs [`urls_in`] takes from one command line.+const MAX_URLS_PER_TEXT: usize = 4;++/// Normalizes `raw`. Only `https` on the default port, with no credentials+/// in it and a host name (not an address), is a repository the cache holds.+pub fn parse(raw: &str) -> Result<RepoUrl, Unsupported> {+ let raw = raw.trim();+ if raw.is_empty() || raw.len() > 512 {+ return Err(Unsupported);+ }+ let u = url::Url::parse(raw).map_err(|_| Unsupported)?;+ if u.scheme() != "https"+ || !u.username().is_empty()+ || u.password().is_some()+ || u.query().is_some()+ || u.fragment().is_some()+ || u.port().is_some_and(|p| p != 443)+ {+ return Err(Unsupported);+ }+ let host = match u.host() {+ Some(url::Host::Domain(d)) => d.to_ascii_lowercase(),+ _ => return Err(Unsupported),+ };+ if !host.contains('.') || host == "localhost" || host.ends_with(".local") {+ return Err(Unsupported);+ }+ let mut path = u.path().trim_end_matches('/').to_string();+ if let Some(p) = path.strip_suffix(".git") {+ path = p.trim_end_matches('/').to_string();+ }+ // `https://host/owner/repo` at least; no dot segments or odd bytes.+ if path.matches('/').count() < 2+ || path+ .split('/')+ .any(|s| s == ".." || s == "." || s.contains('\\'))+ || !path+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b"/-._~%+".contains(&b))+ {+ return Err(Unsupported);+ }+ let url = format!("https://{host}{path}");+ let key = hex::encode(&Sha256::digest(url.as_bytes())[..8]);+ Ok(RepoUrl { url, key, host })+}++/// The repositories a command line clones: every `https://` word of a text+/// that says `git` and `clone` (or `fetch`, `submodule`).+pub fn urls_in(text: &str) -> Vec<RepoUrl> {+ if text.len() > 64 * 1024 || !text.contains("git") {+ return Vec::new();+ }+ if !["clone", "fetch", "pull", "submodule"]+ .iter()+ .any(|w| text.contains(w))+ {+ return Vec::new();+ }+ let mut out: Vec<RepoUrl> = Vec::new();+ let mut rest = text;+ while let Some(at) = rest.find("https://") {+ let tail = &rest[at..];+ let end = tail+ .find(|c: char| c.is_whitespace() || "'\"<>)(;|&`\\".contains(c))+ .unwrap_or(tail.len());+ if let Ok(r) = parse(&tail[..end])+ && !out.iter().any(|o| o.key == r.key)+ {+ out.push(r);+ if out.len() >= MAX_URLS_PER_TEXT {+ break;+ }+ }+ rest = &tail[end.max(1)..];+ }+ out+}++/// Whether `ip` is an address anyone on the internet can reach (not this+/// machine, a private network, link-local, shared or reserved space).+pub fn ip_is_public(ip: IpAddr) -> bool {+ match ip {+ IpAddr::V4(v4) => v4_is_public(v4),+ IpAddr::V6(v6) => v6_is_public(v6),+ }+}++fn v4_is_public(ip: Ipv4Addr) -> bool {+ let o = ip.octets();+ !(ip.is_loopback()+ || ip.is_private()+ || ip.is_link_local()+ || ip.is_unspecified()+ || ip.is_broadcast()+ || ip.is_multicast()+ || ip.is_documentation()+ // Shared address space, benchmarking, reserved and protocol blocks.+ || (o[0] == 100 && (64..128).contains(&o[1]))+ || (o[0] == 198 && (o[1] == 18 || o[1] == 19))+ || o[0] == 0+ || o[0] >= 240+ || (o[0] == 192 && o[1] == 0 && o[2] == 0))+}++fn v6_is_public(ip: Ipv6Addr) -> bool {+ if let Some(v4) = ip.to_ipv4_mapped() {+ return v4_is_public(v4);+ }+ let s = ip.segments();+ !(ip.is_loopback()+ || ip.is_unspecified()+ || ip.is_multicast()+ // Unique local fc00::/7, link-local fe80::/10, documentation 2001:db8::/32.+ || (s[0] & 0xfe00) == 0xfc00+ || (s[0] & 0xffc0) == 0xfe80+ || (s[0] == 0x2001 && s[1] == 0x0db8)+ // NAT64 and 6to4 can wrap a private v4 address.+ || (s[0] == 0x0064 && s[1] == 0xff9b)+ || s[0] == 0x2002)+}++/// Whether every address `host` resolves to is public: the daemon never+/// mirrors from a host on this machine or a network behind it (a Space+/// without access to that network would get the repository through the+/// mirror).+pub async fn host_is_public(host: &str) -> bool {+ let host = host.to_string();+ let resolved = tokio::time::timeout(+ std::time::Duration::from_secs(5),+ tokio::net::lookup_host((host, 443)),+ )+ .await;+ let Ok(Ok(addrs)) = resolved else {+ return false;+ };+ let mut any = false;+ for a in addrs {+ any = true;+ if !ip_is_public(a.ip()) {+ return false;+ }+ }+ any+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn urls_normalize_to_one_spelling() {+ let a = parse("https://GitHub.com/vitejs/vite.git").unwrap();+ let b = parse("https://github.com/vitejs/vite/").unwrap();+ let c = parse("https://github.com/vitejs/vite").unwrap();+ assert_eq!(a, b);+ assert_eq!(b, c);+ assert_eq!(a.url, "https://github.com/vitejs/vite");+ assert_eq!(a.key.len(), 16);+ assert_ne!(+ a.key,+ parse("https://github.com/vitejs/vitest").unwrap().key+ );+ }++ #[test]+ fn only_plain_public_https_repositories_qualify() {+ for bad in [+ "http://github.com/o/r",+ "ssh://[email protected]/o/r",+ "[email protected]:o/r.git",+ "https://user:[email protected]/o/r",+ "https://[email protected]/o/r",+ "https://github.com:8443/o/r",+ "https://github.com/o/r?x=1",+ "https://github.com/o/r#frag",+ "https://127.0.0.1/o/r",+ "https://[::1]/o/r",+ "https://localhost/o/r",+ "https://intranet/o/r",+ "https://github.com/o",+ "https://github.com/o/../r",+ "file:///etc/passwd",+ "",+ ] {+ assert!(parse(bad).is_err(), "{bad}");+ }+ assert!(parse("https://gitlab.com/group/sub/project.git").is_ok());+ }++ #[test]+ fn a_command_line_names_the_repositories_it_clones() {+ let found = urls_in(+ "cd /work && git clone --depth 1 https://github.com/vitejs/vite.git app; \+ git clone 'https://gitlab.com/g/p' x",+ );+ assert_eq!(+ found.iter().map(|r| r.url.as_str()).collect::<Vec<_>>(),+ ["https://github.com/vitejs/vite", "https://gitlab.com/g/p"]+ );+ // A URL with credentials is never taken, and text that does not+ // clone names nothing.+ assert!(urls_in("git clone https://u:[email protected]/o/r").is_empty());+ assert!(urls_in("curl https://github.com/o/r").is_empty());+ assert!(urls_in("echo git https://github.com/o/r").is_empty());+ }++ #[test]+ fn private_and_reserved_addresses_are_not_public() {+ for ip in [+ "127.0.0.1",+ "10.1.2.3",+ "172.16.0.1",+ "192.168.1.1",+ "169.254.169.254",+ "100.64.0.1",+ "0.0.0.0",+ "::1",+ "fd00::1",+ "fe80::1",+ "::ffff:10.0.0.1",+ ] {+ assert!(!ip_is_public(ip.parse().unwrap()), "{ip}");+ }+ for ip in ["140.82.112.3", "8.8.8.8", "2606:50c0:8000::154"] {+ assert!(ip_is_public(ip.parse().unwrap()), "{ip}");+ }+ }+}diff --git a/libs/cua/crates/cua-sandbox-core/Cargo.toml b/libs/cua/crates/cua-sandbox-core/Cargo.tomlindex 564895f4c5..98b1378131 100644--- a/libs/cua/crates/cua-sandbox-core/Cargo.toml+++ b/libs/cua/crates/cua-sandbox-core/Cargo.toml@@ -16,6 +16,7 @@ testing = ["rmcp/server", "rmcp/transport-streamable-http-server", "dep:axum"][dependencies]cua-home.workspace = true+cua-repo-cache.workspace = truermcp = { workspace = true, features = ["client", "transport-streamable-http-client-reqwest", "reqwest-tls-no-provider", "base64"] }axum = { workspace = true, optional = true }# External runtime providers send guest output and screenshots as base64.diff --git a/libs/cua/crates/cua-sandbox-core/src/lib.rs b/libs/cua/crates/cua-sandbox-core/src/lib.rsindex 1d270a5350..2c3e46bb33 100644--- a/libs/cua/crates/cua-sandbox-core/src/lib.rs+++ b/libs/cua/crates/cua-sandbox-core/src/lib.rs@@ -51,6 +51,7 @@ pub mod profile;pub mod provider;pub mod proxy;pub mod refs;+pub mod repo_cache;mod runtime;mod sandbox;pub mod settings;diff --git a/libs/cua/crates/cua-sandbox-core/src/repo_cache.rs b/libs/cua/crates/cua-sandbox-core/src/repo_cache.rsnew file mode 100644index 0000000000..b2d0ca05f9--- /dev/null+++ b/libs/cua/crates/cua-sandbox-core/src/repo_cache.rs@@ -0,0 +1,56 @@+//! The repo cache with this machine's settings (`cache.repos` and+//! `cache.repos_size_gb`, see [`crate::settings`]).++pub use cua_repo_cache::{+ Config, DEFAULT_CAP_BYTES, Entry, GUEST_ROOT, Outcome, Reason, RepoCache, RepoUrl, Status, shim,+};++/// The cache under `$CUA_HOME` with the settings read now: on unless+/// `cache.repos` is off, capped by `cache.repos_size_gb` (else the default).+pub fn current() -> RepoCache {+ let (enabled, cap_bytes) = crate::settings::Settings::load()+ .map(|s| s.repo_cache())+ .unwrap_or((true, None));+ RepoCache::at_default(Config { enabled, cap_bytes })+}++/// Whether a command line may clone a repository (a cheap check: no+/// settings are read for a command that does not).+pub fn names_a_clone(command: &str) -> bool {+ !cua_repo_cache::url::urls_in(command).is_empty()+}++/// The repo cache's directory as a container Space gets it: read-only, at+/// [`GUEST_ROOT`], and nothing else (no network, no other host directory).+pub fn mount(root: std::path::PathBuf) -> cua_vmm::Mount {+ cua_vmm::Mount {+ host: root,+ guest: GUEST_ROOT.to_string(),+ read_only: true,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_cache_mount_is_read_only_at_the_guest_root_and_accepted_by_a_container_backend() {+ let dir = tempfile::tempdir().unwrap();+ let m = mount(dir.path().to_path_buf());+ assert!(m.read_only);+ assert_eq!(m.guest, "/cua/repo-cache");+ assert_eq!(m.host, dir.path());+ cua_vmm::types::check_mounts(cua_vmm::BackendKind::Container, std::slice::from_ref(&m))+ .unwrap();+ }++ #[test]+ fn a_clone_in_a_space_never_names_a_secret_or_a_url_in_what_the_helper_logs() {+ // The helper's log line is a time, a fixed word, the repository's+ // hash key and seconds: the parser takes nothing else.+ let l = shim::parse_log("1700000000 hit_checked 0123456789abcdef 1\n");+ assert_eq!(l.len(), 1);+ assert!(shim::parse_log("1700000000 hit_checked https://github.com/o/r 1\n").is_empty());+ }+}diff --git a/libs/cua/crates/cua-sandbox-core/src/settings.rs b/libs/cua/crates/cua-sandbox-core/src/settings.rsindex 973f7a9852..441c73070c 100644--- a/libs/cua/crates/cua-sandbox-core/src/settings.rs+++ b/libs/cua/crates/cua-sandbox-core/src/settings.rs@@ -35,7 +35,7 @@ pub struct Key {}/// Every setting, in display order.-pub const KEYS: [Key; 17] = [+pub const KEYS: [Key; 19] = [Key {name: "default.on",env: "CUA_DEFAULT_ON",@@ -120,6 +120,18 @@ pub const KEYS: [Key; 17] = [default: "on",description: "when no location is given and a linked cloud has a budget (`cua cloud budget`), Spaces go to this machine first and overflow into your clouds when it is full, never past the budget (off: this machine only)",},+ Key {+ name: "cache.repos",+ env: "CUA_CACHE_REPOS",+ default: "on",+ description: "the repo cache: public git repositories this machine keeps a verified copy of, so a repeat `git clone` in a Space starts from it (on, off). Only public repositories, only on this machine's disk; `cua host cache clear` empties it",+ },+ Key {+ name: "cache.repos_size_gb",+ env: "CUA_CACHE_REPOS_SIZE_GB",+ default: "auto",+ description: "the most disk the repo cache may use, in GB (auto: the smaller of 5 GB and a tenth of the free disk); the least recently used repositories go first",+ },Key {name: "pool.memory_percent",env: "CUA_POOL_MEMORY_PERCENT",@@ -517,6 +529,27 @@ impl Settings {.unwrap_or(true)}+ /// The repo cache's settings: whether it is on (`cache.repos`, default+ /// on) and its size cap in bytes (`cache.repos_size_gb`; `None`: auto).+ pub fn repo_cache(&self) -> (bool, Option<u64>) {+ let on = key("cache.repos")+ .map(|k| self.entry(k).value)+ .map(|v| {+ !matches!(+ v.trim().to_ascii_lowercase().as_str(),+ "off" | "false" | "0" | "no"+ )+ })+ .unwrap_or(true);+ let cap = key("cache.repos_size_gb")+ .map(|k| self.entry(k).value)+ .ok()+ .and_then(|v| v.trim().parse::<f64>().ok())+ .filter(|g| g.is_finite() && *g >= 0.0)+ .map(|g| (g * f64::from(1u32 << 30)) as u64);+ (on, cap)+ }+/// The default kind and where it came from.pub fn default_kind(&self) -> Result<(Kind, Source), SettingsError> {self.parsed(KEYS[1], Kind::parse)@@ -565,6 +598,38 @@ pub fn normalize(key: Key, value: &str) -> Result<String, SettingsError> {)));}},+ "cache.repos" => match v.to_ascii_lowercase().as_str() {+ "1" | "true" | "yes" | "on" => "on".into(),+ "0" | "false" | "no" | "off" => "off".into(),+ _ => {+ return Err(SettingsError(format!(+ "cache.repos: expected on or off, got {v:?}"+ )));+ }+ },+ "cache.repos_size_gb" => {+ if v.eq_ignore_ascii_case("auto") || v.is_empty() {+ "auto".into()+ } else {+ let g: f64 = v.parse().map_err(|_| {+ SettingsError(format!(+ "cache.repos_size_gb: expected auto or a number of GB, got {v:?}"+ ))+ })?;+ if !g.is_finite() || !(0.0..=100_000.0).contains(&g) {+ return Err(SettingsError(+ "cache.repos_size_gb: expected auto or a number of GB between 0 and 100000"+ .into(),+ ));+ }+ // 0 means nothing is cached.+ if g.fract() == 0.0 {+ format!("{}", g as u64)+ } else {+ format!("{g}")+ }+ }+ }"pool.auto" => match v.to_ascii_lowercase().as_str() {"1" | "true" | "yes" | "on" => "on".into(),"0" | "false" | "no" | "off" => "off".into(),@@ -772,6 +837,30 @@ mod tests {assert!(list.iter().all(|e| e.source == Source::Default));}+ /// The repo cache is on by default with an automatic size; the words and+ /// numbers a person sets are checked.+ #[test]+ fn the_repo_cache_settings() {+ let d = tempfile::tempdir().unwrap();+ let mut s = settings(d.path(), &[]);+ assert_eq!(s.repo_cache(), (true, None));+ s.set(key("cache.repos").unwrap(), "off").unwrap();+ s.set(key("cache.repos_size_gb").unwrap(), "2.5").unwrap();+ assert_eq!(s.repo_cache(), (false, Some(2_684_354_560)));+ s.set(key("cache.repos").unwrap(), "yes").unwrap();+ s.set(key("cache.repos_size_gb").unwrap(), "auto").unwrap();+ assert_eq!(s.repo_cache(), (true, None));+ let e = s+ .set(key("cache.repos_size_gb").unwrap(), "lots")+ .unwrap_err();+ assert!(e.0.contains("cache.repos_size_gb"), "{e}");+ let e = s.set(key("cache.repos").unwrap(), "maybe").unwrap_err();+ assert!(e.0.contains("expected on or off"), "{e}");+ // The environment wins over the file.+ let s = settings(d.path(), &[("CUA_CACHE_REPOS", "off")]);+ assert!(!s.repo_cache().0);+ }+/// explicit > env > config > default, for each axis.#[test]fn precedence() {diff --git a/libs/cua/crates/cua-sdk/src/native/config.rs b/libs/cua/crates/cua-sdk/src/native/config.rsindex 0ffc34ad58..70e8048ab5 100644--- a/libs/cua/crates/cua-sdk/src/native/config.rs+++ b/libs/cua/crates/cua-sdk/src/native/config.rs@@ -194,3 +194,74 @@ mod tests {check_placement("".into(), "".into(), "".into()).unwrap();}}++/// What the repo cache holds and what it saved, in plain words for+/// Settings (`cache.repos` and `cache.repos_size_gb` are its settings,+/// changed with [`config_set`]).+#[derive(Debug, Clone, PartialEq, uniffi::Record)]+pub struct RepoCacheStatus {+ /// The cache is on (`cache.repos`).+ pub enabled: bool,+ /// Repositories held.+ pub repos: u32,+ /// What they take on disk.+ pub bytes: u64,+ /// The size cap in force.+ pub cap_bytes: u64,+ /// The size setting: `auto`, or the number of GB.+ pub size_setting: String,+ /// `Repos: 3, 1.2 GB of 5 GB`.+ pub summary: String,+ /// `Last week: 80% of clones came from the cache, about 2 minutes saved`.+ pub week: String,+ /// Clones served from the cache in the last week.+ pub hits: u32,+ /// Clones that downloaded in the last week.+ pub misses: u32,+ /// Seconds the hits saved.+ pub seconds_saved: u64,+}++fn repo_cache_status_of(s: &Settings) -> RepoCacheStatus {+ let cache = cua_sandbox_core::repo_cache::RepoCache::at_default({+ let (enabled, cap_bytes) = s.repo_cache();+ cua_sandbox_core::repo_cache::Config { enabled, cap_bytes }+ });+ cache.sync_config();+ let st = cache.status();+ RepoCacheStatus {+ enabled: st.enabled,+ repos: st.repos,+ bytes: st.bytes,+ cap_bytes: st.cap_bytes,+ size_setting: s+ .configured(settings::key("cache.repos_size_gb").expect("known key"))+ .unwrap_or_else(|| "auto".into()),+ summary: st.size_line(),+ week: st.week_line(),+ hits: st.hits,+ misses: st.misses,+ seconds_saved: st.seconds_saved,+ }+}++/// The repo cache now: on or off, how much it holds of its cap, and what+/// the last week saved.+#[uniffi::export]+pub fn repo_cache_status() -> Result<RepoCacheStatus> {+ Ok(repo_cache_status_of(&load()?))+}++/// Deletes every repository the repo cache holds (they are copied again the+/// next time a Space clones them). Returns the cache after.+#[uniffi::export]+pub fn repo_cache_clear() -> Result<RepoCacheStatus> {+ let s = load()?;+ let (enabled, cap_bytes) = s.repo_cache();+ cua_sandbox_core::repo_cache::RepoCache::at_default(cua_sandbox_core::repo_cache::Config {+ enabled,+ cap_bytes,+ })+ .clear();+ Ok(repo_cache_status_of(&s))+}diff --git a/libs/cua/crates/cua-spaces/src/exec.rs b/libs/cua/crates/cua-spaces/src/exec.rsindex 9b8f8e3a5d..95500e17b3 100644--- a/libs/cua/crates/cua-spaces/src/exec.rs+++ b/libs/cua/crates/cua-spaces/src/exec.rs@@ -106,6 +106,9 @@ impl Space {/// Runs `command` in the Space's shell and collects its output.pub async fn bash(&self, command: &str, timeout: Duration) -> Result<BashOutput> {+ // A clone of a public repository is learned (the repo cache); what+ // the command does is not changed.+ crate::repo_cache::observe_command(self, command);let out = self.spacesd()?.run(self.shell_command(command).timeout(timeout))diff --git a/libs/cua/crates/cua-spaces/src/lib.rs b/libs/cua/crates/cua-spaces/src/lib.rsindex 17b3c8bdcc..ed0c4416ee 100644--- a/libs/cua/crates/cua-spaces/src/lib.rs+++ b/libs/cua/crates/cua-spaces/src/lib.rs@@ -91,6 +91,7 @@ pub mod prewarm;pub mod registry;pub mod relay;pub mod rename;+mod repo_cache;pub mod resources;pub mod route;pub mod routines;diff --git a/libs/cua/crates/cua-spaces/src/repo_cache.rs b/libs/cua/crates/cua-spaces/src/repo_cache.rsnew file mode 100644index 0000000000..ee2a52da60--- /dev/null+++ b/libs/cua/crates/cua-spaces/src/repo_cache.rs@@ -0,0 +1,82 @@+//! The repo cache in a local Space: installing what makes a plain+//! `git clone` use it, learning from the clones the daemon can see, and+//! reading back what the Space's helper did. Every failure here is silent:+//! the Space simply clones the normal way.++use std::collections::HashSet;+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++use cua_sandbox_core::repo_cache::{self, shim};++use crate::space::Space;++/// Local Spaces whose git uses the cache now.+fn installed() -> &'static Mutex<HashSet<String>> {+ static S: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();+ S.get_or_init(Default::default)+}++/// Makes a Space that just came up use the cache: installs the helper next to+/// its git and includes the cache's git config (a script that does nothing in+/// a Space without the mount, without git, or without the rights). Takes+/// well under a tenth of a second and never longer than a few seconds.+pub(crate) async fn install(space: &Space, name: &str) {+ let cache = repo_cache::current();+ if !cache.config().enabled || cache.prepare().is_err() {+ return;+ }+ let script = shim::install_script();+ let run = tokio::time::timeout(+ Duration::from_secs(4),+ space.bash(&script, Duration::from_secs(3)),+ )+ .await;+ if let Ok(Ok(out)) = run+ && out.success()+ && out.stdout.contains(shim::INSTALLED_MARKER)+ && let Ok(mut s) = installed().lock()+ {+ s.insert(name.to_string());+ }+}++/// A command run in a Space: what it clones is learned (see+/// [`cua_sandbox_core::repo_cache::RepoCache::learn`]), and what the Space's+/// helper logged since is counted. Local Spaces only.+pub(crate) fn observe_command(space: &Space, command: &str) {+ if !matches!(space.id(), crate::id::SpaceId::Local { .. }) {+ return;+ }+ // Most commands clone nothing: no settings are read for them.+ if repo_cache::names_a_clone(command) {+ repo_cache::current().learn(command);+ }+}++/// Counts what the helper in `space` logged since last asked, when its git+/// uses the cache. Bounded to a second and a half.+pub(crate) async fn collect(space: &Space, name: &str) {+ let uses = installed().lock().is_ok_and(|s| s.contains(name));+ if !uses {+ return;+ }+ let cmd = shim::take_log_command();+ let run = tokio::time::timeout(+ Duration::from_millis(1500),+ space.bash(&cmd, Duration::from_secs(1)),+ )+ .await;+ if let Ok(Ok(out)) = run+ && !out.stdout.is_empty()+ {+ repo_cache::current().ingest_guest_log(&out.stdout);+ }+}++/// The Space is gone (deleted or stopped): it no longer uses the cache.+pub(crate) fn forget(name: &str) {+ if let Ok(mut s) = installed().lock() {+ s.remove(name);+ }+}diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rsindex 940d96cca7..4c06c53918 100644--- a/libs/cua/crates/cua-spaces/src/spaces.rs+++ b/libs/cua/crates/cua-spaces/src/spaces.rs@@ -2878,6 +2878,16 @@ impl Spaces {return Err(e);}};+ // A container Space reads the repo cache through a read-only mount:+ // its git gets the helper (best effort, bounded, silent).+ let guest_os = crate::host_spaces::resolve_image(&image).1;+ if opts.kind != Kind::Vm+ && opts.kind != Kind::MicroVm+ && guest_os != "macos"+ && guest_os != "windows"+ {+ crate::repo_cache::install(&space, &name).await;+ }self.store(&space, credential)?;self.inner.connections@@ -3109,6 +3119,12 @@ impl Spaces {async fn delete_copy_of(&self, id: SpaceId) -> Result<String> {self.learn_usage_before_delete(&id.to_string()).await;+ if let SpaceId::Local { name } = &id {+ if let Ok(space) = self.space(&id.to_string()).await {+ crate::repo_cache::collect(&space, name).await;+ }+ crate::repo_cache::forget(name);+ }// A Space added by address keeps running: if it is attached to the// relay, its driver is asked to leave while it is still reachable.#[cfg(feature = "spaces-agents")]diff --git a/libs/cua/crates/cua-telemetry/src/agent_runs.rs b/libs/cua/crates/cua-telemetry/src/agent_runs.rsindex dd9dc9d88d..473b64a4a1 100644--- a/libs/cua/crates/cua-telemetry/src/agent_runs.rs+++ b/libs/cua/crates/cua-telemetry/src/agent_runs.rs@@ -158,6 +158,25 @@ impl Telemetry {}}+ /// What the repo cache did for one clone (`cua_repo_cache`): only fixed+ /// words and numbers, never a URL, a repository name or a path.+ pub fn repo_cache(+ &self,+ outcome: &str,+ source: &str,+ bytes_saved: u64,+ seconds_saved: u64,+ reason: &str,+ ) -> Captured {+ if !self.is_enabled() {+ return Captured::Disabled;+ }+ match events::repo_cache(outcome, source, bytes_saved, seconds_saved, reason) {+ Some(ev) => self.capture(ev),+ None => Captured::Invalid(format!("unknown repo cache outcome {outcome}")),+ }+ }+/// Whether this install started `run_id` and has not seen it end yet.pub fn agent_run_pending(&self, run_id: &str) -> bool {self.pending_path(run_id).is_some_and(|p| p.exists())diff --git a/libs/cua/crates/cua-telemetry/src/cli_commands.in b/libs/cua/crates/cua-telemetry/src/cli_commands.inindex 474c6843d3..a9d8088043 100644--- a/libs/cua/crates/cua-telemetry/src/cli_commands.in+++ b/libs/cua/crates/cua-telemetry/src/cli_commands.in@@ -113,6 +113,7 @@"doctor.parity","dump-docs","fleet",+ "host.cache","host.config","host.migrate","host.pair",diff --git a/libs/cua/crates/cua-telemetry/src/events.rs b/libs/cua/crates/cua-telemetry/src/events.rsindex 9cc6f12b5c..214195b48a 100644--- a/libs/cua/crates/cua-telemetry/src/events.rs+++ b/libs/cua/crates/cua-telemetry/src/events.rs@@ -1478,6 +1478,33 @@ pub fn agent_signin_imported(harness: &str) -> Event {.s("harness", pick(schema::SIGNIN_HARNESSES, harness, "other"))}+/// `cua_repo_cache`: what the repo cache did for one clone. Only fixed words+/// and numbers: `outcome` is `hit`, `miss` or `fallback`, `source` `local` or+/// `network`, `reason` one of [`schema::REPO_CACHE_REASONS`].+pub fn repo_cache(+ outcome: &str,+ source: &str,+ bytes_saved: u64,+ seconds_saved: u64,+ reason: &str,+) -> Option<Event> {+ let outcome = schema::REPO_CACHE_OUTCOMES+ .iter()+ .copied()+ .find(|o| *o == outcome)?;+ Some(+ Event::new(event::REPO_CACHE)+ .s("outcome", outcome)+ .s(+ "source",+ pick(schema::REPO_CACHE_SOURCES, source, "network"),+ )+ .n("bytes_saved", bytes_saved.min(1_000_000_000_000))+ .n("seconds_saved", seconds_saved.min(86_400))+ .s("reason", pick(schema::REPO_CACHE_REASONS, reason, "other")),+ )+}+/// `cua_agent_used_space`: an agent's tool call reached a Space and worked./// None for a tool that does not act inside a Space.pub fn agent_used_space(tool: &str) -> Option<Event> {diff --git a/libs/cua/crates/cua-telemetry/src/schema.rs b/libs/cua/crates/cua-telemetry/src/schema.rsindex 1e43808837..40cad503b7 100644--- a/libs/cua/crates/cua-telemetry/src/schema.rs+++ b/libs/cua/crates/cua-telemetry/src/schema.rs@@ -403,6 +403,29 @@ pub const INSTALL_ERROR_KINDS: &[&str] = &[pub const INSTALLERS: &[&str] = &["sh", "ps1"];/// What the install was asked to put on the machine (joined with `+`).pub const INSTALL_ITEMS: &[&str] = &["cli", "spaces", "cua_driver", "host"];+/// What the repo cache did for one clone (`cua_repo_cache`): a hit (served+/// from a mirror), a miss (no mirror yet), or a fallback (a mirror that could+/// not be used).+pub const REPO_CACHE_OUTCOMES: &[&str] = &["hit", "miss", "fallback"];+/// Where a cloned repository came from.+pub const REPO_CACHE_SOURCES: &[&str] = &["local", "network"];+/// Why the repo cache did not serve a clone: a fixed list, `none` for a hit+/// or a first sighting.+pub const REPO_CACHE_REASONS: &[&str] = &[+ "none",+ "disabled",+ "no_git",+ "unsupported_url",+ "host_not_public",+ "private",+ "unreachable",+ "too_big",+ "cache_full",+ "disk_full",+ "verify_failed",+ "fill_failed",+ "other",+];/// The kind of Spaces tool an agent's call used (`cua_agent_used_space`).pub const SPACE_TOOL_GROUPS: &[&str] =&["shell", "files", "computer", "services", "agents", "other"];@@ -923,6 +946,7 @@ pub mod event {pub const AGENT_RUN_STARTED: &str = "cua_agent_run_started";pub const AGENT_RUN_COMPLETED: &str = "cua_agent_run_completed";pub const AGENT_JOIN_PHASE: &str = "cua_agent_join_phase";+ pub const REPO_CACHE: &str = "cua_repo_cache";pub const BENCH_RUN_COMPLETED: &str = "cua_bench_run_completed";pub const DAEMON_STARTED: &str = "cua_daemon_started";pub const DAEMON_HEALTH: &str = "cua_daemon_health";@@ -1335,6 +1359,43 @@ pub const EVENTS: &[EventSpec] = &[],purpose: "How long an agent takes to join a Space and answer, step by step, per agent and runtime, cold and warm; where joins fail.",},+ EventSpec {+ name: event::REPO_CACHE,+ version: 1,+ tier: Tier::Usage,+ sample_rate: 1.0,+ products: AGENT_PRODUCTS,+ props: &[+ p(+ "outcome",+ Kind::Enum(REPO_CACHE_OUTCOMES),+ "What the repo cache did for one clone: hit (served from a mirror on this machine), miss (no mirror yet) or fallback (a mirror that could not be used, so the clone went the normal way).",+ ),+ p(+ "source",+ Kind::Enum(REPO_CACHE_SOURCES),+ "Where the repository came from: local (a mirror on this machine) or network.",+ ),+ p(+ "bytes_saved",+ Kind::Count {+ max: 1_000_000_000_000,+ },+ "Bytes a hit did not download (the mirror's size); 0 otherwise.",+ ),+ p(+ "seconds_saved",+ Kind::Count { max: 86_400 },+ "Seconds a hit saved against the network clone that filled the mirror; 0 otherwise.",+ ),+ p(+ "reason",+ Kind::Enum(REPO_CACHE_REASONS),+ "Why a clone was not served from the cache: a fixed word (private, host_not_public, verify_failed, cache_full, disk_full, and so on); none for a hit or a first sighting. Never a URL, a repository name or a path.",+ ),+ ],+ purpose: "Whether the repo cache makes repeat clones in Spaces faster, how often it can be used, and why it cannot. Counts and fixed words only.",+ },EventSpec {name: event::BENCH_RUN_COMPLETED,version: 1,diff --git a/libs/cua/crates/cua-telemetry/tests/privacy.rs b/libs/cua/crates/cua-telemetry/tests/privacy.rsindex 7b0c398561..8fd9b70c4c 100644--- a/libs/cua/crates/cua-telemetry/tests/privacy.rs+++ b/libs/cua/crates/cua-telemetry/tests/privacy.rs@@ -306,6 +306,19 @@ fn all_builders(s: &str) -> Vec<Event> {).is_none());+ v.push(events::repo_cache("hit", "local", 80_000_000, 4, "none").unwrap());+ v.push(events::repo_cache("fallback", "network", 0, 0, "verify_failed").unwrap());+ v.push(+ events::repo_cache(+ "miss",+ "https://github.com/o/r",+ 1 << 60,+ 1 << 60,+ "/Users/me/x",+ )+ .unwrap(),+ );+ assert!(events::repo_cache("https://github.com/o/r", "local", 0, 0, "none").is_none());v.push(events::agent_signin_imported("codex"));v.push(events::agent_signin_imported(s));v.push(events::agent_used_space("space_bash").unwrap());diff --git a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.ktindex 15c6a56b32..b3f7302b42 100644--- a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt+++ b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt@@ -829,6 +829,10 @@ external fun uniffi_cua_sdk_checksum_func_config_unset(): Shortexternal fun uniffi_cua_sdk_checksum_func_locations(): Short+external fun uniffi_cua_sdk_checksum_func_repo_cache_clear(+): Short+external fun uniffi_cua_sdk_checksum_func_repo_cache_status(+): Shortexternal fun uniffi_cua_sdk_checksum_func_canonical_image(): Shortexternal fun uniffi_cua_sdk_checksum_func_canonical_image_tier(@@ -2900,6 +2904,10 @@ external fun uniffi_cua_sdk_fn_func_config_unset(`key`: RustBuffer.ByValue,uniff): RustBuffer.ByValueexternal fun uniffi_cua_sdk_fn_func_locations(uniffi_out_err: UniffiRustCallStatus,): RustBuffer.ByValue+external fun uniffi_cua_sdk_fn_func_repo_cache_clear(uniffi_out_err: UniffiRustCallStatus,+): RustBuffer.ByValue+external fun uniffi_cua_sdk_fn_func_repo_cache_status(uniffi_out_err: UniffiRustCallStatus,+): RustBuffer.ByValueexternal fun uniffi_cua_sdk_fn_func_canonical_image(`os`: RustBuffer.ByValue,`version`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,): RustBuffer.ByValueexternal fun uniffi_cua_sdk_fn_func_canonical_image_tier(`os`: RustBuffer.ByValue,`version`: RustBuffer.ByValue,`tier`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,@@ -3140,6 +3148,12 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cua_sdk_checksum_func_locations() != 62174.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}+ if (lib.uniffi_cua_sdk_checksum_func_repo_cache_clear() != 39088.toShort()) {+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ }+ if (lib.uniffi_cua_sdk_checksum_func_repo_cache_status() != 20147.toShort()) {+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ }if (lib.uniffi_cua_sdk_checksum_func_canonical_image() != 8955.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}@@ -40407,6 +40421,119 @@ public object FfiConverterTypeRelayMachine: FfiConverterRustBuffer<RelayMachine>+/**+ * What the repo cache holds and what it saved, in plain words for+ * Settings (`cache.repos` and `cache.repos_size_gb` are its settings,+ * changed with [`config_set`]).+ */+data class RepoCacheStatus (+ /**+ * The cache is on (`cache.repos`).+ */+ var `enabled`: kotlin.Boolean+ ,+ /**+ * Repositories held.+ */+ var `repos`: kotlin.UInt+ ,+ /**+ * What they take on disk.+ */+ var `bytes`: kotlin.ULong+ ,+ /**+ * The size cap in force.+ */+ var `capBytes`: kotlin.ULong+ ,+ /**+ * The size setting: `auto`, or the number of GB.+ */+ var `sizeSetting`: kotlin.String+ ,+ /**+ * `Repos: 3, 1.2 GB of 5 GB`.+ */+ var `summary`: kotlin.String+ ,+ /**+ * `Last week: 80% of clones came from the cache, about 2 minutes saved`.+ */+ var `week`: kotlin.String+ ,+ /**+ * Clones served from the cache in the last week.+ */+ var `hits`: kotlin.UInt+ ,+ /**+ * Clones that downloaded in the last week.+ */+ var `misses`: kotlin.UInt+ ,+ /**+ * Seconds the hits saved.+ */+ var `secondsSaved`: kotlin.ULong++){++++++ companion object+}++/**+ * @suppress+ */+public object FfiConverterTypeRepoCacheStatus: FfiConverterRustBuffer<RepoCacheStatus> {+ override fun read(buf: ByteBuffer): RepoCacheStatus {+ return RepoCacheStatus(+ FfiConverterBoolean.read(buf),+ FfiConverterUInt.read(buf),+ FfiConverterULong.read(buf),+ FfiConverterULong.read(buf),+ FfiConverterString.read(buf),+ FfiConverterString.read(buf),+ FfiConverterString.read(buf),+ FfiConverterUInt.read(buf),+ FfiConverterUInt.read(buf),+ FfiConverterULong.read(buf),+ )+ }++ override fun allocationSize(value: RepoCacheStatus) = (+ FfiConverterBoolean.allocationSize(value.`enabled`) ++ FfiConverterUInt.allocationSize(value.`repos`) ++ FfiConverterULong.allocationSize(value.`bytes`) ++ FfiConverterULong.allocationSize(value.`capBytes`) ++ FfiConverterString.allocationSize(value.`sizeSetting`) ++ FfiConverterString.allocationSize(value.`summary`) ++ FfiConverterString.allocationSize(value.`week`) ++ FfiConverterUInt.allocationSize(value.`hits`) ++ FfiConverterUInt.allocationSize(value.`misses`) ++ FfiConverterULong.allocationSize(value.`secondsSaved`)+ )++ override fun write(value: RepoCacheStatus, buf: ByteBuffer) {+ FfiConverterBoolean.write(value.`enabled`, buf)+ FfiConverterUInt.write(value.`repos`, buf)+ FfiConverterULong.write(value.`bytes`, buf)+ FfiConverterULong.write(value.`capBytes`, buf)+ FfiConverterString.write(value.`sizeSetting`, buf)+ FfiConverterString.write(value.`summary`, buf)+ FfiConverterString.write(value.`week`, buf)+ FfiConverterUInt.write(value.`hits`, buf)+ FfiConverterUInt.write(value.`misses`, buf)+ FfiConverterULong.write(value.`secondsSaved`, buf)+ }+}+++/*** A reference resolved for a backend.*/@@ -55177,6 +55304,36 @@ public object FfiConverterMapStringSequenceString: FfiConverterRustBuffer<Map<ko}+ /**+ * Deletes every repository the repo cache holds (they are copied again the+ * next time a Space clones them). Returns the cache after.+ */+ @Throws(CuaException::class) fun `repoCacheClear`(): RepoCacheStatus {+ return FfiConverterTypeRepoCacheStatus.lift(+ uniffiRustCallWithError(CuaException) { _status ->+ UniffiLib.uniffi_cua_sdk_fn_func_repo_cache_clear(++ _status)+}+ )+ }+++ /**+ * The repo cache now: on or off, how much it holds of its cap, and what+ * the last week saved.+ */+ @Throws(CuaException::class) fun `repoCacheStatus`(): RepoCacheStatus {+ return FfiConverterTypeRepoCacheStatus.lift(+ uniffiRustCallWithError(CuaException) { _status ->+ UniffiLib.uniffi_cua_sdk_fn_func_repo_cache_status(++ _status)+}+ )+ }++/*** The canonical image for `os` (`linux`, `windows`, `macos`) and* `version` (`None` = default: `ghcr.io/trycua/linux:24.04`,diff --git a/libs/cua/python/src/cua/_native.py b/libs/cua/python/src/cua/_native.pyindex fe8db584ab..839a084c27 100644--- a/libs/cua/python/src/cua/_native.py+++ b/libs/cua/python/src/cua/_native.py@@ -539,6 +539,10 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_func_qualify_sandbox_ref() != 59566:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_sdk_checksum_func_repo_cache_clear() != 39088:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_sdk_checksum_func_repo_cache_status() != 20147:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_func_resolve_image() != 56346:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_func_resolve_image_with_secret() != 48984:@@ -2379,6 +2383,14 @@ _UniffiLib.uniffi_cua_sdk_fn_func_qualify_sandbox_ref.argtypes = (ctypes.POINTER(_UniffiRustCallStatus),)_UniffiLib.uniffi_cua_sdk_fn_func_qualify_sandbox_ref.restype = _UniffiRustBuffer+_UniffiLib.uniffi_cua_sdk_fn_func_repo_cache_clear.argtypes = (+ ctypes.POINTER(_UniffiRustCallStatus),+)+_UniffiLib.uniffi_cua_sdk_fn_func_repo_cache_clear.restype = _UniffiRustBuffer+_UniffiLib.uniffi_cua_sdk_fn_func_repo_cache_status.argtypes = (+ ctypes.POINTER(_UniffiRustCallStatus),+)+_UniffiLib.uniffi_cua_sdk_fn_func_repo_cache_status.restype = _UniffiRustBuffer_UniffiLib.uniffi_cua_sdk_fn_func_resolve_image.argtypes = (_UniffiRustBuffer,_UniffiRustBuffer,@@ -4963,6 +4975,12 @@ _UniffiLib.uniffi_cua_sdk_checksum_func_presence_text_color.restype = ctypes.c_u_UniffiLib.uniffi_cua_sdk_checksum_func_qualify_sandbox_ref.argtypes = ()_UniffiLib.uniffi_cua_sdk_checksum_func_qualify_sandbox_ref.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_sdk_checksum_func_repo_cache_clear.argtypes = (+)+_UniffiLib.uniffi_cua_sdk_checksum_func_repo_cache_clear.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_sdk_checksum_func_repo_cache_status.argtypes = (+)+_UniffiLib.uniffi_cua_sdk_checksum_func_repo_cache_status.restype = ctypes.c_uint16_UniffiLib.uniffi_cua_sdk_checksum_func_resolve_image.argtypes = ()_UniffiLib.uniffi_cua_sdk_checksum_func_resolve_image.restype = ctypes.c_uint16@@ -20912,6 +20930,95 @@ class _UniffiFfiConverterTypeReadinessProbe(_UniffiConverterRustBuffer):_UniffiFfiConverterOptionalUInt16.write(value.http_status, buf)_UniffiFfiConverterOptionalString.write(value.service, buf)+@dataclass+class RepoCacheStatus:+ """+ What the repo cache holds and what it saved, in plain words for+ Settings (`cache.repos` and `cache.repos_size_gb` are its settings,+ changed with [`config_set`]).+"""+ def __init__(self, *, enabled:bool, repos:int, bytes:int, cap_bytes:int, size_setting:str, summary:str, week:str, hits:int, misses:int, seconds_saved:int):+ self.enabled = enabled+ self.repos = repos+ self.bytes = bytes+ self.cap_bytes = cap_bytes+ self.size_setting = size_setting+ self.summary = summary+ self.week = week+ self.hits = hits+ self.misses = misses+ self.seconds_saved = seconds_saved+++++ def __str__(self):+ return "RepoCacheStatus(enabled={}, repos={}, bytes={}, cap_bytes={}, size_setting={}, summary={}, week={}, hits={}, misses={}, seconds_saved={})".format(self.enabled, self.repos, self.bytes, self.cap_bytes, self.size_setting, self.summary, self.week, self.hits, self.misses, self.seconds_saved)+ def __eq__(self, other):+ if self.enabled != other.enabled:+ return False+ if self.repos != other.repos:+ return False+ if self.bytes != other.bytes:+ return False+ if self.cap_bytes != other.cap_bytes:+ return False+ if self.size_setting != other.size_setting:+ return False+ if self.summary != other.summary:+ return False+ if self.week != other.week:+ return False+ if self.hits != other.hits:+ return False+ if self.misses != other.misses:+ return False+ if self.seconds_saved != other.seconds_saved:+ return False+ return True++class _UniffiFfiConverterTypeRepoCacheStatus(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return RepoCacheStatus(+ enabled=_UniffiFfiConverterBoolean.read(buf),+ repos=_UniffiFfiConverterUInt32.read(buf),+ bytes=_UniffiFfiConverterUInt64.read(buf),+ cap_bytes=_UniffiFfiConverterUInt64.read(buf),+ size_setting=_UniffiFfiConverterString.read(buf),+ summary=_UniffiFfiConverterString.read(buf),+ week=_UniffiFfiConverterString.read(buf),+ hits=_UniffiFfiConverterUInt32.read(buf),+ misses=_UniffiFfiConverterUInt32.read(buf),+ seconds_saved=_UniffiFfiConverterUInt64.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterBoolean.check_lower(value.enabled)+ _UniffiFfiConverterUInt32.check_lower(value.repos)+ _UniffiFfiConverterUInt64.check_lower(value.bytes)+ _UniffiFfiConverterUInt64.check_lower(value.cap_bytes)+ _UniffiFfiConverterString.check_lower(value.size_setting)+ _UniffiFfiConverterString.check_lower(value.summary)+ _UniffiFfiConverterString.check_lower(value.week)+ _UniffiFfiConverterUInt32.check_lower(value.hits)+ _UniffiFfiConverterUInt32.check_lower(value.misses)+ _UniffiFfiConverterUInt64.check_lower(value.seconds_saved)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterBoolean.write(value.enabled, buf)+ _UniffiFfiConverterUInt32.write(value.repos, buf)+ _UniffiFfiConverterUInt64.write(value.bytes, buf)+ _UniffiFfiConverterUInt64.write(value.cap_bytes, buf)+ _UniffiFfiConverterString.write(value.size_setting, buf)+ _UniffiFfiConverterString.write(value.summary, buf)+ _UniffiFfiConverterString.write(value.week, buf)+ _UniffiFfiConverterUInt32.write(value.hits, buf)+ _UniffiFfiConverterUInt32.write(value.misses, buf)+ _UniffiFfiConverterUInt64.write(value.seconds_saved, buf)+@dataclassclass ResolvedImage:"""@@ -46781,6 +46888,36 @@ def qualify_sandbox_ref(name: str,local: typing.Union[object, typing.Optional[bo*_uniffi_lowered_args,)return _uniffi_lift_return(_uniffi_ffi_result)+def repo_cache_clear() -> RepoCacheStatus:+ """+ Deletes every repository the repo cache holds (they are copied again the+ next time a Space clones them). Returns the cache after.+"""+ _uniffi_lowered_args = (+ )+ _uniffi_lift_return = _UniffiFfiConverterTypeRepoCacheStatus.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError+ _uniffi_ffi_result = _uniffi_rust_call_with_error(+ _uniffi_error_converter,+ _UniffiLib.uniffi_cua_sdk_fn_func_repo_cache_clear,+ *_uniffi_lowered_args,+ )+ return _uniffi_lift_return(_uniffi_ffi_result)+def repo_cache_status() -> RepoCacheStatus:+ """+ The repo cache now: on or off, how much it holds of its cap, and what+ the last week saved.+"""+ _uniffi_lowered_args = (+ )+ _uniffi_lift_return = _UniffiFfiConverterTypeRepoCacheStatus.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError+ _uniffi_ffi_result = _uniffi_rust_call_with_error(+ _uniffi_error_converter,+ _UniffiLib.uniffi_cua_sdk_fn_func_repo_cache_status,+ *_uniffi_lowered_args,+ )+ return _uniffi_lift_return(_uniffi_ffi_result)def resolve_image(reference: str,backend: str,arch: typing.Optional[str]) -> ResolvedImage:"""Resolves `reference` for `backend` (`auto`, `local`, `provider`,@@ -47403,6 +47540,7 @@ __all__ = ["PtySize","PublicUrl","ReadinessProbe",+ "RepoCacheStatus","ResolvedImage","SharedBase","SpaceResources",@@ -47514,6 +47652,8 @@ __all__ = ["presence_now_ms","presence_text_color","qualify_sandbox_ref",+ "repo_cache_clear",+ "repo_cache_status","resolve_image","resolve_image_with_secret","sandbox_locations",diff --git a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swiftindex df24a2f5ac..9e10af10a9 100644--- a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift+++ b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift@@ -33755,6 +33755,157 @@ public func FfiConverterTypeRelayMachine_lower(_ value: RelayMachine) -> RustBuf}+/**+ * What the repo cache holds and what it saved, in plain words for+ * Settings (`cache.repos` and `cache.repos_size_gb` are its settings,+ * changed with [`config_set`]).+ */+public struct RepoCacheStatus: Equatable, Hashable {+ /**+ * The cache is on (`cache.repos`).+ */+ public var enabled: Bool+ /**+ * Repositories held.+ */+ public var repos: UInt32+ /**+ * What they take on disk.+ */+ public var bytes: UInt64+ /**+ * The size cap in force.+ */+ public var capBytes: UInt64+ /**+ * The size setting: `auto`, or the number of GB.+ */+ public var sizeSetting: String+ /**+ * `Repos: 3, 1.2 GB of 5 GB`.+ */+ public var summary: String+ /**+ * `Last week: 80% of clones came from the cache, about 2 minutes saved`.+ */+ public var week: String+ /**+ * Clones served from the cache in the last week.+ */+ public var hits: UInt32+ /**+ * Clones that downloaded in the last week.+ */+ public var misses: UInt32+ /**+ * Seconds the hits saved.+ */+ public var secondsSaved: UInt64++ // Default memberwise initializers are never public by default, so we+ // declare one manually.+ public init(+ /**+ * The cache is on (`cache.repos`).+ */enabled: Bool,+ /**+ * Repositories held.+ */repos: UInt32,+ /**+ * What they take on disk.+ */bytes: UInt64,+ /**+ * The size cap in force.+ */capBytes: UInt64,+ /**+ * The size setting: `auto`, or the number of GB.+ */sizeSetting: String,+ /**+ * `Repos: 3, 1.2 GB of 5 GB`.+ */summary: String,+ /**+ * `Last week: 80% of clones came from the cache, about 2 minutes saved`.+ */week: String,+ /**+ * Clones served from the cache in the last week.+ */hits: UInt32,+ /**+ * Clones that downloaded in the last week.+ */misses: UInt32,+ /**+ * Seconds the hits saved.+ */secondsSaved: UInt64) {+ self.enabled = enabled+ self.repos = repos+ self.bytes = bytes+ self.capBytes = capBytes+ self.sizeSetting = sizeSetting+ self.summary = summary+ self.week = week+ self.hits = hits+ self.misses = misses+ self.secondsSaved = secondsSaved+ }+++++}++#if compiler(>=6)+extension RepoCacheStatus: Sendable {}+#endif++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public struct FfiConverterTypeRepoCacheStatus: FfiConverterRustBuffer {+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> RepoCacheStatus {+ return+ try RepoCacheStatus(+ enabled: FfiConverterBool.read(from: &buf),+ repos: FfiConverterUInt32.read(from: &buf),+ bytes: FfiConverterUInt64.read(from: &buf),+ capBytes: FfiConverterUInt64.read(from: &buf),+ sizeSetting: FfiConverterString.read(from: &buf),+ summary: FfiConverterString.read(from: &buf),+ week: FfiConverterString.read(from: &buf),+ hits: FfiConverterUInt32.read(from: &buf),+ misses: FfiConverterUInt32.read(from: &buf),+ secondsSaved: FfiConverterUInt64.read(from: &buf)+ )+ }++ public static func write(_ value: RepoCacheStatus, into buf: inout [UInt8]) {+ FfiConverterBool.write(value.enabled, into: &buf)+ FfiConverterUInt32.write(value.repos, into: &buf)+ FfiConverterUInt64.write(value.bytes, into: &buf)+ FfiConverterUInt64.write(value.capBytes, into: &buf)+ FfiConverterString.write(value.sizeSetting, into: &buf)+ FfiConverterString.write(value.summary, into: &buf)+ FfiConverterString.write(value.week, into: &buf)+ FfiConverterUInt32.write(value.hits, into: &buf)+ FfiConverterUInt32.write(value.misses, into: &buf)+ FfiConverterUInt64.write(value.secondsSaved, into: &buf)+ }+}+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeRepoCacheStatus_lift(_ buf: RustBuffer) throws -> RepoCacheStatus {+ return try FfiConverterTypeRepoCacheStatus.lift(buf)+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeRepoCacheStatus_lower(_ value: RepoCacheStatus) -> RustBuffer {+ return FfiConverterTypeRepoCacheStatus.lower(value)+}++/*** A reference resolved for a backend.*/@@ -50658,6 +50809,26 @@ public func locations() -> [LocationInfo] {)})}+/**+ * Deletes every repository the repo cache holds (they are copied again the+ * next time a Space clones them). Returns the cache after.+ */+public func repoCacheClear()throws -> RepoCacheStatus {+ return try FfiConverterTypeRepoCacheStatus_lift(try rustCallWithError(FfiConverterTypeCuaError_lift) {+ uniffi_cua_sdk_fn_func_repo_cache_clear($0+ )+})+}+/**+ * The repo cache now: on or off, how much it holds of its cap, and what+ * the last week saved.+ */+public func repoCacheStatus()throws -> RepoCacheStatus {+ return try FfiConverterTypeRepoCacheStatus_lift(try rustCallWithError(FfiConverterTypeCuaError_lift) {+ uniffi_cua_sdk_fn_func_repo_cache_status($0+ )+})+}/*** The canonical image for `os` (`linux`, `windows`, `macos`) and* `version` (`None` = default: `ghcr.io/trycua/linux:24.04`,@@ -51204,6 +51375,12 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_sdk_checksum_func_locations() != 62174) {return InitializationResult.apiChecksumMismatch}+ if (uniffi_cua_sdk_checksum_func_repo_cache_clear() != 39088) {+ return InitializationResult.apiChecksumMismatch+ }+ if (uniffi_cua_sdk_checksum_func_repo_cache_status() != 20147) {+ return InitializationResult.apiChecksumMismatch+ }if (uniffi_cua_sdk_checksum_func_canonical_image() != 8955) {return InitializationResult.apiChecksumMismatch}diff --git a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.hindex 967d56aa0b..6867f7a83d 100644--- a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h+++ b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h@@ -3058,6 +3058,18 @@ RustBuffer uniffi_cua_sdk_fn_func_config_unset(RustBuffer key, RustCallStatus *_#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_FUNC_LOCATIONSRustBuffer uniffi_cua_sdk_fn_func_locations(RustCallStatus *_Nonnull out_status+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_FUNC_REPO_CACHE_CLEAR+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_FUNC_REPO_CACHE_CLEAR+RustBuffer uniffi_cua_sdk_fn_func_repo_cache_clear(RustCallStatus *_Nonnull out_status++);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_FUNC_REPO_CACHE_STATUS+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_FUNC_REPO_CACHE_STATUS+RustBuffer uniffi_cua_sdk_fn_func_repo_cache_status(RustCallStatus *_Nonnull out_status+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_FUNC_CANONICAL_IMAGE@@ -3618,6 +3630,18 @@ uint16_t uniffi_cua_sdk_checksum_func_config_unset(void#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_FUNC_LOCATIONSuint16_t uniffi_cua_sdk_checksum_func_locations(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_FUNC_REPO_CACHE_CLEAR+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_FUNC_REPO_CACHE_CLEAR+uint16_t uniffi_cua_sdk_checksum_func_repo_cache_clear(void++);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_FUNC_REPO_CACHE_STATUS+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_FUNC_REPO_CACHE_STATUS+uint16_t uniffi_cua_sdk_checksum_func_repo_cache_status(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_FUNC_CANONICAL_IMAGEdiff --git a/libs/cua/typescript/src/native/cua_sdk-ffi.ts b/libs/cua/typescript/src/native/cua_sdk-ffi.tsindex 7b9e355508..2ece776763 100644--- a/libs/cua/typescript/src/native/cua_sdk-ffi.ts+++ b/libs/cua/typescript/src/native/cua_sdk-ffi.ts@@ -818,6 +818,16 @@ const DEFINITIONS = {ret: FfiType.RustBuffer,hasRustCallStatus: true,},+ "uniffi_cua_sdk_fn_func_repo_cache_clear": {+ args: [],+ ret: FfiType.RustBuffer,+ hasRustCallStatus: true,+ },+ "uniffi_cua_sdk_fn_func_repo_cache_status": {+ args: [],+ ret: FfiType.RustBuffer,+ hasRustCallStatus: true,+ },"uniffi_cua_sdk_fn_func_resolve_image": {args: [FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer],ret: FfiType.RustBuffer,@@ -3313,6 +3323,16 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_sdk_checksum_func_repo_cache_clear": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },+ "uniffi_cua_sdk_checksum_func_repo_cache_status": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_checksum_func_resolve_image": {args: [],ret: FfiType.UInt16,@@ -5988,6 +6008,8 @@ interface NativeModuleInterface {uniffi_cua_sdk_fn_func_presence_now_ms(uniffi_out_err: UniffiRustCallStatus): number;uniffi_cua_sdk_fn_func_presence_text_color(background: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_func_qualify_sandbox_ref(name: Uint8Array, local: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;+ uniffi_cua_sdk_fn_func_repo_cache_clear(uniffi_out_err: UniffiRustCallStatus): Uint8Array;+ uniffi_cua_sdk_fn_func_repo_cache_status(uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_func_resolve_image(reference: Uint8Array, backend: Uint8Array, arch: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_func_resolve_image_with_secret(reference: Uint8Array, backend: Uint8Array, arch: Uint8Array, secret: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_func_sandbox_locations(uniffi_out_err: UniffiRustCallStatus): Uint8Array;@@ -6487,6 +6509,8 @@ interface NativeModuleInterface {uniffi_cua_sdk_checksum_func_presence_now_ms(): number;uniffi_cua_sdk_checksum_func_presence_text_color(): number;uniffi_cua_sdk_checksum_func_qualify_sandbox_ref(): number;+ uniffi_cua_sdk_checksum_func_repo_cache_clear(): number;+ uniffi_cua_sdk_checksum_func_repo_cache_status(): number;uniffi_cua_sdk_checksum_func_resolve_image(): number;uniffi_cua_sdk_checksum_func_resolve_image_with_secret(): number;uniffi_cua_sdk_checksum_func_sandbox_locations(): number;diff --git a/libs/cua/typescript/src/native/cua_sdk.ts b/libs/cua/typescript/src/native/cua_sdk.tsindex 3e76e4c465..ba1bfc985e 100644--- a/libs/cua/typescript/src/native/cua_sdk.ts+++ b/libs/cua/typescript/src/native/cua_sdk.ts@@ -683,6 +683,48 @@ export function qualifySandboxRef(name: string, local: boolean | undefined = und));}+/**+ * Deletes every repository the repo cache holds (they are copied again the+ * next time a Space clones them). Returns the cache after.+ */+export function repoCacheClear(): RepoCacheStatus /*throws*/ {+ return ((__rb: Uint8Array) => {+ try {+ return FfiConverterTypeRepoCacheStatus.lift(__rb);+ } finally {+ nativeModule().rustbuffer_free(__rb);+ }+ })(uniffiCaller.rustCallWithError(+ /*liftError:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError),+ /*caller:*/ (callStatus) => {+ return nativeModule().uniffi_cua_sdk_fn_func_repo_cache_clear(+ callStatus);+ },+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ ));+ }++/**+ * The repo cache now: on or off, how much it holds of its cap, and what+ * the last week saved.+ */+export function repoCacheStatus(): RepoCacheStatus /*throws*/ {+ return ((__rb: Uint8Array) => {+ try {+ return FfiConverterTypeRepoCacheStatus.lift(__rb);+ } finally {+ nativeModule().rustbuffer_free(__rb);+ }+ })(uniffiCaller.rustCallWithError(+ /*liftError:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError),+ /*caller:*/ (callStatus) => {+ return nativeModule().uniffi_cua_sdk_fn_func_repo_cache_status(+ callStatus);+ },+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ ));+ }+/*** Resolves `reference` for `backend` (`auto`, `local`, `provider`,* `container`/`docker`/`gvisor`, `vm`/`qemu`/`kubevirt`, `lume`)@@ -15814,6 +15856,116 @@ const FfiConverterTypeReadinessProbe = (() => {return new FFIConverter();})();+/**+ * What the repo cache holds and what it saved, in plain words for+ * Settings (`cache.repos` and `cache.repos_size_gb` are its settings,+ * changed with [`config_set`]).+ */+export type RepoCacheStatus = {+ /**+ * The cache is on (`cache.repos`).+ */+ enabled: boolean,+ /**+ * Repositories held.+ */+ repos: number,+ /**+ * What they take on disk.+ */+ bytes: bigint,+ /**+ * The size cap in force.+ */+ capBytes: bigint,+ /**+ * The size setting: `auto`, or the number of GB.+ */+ sizeSetting: string,+ /**+ * `Repos: 3, 1.2 GB of 5 GB`.+ */+ summary: string,+ /**+ * `Last week: 80% of clones came from the cache, about 2 minutes saved`.+ */+ week: string,+ /**+ * Clones served from the cache in the last week.+ */+ hits: number,+ /**+ * Clones that downloaded in the last week.+ */+ misses: number,+ /**+ * Seconds the hits saved.+ */+ secondsSaved: bigint+}++/**+ * Generated factory for {@link RepoCacheStatus} record objects.+ */+export const RepoCacheStatus = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<RepoCacheStatus, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<RepoCacheStatus>,+ });+})();++const FfiConverterTypeRepoCacheStatus = (() => {+ type TypeName = RepoCacheStatus;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ enabled: FfiConverterBool.read(from),+ repos: FfiConverterUInt32.read(from),+ bytes: FfiConverterUInt64.read(from),+ capBytes: FfiConverterUInt64.read(from),+ sizeSetting: FfiConverterString.read(from),+ summary: FfiConverterString.read(from),+ week: FfiConverterString.read(from),+ hits: FfiConverterUInt32.read(from),+ misses: FfiConverterUInt32.read(from),+ secondsSaved: FfiConverterUInt64.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterBool.write(value.enabled, into);+ FfiConverterUInt32.write(value.repos, into);+ FfiConverterUInt64.write(value.bytes, into);+ FfiConverterUInt64.write(value.capBytes, into);+ FfiConverterString.write(value.sizeSetting, into);+ FfiConverterString.write(value.summary, into);+ FfiConverterString.write(value.week, into);+ FfiConverterUInt32.write(value.hits, into);+ FfiConverterUInt32.write(value.misses, into);+ FfiConverterUInt64.write(value.secondsSaved, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterBool.allocationSize(value.enabled) ++ FfiConverterUInt32.allocationSize(value.repos) ++ FfiConverterUInt64.allocationSize(value.bytes) ++ FfiConverterUInt64.allocationSize(value.capBytes) ++ FfiConverterString.allocationSize(value.sizeSetting) ++ FfiConverterString.allocationSize(value.summary) ++ FfiConverterString.allocationSize(value.week) ++ FfiConverterUInt32.allocationSize(value.hits) ++ FfiConverterUInt32.allocationSize(value.misses) ++ FfiConverterUInt64.allocationSize(value.secondsSaved);++ }+ };+ return new FFIConverter();+})();+/*** A reference resolved for a backend.*/@@ -46581,6 +46733,12 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_func_qualify_sandbox_ref() !== 59566) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_func_qualify_sandbox_ref");}+ if (nativeModule().uniffi_cua_sdk_checksum_func_repo_cache_clear() !== 39088) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_func_repo_cache_clear");+ }+ if (nativeModule().uniffi_cua_sdk_checksum_func_repo_cache_status() !== 20147) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_func_repo_cache_status");+ }if (nativeModule().uniffi_cua_sdk_checksum_func_resolve_image() !== 56346) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_func_resolve_image");}@@ -48192,6 +48350,7 @@ export default Object.freeze({FfiConverterTypeRelayDevice,FfiConverterTypeRelayMachine,FfiConverterTypeReplayMode,+ FfiConverterTypeRepoCacheStatus,FfiConverterTypeResolvedImage,FfiConverterTypeResourcesEvent,FfiConverterTypeResourcesListener,diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex bf6aa96292..a82d360910 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -13405,7 +13405,7 @@},{"abstract": "Show or change what this computer shares: its own desktop, and whether it creates Spaces for your other devices",- "after_help": "Examples:\n cua host config\n # Stop sharing this desktop; keep providing Spaces\n cua host config --desktop off --provide-spaces on\n cua host config --max-spaces 6\n # Give the Spaces other machines create here at most 32 GB of memory and\n # 200 GB of disk in total, and stop each after 8 hours (0: no limit)\n cua host config --max-memory 32 --max-disk 200 --max-run-time 480",+ "after_help": "Examples:\n cua host config\n # Stop sharing this desktop; keep providing Spaces\n cua host config --desktop off --provide-spaces on\n cua host config --max-spaces 6\n # Give the Spaces other machines create here at most 32 GB of memory and\n # 200 GB of disk in total, and stop each after 8 hours (0: no limit)\n cua host config --max-memory 32 --max-disk 200 --max-run-time 480\n # Keep no copies of public git repositories on this machine, or at most 2 GB\n cua host config --repo-cache off\n cua host config --repo-cache on --repo-cache-size 2","aliases": [],"arguments": [],"flags": [],@@ -13530,12 +13530,114 @@"takes_value": true,"type": "integer","value_name": "MINUTES"+ },+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "The repo cache: on | off. It keeps verified copies of public git repositories on this machine so a repeat `git clone` in a Space starts from one (never private repositories, never anything off this machine's disk)",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "repo-cache",+ "possible_values": [+ "on",+ "off"+ ],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "on | off",+ "value_name": "REPO_CACHE"+ },+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "The most disk the repo cache may use, in GB (`auto`: the smaller of 5 GB and a tenth of the free disk). The least recently used repositories go first",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "repo-cache-size",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "string",+ "value_name": "GB"}],"subcommand_optional": false,"subcommands": [],"usage": "cua host config [OPTIONS]"},+ {+ "abstract": "What the repo cache holds, and empty it",+ "aliases": [],+ "arguments": [],+ "flags": [],+ "hidden": false,+ "hidden_aliases": [],+ "name": "cache",+ "options": [],+ "subcommand_optional": false,+ "subcommands": [+ {+ "abstract": "What the repo cache holds: repositories, size and what the last week saved",+ "after_help": "Examples:\n cua host cache status",+ "aliases": [],+ "arguments": [],+ "flags": [],+ "hidden": false,+ "hidden_aliases": [],+ "name": "status",+ "options": [],+ "subcommand_optional": false,+ "subcommands": [],+ "usage": "cua host cache status [OPTIONS]"+ },+ {+ "abstract": "Copy one public repository into the cache now, instead of when a Space first clones it (or bring a copy up to date). A repository that needs a sign-in is never cached",+ "after_help": "Examples:\n cua host cache fill https://github.com/vitejs/vite",+ "aliases": [],+ "arguments": [+ {+ "default_value": null,+ "help": "The repository's `https` address",+ "hidden": false,+ "is_optional": false,+ "name": "URL",+ "possible_values": [],+ "repeatable": false,+ "type": "string"+ }+ ],+ "flags": [],+ "hidden": false,+ "hidden_aliases": [],+ "name": "fill",+ "options": [],+ "subcommand_optional": false,+ "subcommands": [],+ "usage": "cua host cache fill [OPTIONS] <URL>"+ },+ {+ "abstract": "Delete every repository the cache holds. They are copied again the next time a Space clones them",+ "after_help": "Examples:\n cua host cache clear",+ "aliases": [],+ "arguments": [],+ "flags": [],+ "hidden": false,+ "hidden_aliases": [],+ "name": "clear",+ "options": [],+ "subcommand_optional": false,+ "subcommands": [],+ "usage": "cua host cache clear [OPTIONS]"+ }+ ],+ "usage": "cua host cache [OPTIONS] <COMMAND>"+ },{"abstract": "Show whether this computer is set up, the service, and who is connected","after_help": "Examples:\n cua host status",diff --git a/scripts/docs-generators/cua-sdk.ts b/scripts/docs-generators/cua-sdk.tsindex 8776497ded..770a9f8f4e 100644--- a/scripts/docs-generators/cua-sdk.ts+++ b/scripts/docs-generators/cua-sdk.ts@@ -491,6 +491,14 @@ export const PAGES: PageSpec[] = [members: [{ object: 'Local', title: 'Runtime per kind methods', methods: ['runtime_kinds', 'runtime_check_path'] }],items: ['RuntimeKindState', 'RuntimeDetected', 'RuntimePathProbe'],},+ {+ slug: 'repo-cache',+ title: 'Repo cache',+ description: 'What the repo cache holds and what it saved, and clearing it.',+ intro:+ 'The daemon keeps verified copies of public git repositories so a repeat `git clone` in a Space is fast. `repo_cache_status` reads what it holds and what the last week saved in plain words; `repo_cache_clear` deletes every copy. It is on by default and is turned off, or given a size, with `config_set` on `cache.repos` and `cache.repos_size_gb`.',+ items: ['RepoCacheStatus', 'repo_cache_status', 'repo_cache_clear'],+ },{slug: 'spaces',title: 'Spaces',@@ -1000,7 +1008,7 @@ const TELEMETRY_CONCEPTS = ['../concepts/telemetry', '../concepts/telemetry-even/** Groups of the reference sidebar; folders other generators own are listed by name. */const NAV: Array<[label: string, pages: string[]]> = [- ['Sandboxes', ['cua', 'runtime-kinds', 'sandbox', 'share', 'image', 'os-image-catalog', 'image-software', 'services', 'runtime-support']],+ ['Sandboxes', ['cua', 'runtime-kinds', 'repo-cache', 'sandbox', 'share', 'image', 'os-image-catalog', 'image-software', 'services', 'runtime-support']],['Inside a sandbox', ['spacesd', 'agents', 'agent-setup']],['Spaces', ['spaces']],['Account', ['auth']],diff --git a/tests/e2e/cua-sdk/rust/Cargo.lock b/tests/e2e/cua-sdk/rust/Cargo.lockindex 0441f2e9c2..f04162e12b 100644--- a/tests/e2e/cua-sdk/rust/Cargo.lock+++ b/tests/e2e/cua-sdk/rust/Cargo.lock@@ -1639,6 +1639,22 @@ dependencies = ["tonic-prost-build",]+[[package]]+name = "cua-repo-cache"+version = "0.9.0"+dependencies = [+ "cua-home",+ "cua-telemetry",+ "hex",+ "libc",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tokio",+ "tracing",+ "url",+]+[[package]]name = "cua-sandbox-core"version = "0.9.0"@@ -1648,6 +1664,7 @@ dependencies = ["bytes","cua-home","cua-image",+ "cua-repo-cache","cua-spacesd-client","cua-vmm","futures-util",diff --git a/tests/e2e/local-runtimes/Cargo.lock b/tests/e2e/local-runtimes/Cargo.lockindex ac762db741..930491f869 100644--- a/tests/e2e/local-runtimes/Cargo.lock+++ b/tests/e2e/local-runtimes/Cargo.lock@@ -1432,6 +1432,22 @@ dependencies = ["tonic-prost-build",]+[[package]]+name = "cua-repo-cache"+version = "0.9.0"+dependencies = [+ "cua-home",+ "cua-telemetry",+ "hex",+ "libc",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tokio",+ "tracing",+ "url",+]+[[package]]name = "cua-sandbox-core"version = "0.9.0"@@ -1441,6 +1457,7 @@ dependencies = ["bytes","cua-home","cua-image",+ "cua-repo-cache","cua-spacesd-client","cua-vmm","futures-util",