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
feat(cua): add a machine with a one-time pairing code (cua host setup --pair, installers --pair) (CUA-1358) (#5003)
Francesco Bonacci2a5a7caacd32
diff --git a/.github/workflows/ci-installers.yml b/.github/workflows/ci-installers.ymlindex 4fb8388083..f14ef56087 100644--- a/.github/workflows/ci-installers.yml+++ b/.github/workflows/ci-installers.yml@@ -84,8 +84,10 @@ jobs:sleep 1CUA_INSTALL_BASE_URL=http://127.0.0.1:8765 sh /w/install.sh --yes --no-onboarding --mode client/usr/local/bin/cua --version- test -x /usr/local/bin/cua-spaces- grep -qx client "$HOME/.cua/spaces-install-mode"+ # Cua Spaces is macOS-only for now: Linux skips the app.+ test ! -e /usr/local/bin/cua-spaces+ # --pair installs the CLI and adds the machine with the code.+ CUA_INSTALL_BASE_URL=http://127.0.0.1:8765 sh /w/install.sh --dry-run --pair K7QM-4XPB-2RHD | grep -q "host setup --pair K7QM-4XPB-2RHD"'installer-smoke-macos:diff --git a/docs/content/docs/cua-cli/reference/cli/host.mdx b/docs/content/docs/cua-cli/reference/cli/host.mdxindex 22bf280b72..6674d241f8 100644--- a/docs/content/docs/cua-cli/reference/cli/host.mdx+++ b/docs/content/docs/cua-cli/reference/cli/host.mdx@@ -13,6 +13,7 @@ description: "Set this machine up for unattended access."| Command | Description || --- | --- || [`cua host setup`](#cua-host-setup) | Set this machine 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 machine shares: its own desktop, and whether it creates Spaces for your other devices. || [`cua host status`](#cua-host-status) | Show whether this machine is set up, the service, and who is connected. || [`cua host stop`](#cua-host-stop) | Stop sharing: disconnect everyone and refuse new connections. |@@ -42,6 +43,7 @@ cua host setup [OPTIONS]| Flag | Type | Default | Description || --- | --- | --- | --- || <span id="cua-host-setup--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai). |+| <span id="cua-host-setup--pair"></span>`--pair` | string | | Join with a one-time pairing code (or add-machine link) made in the Cua Spaces app or with `cua host pair`, instead of signing in here. The machine joins the account (or team) that made it. || <span id="cua-host-setup--direct"></span>`--direct` | string | | Serve directly on ip:port with a local env token (LAN / port-forwarded) instead of joining a relay. || <span id="cua-host-setup--name"></span>`--name` | string | | Display name (default: the host name). || <span id="cua-host-setup--allow"></span>`--allow` | string | | Also allow this account (id or email). Repeatable. |@@ -71,6 +73,35 @@ cua host setup --direct 0.0.0.0:3211 --name studio-mac# A spare Mac on your tailnet that runs Spaces, without the relay (prints the command that adds it on your laptop)cua host setup --direct 100.101.102.103:3211 --profile spare++# Add this machine with a one-time code from the Cua Spaces app (Add a machine) or `cua host pair`: no sign-in needed here+cua host setup --pair K7QM-4XPB-2RHD+```++## `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. Codes work once and expire (30 minutes by default). Run from an enrolled device.++```text output+cua host pair [OPTIONS]+```++| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| <span id="cua-host-pair--team"></span>`--team` | string | | Add the machine for this team (its id). |+| <span id="cua-host-pair--name"></span>`--name` | string | | Name the machine gets (default: its own host name). |+| <span id="cua-host-pair--expires"></span>`--expires` | integer | `30` | Minutes until the code expires (1 to 1440). |+| <span id="cua-host-pair--revoke"></span>`--revoke` | string | | Revoke an unused code by id (`pc_…`). |+| <span id="cua-host-pair--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai). |+| <span id="cua-host-pair--list"></span>`--list` | boolean | `false` | List your codes (used, unused, revoked, expired) instead. |++**Examples**++```bash test="cli-shape" id="ref-cua-host-pair"+cua host pair+cua host pair --team team-aigis --expires 60+cua host pair --list+cua host pair --revoke pc_0123456789abcdef```## `cua host config`diff --git a/docs/content/docs/cua-cli/reference/cli/index.mdx b/docs/content/docs/cua-cli/reference/cli/index.mdxindex f0cb424ce1..5502f66bb6 100644--- a/docs/content/docs/cua-cli/reference/cli/index.mdx+++ b/docs/content/docs/cua-cli/reference/cli/index.mdx@@ -156,7 +156,7 @@ Set this machine up for unattended access. [Reference](/cua-cli/reference/cli/ho| Command | Description | Subcommands || --- | --- | --- |-| <span id="cua-host-setup"></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-remove"></span>[`cua host`](/cua-cli/reference/cli/host#cua-host) | Unattended access to this machine (setup, status, stop, start, remove). | [`setup`](/cua-cli/reference/cli/host#cua-host-setup), [`config`](/cua-cli/reference/cli/host#cua-host-config), [`status`](/cua-cli/reference/cli/host#cua-host-status), [`stop`](/cua-cli/reference/cli/host#cua-host-stop), [`start`](/cua-cli/reference/cli/host#cua-host-start), [`share`](/cua-cli/reference/cli/host#cua-host-share), [`unshare`](/cua-cli/reference/cli/host#cua-host-unshare), [`remove`](/cua-cli/reference/cli/host#cua-host-remove) |+| <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-remove"></span>[`cua host`](/cua-cli/reference/cli/host#cua-host) | Unattended access to this machine (setup, status, stop, start, remove). | [`setup`](/cua-cli/reference/cli/host#cua-host-setup), [`pair`](/cua-cli/reference/cli/host#cua-host-pair), [`config`](/cua-cli/reference/cli/host#cua-host-config), [`status`](/cua-cli/reference/cli/host#cua-host-status), [`stop`](/cua-cli/reference/cli/host#cua-host-stop), [`start`](/cua-cli/reference/cli/host#cua-host-start), [`share`](/cua-cli/reference/cli/host#cua-host-share), [`unshare`](/cua-cli/reference/cli/host#cua-host-unshare), [`remove`](/cua-cli/reference/cli/host#cua-host-remove) |### `cua devices`diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdxindex fba3736af8..61cd888ae8 100644--- a/docs/content/docs/cua-sdk/reference/index.mdx+++ b/docs/content/docs/cua-sdk/reference/index.mdx@@ -138,6 +138,6 @@ Pages marked *Cua Spaces app export* document the APIs the Cua Spaces apps are b| --- | --- || [Protocol](/cua-sdk/reference/protocol) | The gRPC contracts of cua-spacesd (`cua.env.v1`) and the cua daemon (`cua.daemon.v1`). |-290 items, 382 methods. The [Types](/cua-sdk/reference/types) page lists them.+291 items, 385 methods. The [Types](/cua-sdk/reference/types) page lists them.The Cua Spaces app export adds 738 items and 38 methods.diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdxindex d7b28f70b3..6c67e7e0c4 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#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/media#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/media#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-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), [`CloudCheck`](/cua-sdk/reference/spaces/cloud#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/cloud#cloudconnected-record), [`CloudCredentials`](/cua-sdk/reference/spaces/cloud#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/cloud#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/cloud#cloudkind-record), [`CloudOptions`](/cua-sdk/reference/sandbox/options#cloudoptions-record), [`CloudProvider`](/cua-sdk/reference/spaces/cloud#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/cloud#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/cloud#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/cloud#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/cloud#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/cloud#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/cloud#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-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/sandbox/options#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/devices#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/devices#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/devices#devicessnapshot-record), [`DoctorReport`](/cua-sdk/reference/local#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-sync#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume-sync#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume-sync#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-sync#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume-sync#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume-sync#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume-sync#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume-sync#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume-sync#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume-sync#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume-sync#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume-sync#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume-sync#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`Fleet`](/cua-sdk/reference/errors#fleet), [`fleet_check_runtime`](/cua-sdk/reference/fleet/images#fleet_check_runtime), [`fleet_generate_claim_token`](/cua-sdk/reference/fleet#fleet_generate_claim_token), [`fleet_image_variant`](/cua-sdk/reference/fleet/images#fleet_image_variant), [`fleet_resolve_runtime`](/cua-sdk/reference/fleet/images#fleet_resolve_runtime), [`fleet_size_limits`](/cua-sdk/reference/fleet/images#fleet_size_limits), [`FleetBillingCard`](/cua-sdk/reference/fleet/images#fleetbillingcard-record), [`FleetBillingCredit`](/cua-sdk/reference/fleet/images#fleetbillingcredit-record), [`FleetBillingStatus`](/cua-sdk/reference/fleet/images#fleetbillingstatus-record), [`FleetClaim`](/cua-sdk/reference/fleet/claims#fleetclaim-record), [`FleetClaimOptions`](/cua-sdk/reference/fleet/claims#fleetclaimoptions-record), [`FleetGcReport`](/cua-sdk/reference/fleet#fleetgcreport-record), [`FleetManagedPool`](/cua-sdk/reference/fleet#fleetmanagedpool-record), [`FleetPool`](/cua-sdk/reference/fleet#fleetpool-record), [`FleetPoolExport`](/cua-sdk/reference/fleet#fleetpoolexport-record), [`FleetPools`](/cua-sdk/reference/fleet#fleetpools), [`FleetPoolSpec`](/cua-sdk/reference/fleet#fleetpoolspec-record), [`FleetSandbox`](/cua-sdk/reference/fleet/claims#fleetsandbox-record), [`FleetSettings`](/cua-sdk/reference/cua#fleetsettings-record), [`FleetSignedUrl`](/cua-sdk/reference/fleet/claims#fleetsignedurl-record), [`FleetSizeLimits`](/cua-sdk/reference/fleet/images#fleetsizelimits-record), [`FleetUsagePricing`](/cua-sdk/reference/fleet/images#fleetusagepricing-record), [`FrameSink`](/cua-sdk/reference/spacesd/media#framesink), [`GpuOption`](/cua-sdk/reference/spaces/create#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces/create#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/sandbox/without-spacesd#guestdisplay), [`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), [`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/local#local), [`LocalImage`](/cua-sdk/reference/local#localimage-record), [`LocalStorage`](/cua-sdk/reference/local#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), [`may_have_fleet_session`](/cua-sdk/reference/auth#may_have_fleet_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/media#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/media#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/media#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/media#mediastats-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), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolOptions`](/cua-sdk/reference/fleet#pooloptions-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), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/sandbox/options#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/devices#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/devices#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), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/local#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/local#runtimecheckstatus-enum), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/sandbox/options#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), [`SandboxRefParts`](/cua-sdk/reference/sandbox#sandboxrefparts-record), [`SandboxSpec`](/cua-sdk/reference/fleet#sandboxspec-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/local#setupstep-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/windows#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/windows#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces/create#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces/create#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces/create#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces/create#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces/create#spacecreateresult-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/windows#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record), [`SpacePowerReport`](/cua-sdk/reference/spaces#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/space#spacerelayregistration-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`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/space#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/space#spaceshares-record), [`SpacesHost`](/cua-sdk/reference/spaces/space#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/space#spaceshostlimit-record), [`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), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/windows#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/local#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/telemetry#streamstatsreport-record), [`telemetry_acknowledge_notice`](/cua-sdk/reference/telemetry#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/telemetry#telemetry_flush), [`telemetry_notice_text`](/cua-sdk/reference/telemetry#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/telemetry#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/telemetry#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/telemetry#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/telemetry#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/telemetry#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/telemetry#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/telemetry#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/telemetry#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/telemetry#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/telemetry#telemetry_status), [`telemetry_use_app_notice`](/cua-sdk/reference/telemetry#telemetry_use_app_notice), [`TelemetryStatus`](/cua-sdk/reference/telemetry#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/teleport#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/teleport#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/teleport#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/teleport#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/teleport#teleportreceipt-record), [`VideoFrame`](/cua-sdk/reference/spacesd/media#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-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#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/media#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/media#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-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), [`CloudCheck`](/cua-sdk/reference/spaces/cloud#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/cloud#cloudconnected-record), [`CloudCredentials`](/cua-sdk/reference/spaces/cloud#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/cloud#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/cloud#cloudkind-record), [`CloudOptions`](/cua-sdk/reference/sandbox/options#cloudoptions-record), [`CloudProvider`](/cua-sdk/reference/spaces/cloud#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/cloud#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/cloud#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/cloud#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/cloud#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/cloud#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/cloud#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-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/sandbox/options#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/devices#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/devices#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/devices#devicessnapshot-record), [`DoctorReport`](/cua-sdk/reference/local#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-sync#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume-sync#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume-sync#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-sync#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume-sync#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume-sync#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume-sync#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume-sync#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume-sync#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume-sync#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume-sync#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume-sync#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume-sync#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`Fleet`](/cua-sdk/reference/errors#fleet), [`fleet_check_runtime`](/cua-sdk/reference/fleet/images#fleet_check_runtime), [`fleet_generate_claim_token`](/cua-sdk/reference/fleet#fleet_generate_claim_token), [`fleet_image_variant`](/cua-sdk/reference/fleet/images#fleet_image_variant), [`fleet_resolve_runtime`](/cua-sdk/reference/fleet/images#fleet_resolve_runtime), [`fleet_size_limits`](/cua-sdk/reference/fleet/images#fleet_size_limits), [`FleetBillingCard`](/cua-sdk/reference/fleet/images#fleetbillingcard-record), [`FleetBillingCredit`](/cua-sdk/reference/fleet/images#fleetbillingcredit-record), [`FleetBillingStatus`](/cua-sdk/reference/fleet/images#fleetbillingstatus-record), [`FleetClaim`](/cua-sdk/reference/fleet/claims#fleetclaim-record), [`FleetClaimOptions`](/cua-sdk/reference/fleet/claims#fleetclaimoptions-record), [`FleetGcReport`](/cua-sdk/reference/fleet#fleetgcreport-record), [`FleetManagedPool`](/cua-sdk/reference/fleet#fleetmanagedpool-record), [`FleetPool`](/cua-sdk/reference/fleet#fleetpool-record), [`FleetPoolExport`](/cua-sdk/reference/fleet#fleetpoolexport-record), [`FleetPools`](/cua-sdk/reference/fleet#fleetpools), [`FleetPoolSpec`](/cua-sdk/reference/fleet#fleetpoolspec-record), [`FleetSandbox`](/cua-sdk/reference/fleet/claims#fleetsandbox-record), [`FleetSettings`](/cua-sdk/reference/cua#fleetsettings-record), [`FleetSignedUrl`](/cua-sdk/reference/fleet/claims#fleetsignedurl-record), [`FleetSizeLimits`](/cua-sdk/reference/fleet/images#fleetsizelimits-record), [`FleetUsagePricing`](/cua-sdk/reference/fleet/images#fleetusagepricing-record), [`FrameSink`](/cua-sdk/reference/spacesd/media#framesink), [`GpuOption`](/cua-sdk/reference/spaces/create#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces/create#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/sandbox/without-spacesd#guestdisplay), [`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), [`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/local#local), [`LocalImage`](/cua-sdk/reference/local#localimage-record), [`LocalStorage`](/cua-sdk/reference/local#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), [`may_have_fleet_session`](/cua-sdk/reference/auth#may_have_fleet_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/media#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/media#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/media#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/media#mediastats-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#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolOptions`](/cua-sdk/reference/fleet#pooloptions-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), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/sandbox/options#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/devices#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/devices#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), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/local#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/local#runtimecheckstatus-enum), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/sandbox/options#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), [`SandboxRefParts`](/cua-sdk/reference/sandbox#sandboxrefparts-record), [`SandboxSpec`](/cua-sdk/reference/fleet#sandboxspec-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/local#setupstep-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/windows#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/windows#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces/create#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces/create#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces/create#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces/create#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces/create#spacecreateresult-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/windows#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record), [`SpacePowerReport`](/cua-sdk/reference/spaces#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/space#spacerelayregistration-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`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/space#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/space#spaceshares-record), [`SpacesHost`](/cua-sdk/reference/spaces/space#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/space#spaceshostlimit-record), [`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), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/windows#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/local#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/telemetry#streamstatsreport-record), [`telemetry_acknowledge_notice`](/cua-sdk/reference/telemetry#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/telemetry#telemetry_flush), [`telemetry_notice_text`](/cua-sdk/reference/telemetry#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/telemetry#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/telemetry#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/telemetry#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/telemetry#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/telemetry#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/telemetry#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/telemetry#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/telemetry#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/telemetry#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/telemetry#telemetry_status), [`telemetry_use_app_notice`](/cua-sdk/reference/telemetry#telemetry_use_app_notice), [`TelemetryStatus`](/cua-sdk/reference/telemetry#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/teleport#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/teleport#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/teleport#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/teleport#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/teleport#teleportreceipt-record), [`VideoFrame`](/cua-sdk/reference/spacesd/media#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record).## Typesdiff --git a/docs/content/docs/cua-sdk/reference/spaces/devices.mdx b/docs/content/docs/cua-sdk/reference/spaces/devices.mdxindex c0b81d3cdb..842f223bcb 100644--- a/docs/content/docs/cua-sdk/reference/spaces/devices.mdx+++ b/docs/content/docs/cua-sdk/reference/spaces/devices.mdx@@ -28,10 +28,13 @@ Returned by [`Auth.devices`](/cua-sdk/reference/auth#authdevices).| [`approve`](#devicesapprove) | Approves the device showing `code`, or re-verifies `device_id`, from this enrolled device. || [`check_enrolled`](#devicescheck_enrolled) | Whether the relay lets this device open a session now (enrolled), asked afresh. || [`confirm_machine`](#devicesconfirm_machine) | Vouches for `machine_id`, a machine that registered without an enrolled device's signature or MFA (from this enrolled device) (S5). |+| [`create_pairing_code`](#devicescreate_pairing_code) | Makes a one-time code (link, QR, install commands) that adds another computer to the account, or to `team` (from this enrolled device). || [`device_id`](#devicesdevice_id) | This device's id, when it has a key (no network). || [`enroll`](#devicesenroll) | Registers this device (creating its key on first use). |+| [`pairing_codes`](#devicespairing_codes) | The account's pairing codes, newest first (without the codes). || [`rename`](#devicesrename) | Renames a device (from this enrolled device). || [`revoke`](#devicesrevoke) | Revokes a device (from this enrolled device). |+| [`revoke_pairing_code`](#devicesrevoke_pairing_code) | Revokes an unused pairing code (`pc_…`). || [`snapshot`](#devicessnapshot) | The account's devices, the grace period, the newest `audit_limit` audit events and the machines' names. || Accessor | Returns | Description |@@ -186,6 +189,58 @@ pub async fn confirm_machine(&self, machine_id: String) -> Result<RelayMachine,**Returns** [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)+### `Devices.create_pairing_code`++Makes a one-time code (link, QR, install commands) that adds another+computer to the account, or to `team` (from this enrolled device).+It expires after `ttl_secs` (30 minutes when `None`).++<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>+<Tab value="Python">++```python+async def create_pairing_code(self, team: Optional[str], ttl_secs: Optional[int]) -> PairingCode+```++</Tab>+<Tab value="TypeScript">++```ts+createPairingCode(team: string | undefined, ttlSecs: bigint | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<PairingCode>+```++</Tab>+<Tab value="Swift">++```swift+func createPairingCode(team: String?, ttlSecs: UInt64?) async throws -> PairingCode+```++</Tab>+<Tab value="Kotlin">++```kotlin+@Throws(CuaException::class)+suspend fun createPairingCode(team: String?, ttlSecs: ULong?): PairingCode+```++</Tab>+<Tab value="Rust">++```rust+pub async fn create_pairing_code(&self, team: Option<String>, ttl_secs: Option<u64>) -> Result<PairingCode, CuaError>+```++</Tab>+</Tabs>++| Parameter | Type | Default |+| --- | --- | --- |+| `team` | `Option<String>` | required |+| `ttl_secs` | `Option<u64>` | required |++**Returns** [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)+### `Devices.device_id`This device's id, when it has a key (no network).@@ -279,6 +334,51 @@ pub async fn enroll(&self) -> Result<DeviceEnrollment, CuaError>**Returns** [`DeviceEnrollment`](#deviceenrollment-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)+### `Devices.pairing_codes`++The account's pairing codes, newest first (without the codes).++<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>+<Tab value="Python">++```python+async def pairing_codes(self) -> List[PairingCode]+```++</Tab>+<Tab value="TypeScript">++```ts+pairingCodes(asyncOpts_?: { signal: AbortSignal }): Promise<Array<PairingCode>>+```++</Tab>+<Tab value="Swift">++```swift+func pairingCodes() async throws -> [PairingCode]+```++</Tab>+<Tab value="Kotlin">++```kotlin+@Throws(CuaException::class)+suspend fun pairingCodes(): List<PairingCode>+```++</Tab>+<Tab value="Rust">++```rust+pub async fn pairing_codes(&self) -> Result<Vec<PairingCode>, CuaError>+```++</Tab>+</Tabs>++**Returns** [`Vec<PairingCode>`](/cua-sdk/reference/spaces/host#pairingcode-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)+### `Devices.rename`Renames a device (from this enrolled device).@@ -379,6 +479,55 @@ pub async fn revoke(&self, id: String) -> Result<RelayDevice, CuaError>**Returns** [`RelayDevice`](#relaydevice-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)+### `Devices.revoke_pairing_code`++Revokes an unused pairing code (`pc_…`).++<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist>+<Tab value="Python">++```python+async def revoke_pairing_code(self, id: str) -> None+```++</Tab>+<Tab value="TypeScript">++```ts+revokePairingCode(id: string, asyncOpts_?: { signal: AbortSignal }): Promise<void>+```++</Tab>+<Tab value="Swift">++```swift+func revokePairingCode(id: String) async throws+```++</Tab>+<Tab value="Kotlin">++```kotlin+@Throws(CuaException::class)+suspend fun revokePairingCode(id: String)+```++</Tab>+<Tab value="Rust">++```rust+pub async fn revoke_pairing_code(&self, id: String) -> Result<(), CuaError>+```++</Tab>+</Tabs>++| Parameter | Type | Default |+| --- | --- | --- |+| `id` | `String` | required |++**Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)+### `Devices.snapshot`The account's devices, the grace period, the newest `audit_limit`diff --git a/docs/content/docs/cua-sdk/reference/spaces/host.mdx b/docs/content/docs/cua-sdk/reference/spaces/host.mdxindex 1e30a54532..8050ed3ef7 100644--- a/docs/content/docs/cua-sdk/reference/spaces/host.mdx+++ b/docs/content/docs/cua-sdk/reference/spaces/host.mdx@@ -884,6 +884,27 @@ Returned by [`Host.configure`](#hostconfigure), [`Host.pause_signed_out`](#hostp| `owner` | `Option<String>` | `None` | The account this machine is registered to (relay mode): its id. || `owner_email` / `ownerEmail` | `Option<String>` | `None` | The owner's email, when the relay gave one. |+## `PairingCode` record++A one-time code that adds a machine to the account ("Add a machine"+by link or QR code).++Returned by [`Devices.create_pairing_code`](/cua-sdk/reference/spaces/devices#devicescreate_pairing_code), [`Devices.pairing_codes`](/cua-sdk/reference/spaces/devices#devicespairing_codes).++| Field | Type | Default | Description |+| --- | --- | --- | --- |+| `id` | `String` | | `pc_…` (to revoke it). |+| `code` | `Option<String>` | | `XXXX-XXXX-XXXX`: only when just made. |+| `url` | `Option<String>` | | `https://spaces.cua.ai/add/<code>` (the link and the QR code): only when just made. |+| `install_sh` / `installSh` | `Option<String>` | | `curl … \| sh -s -- --pair <code>` (macOS, Linux): only when just made. |+| `install_powershell` / `installPowershell` | `Option<String>` | | The PowerShell one-liner (Windows): only when just made. |+| `state` | `String` | | `active`, `used`, `revoked` or `expired`. |+| `team` | `Option<String>` | | Team the machine is added for. |+| `created_at` / `createdAt` | `u64` | | Unix seconds. |+| `expires_at` / `expiresAt` | `u64` | | Unix seconds. |+| `used_at` / `usedAt` | `Option<u64>` | | When a machine used it. |+| `machine` | `Option<String>` | | The machine it added (relay machine id). |+## `RelayClientInfo` recordSomebody connected to a machine through the relay.diff --git a/docs/content/docs/cua-sdk/reference/types.mdx b/docs/content/docs/cua-sdk/reference/types.mdxindex 33a30f4f7d..5fcb491627 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-291 items. Methods are listed on their object.+292 items. Methods are listed on their object.The 738 items of the Cua Spaces app export (source-available, FSL-1.1-MIT, Swift only) are listed on their pages: [Decoded media](/cua-sdk/reference/spaces/decoded-media), [Host teleport](/cua-sdk/reference/spaces/teleport-host), [Teleport an app](/cua-sdk/reference/spaces/teleport-apps), [Spaces app core](/cua-sdk/reference/spaces/app-core#all-items), [App core: Cua Volume storage, mount and sync](/cua-sdk/reference/spaces/volume-app-core#all-items), [App core: agents, drive, notifications](/cua-sdk/reference/spaces/agents-app-core#all-items).@@ -215,6 +215,7 @@ The 738 items of the Cua Spaces app export (source-available, FSL-1.1-MIT, Swift| [`omarchy_image`](/cua-sdk/reference/image#omarchy_image) | function | The Omarchy image, `ghcr.io/trycua/omarchy:<channel>` (default `edge`; also `rc`, `stable`): Omarchy (Arch Linux, Hyprland) with cua-spacesd, as an amd64 VM (QEMU locally, KubeVirt in the cloud; emulated on arm64 hosts). || [`Overlay`](/cua-sdk/reference/sandbox#overlay-record) | record | A binary to inject into a sandbox. || [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record) | record | What an overlay did. |+| [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record) | record | A one-time code that adds a machine to the account ("Add a machine" by link or QR code). || [`parse_sandbox_ref`](/cua-sdk/reference/sandbox#parse_sandbox_ref) | function | Parses a sandbox ref: `local:<name>`, `cloud:<name>`, `direct:<host:port>`, `relay:<machine-id>`, a legacy spelling (`space://fleet/<ns>/<claim>`, `fleet:<ns>:<claim>`, `url:<addr>`, a URL), or a bare name. || [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record) | record | A persistent agent: a named harness whose memory (its home in the Cua Drive) outlives its runs and its Space. || [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record) | record | How to create a persistent agent. |diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex 01bb8f1897..7fdba49866 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -29,11 +29,19 @@ pub enum HostCmd {cua host setup --direct 0.0.0.0:3211 --name studio-mac# A spare Mac on your tailnet that runs Spaces, without the relay# (prints the command that adds it on your laptop)- cua host setup --direct 100.101.102.103:3211 --profile spare")]+ cua host setup --direct 100.101.102.103:3211 --profile spare+ # Add this machine with a one-time code from the Cua Spaces app+ # (Add a machine) or `cua host pair`: no sign-in needed here+ cua host setup --pair K7QM-4XPB-2RHD")]Setup {/// Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai).#[arg(long, conflicts_with = "direct")]relay: Option<String>,+ /// Join with a one-time pairing code (or add-machine link) made in+ /// the Cua Spaces app or with `cua host pair`, instead of signing+ /// in here. The machine joins the account (or team) that made it.+ #[arg(long, value_name = "CODE", conflicts_with_all = ["direct", "remote"])]+ pair: Option<String>,/// When sign-in is needed, use a device code to approve it in a/// browser on another machine. The account session is not saved.#[arg(long, conflicts_with = "direct")]@@ -84,6 +92,35 @@ pub enum HostCmd {#[arg(long, requires = "direct")]allow_any_address: bool,},+ /// 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. Codes work once and expire (30 minutes by default). Run+ /// from an enrolled device.+ #[command(after_help = "Examples:+ cua host pair+ cua host pair --team team-aigis --expires 60+ cua host pair --list+ cua host pair --revoke pc_0123456789abcdef")]+ Pair {+ /// Add the machine for this team (its id).+ #[arg(long)]+ team: Option<String>,+ /// Name the machine gets (default: its own host name).+ #[arg(long)]+ name: Option<String>,+ /// Minutes until the code expires (1 to 1440).+ #[arg(long, value_name = "MINUTES", default_value_t = 30)]+ expires: u64,+ /// List your codes (used, unused, revoked, expired) instead.+ #[arg(long, conflicts_with_all = ["revoke", "team", "name"])]+ list: bool,+ /// Revoke an unused code by id (`pc_…`).+ #[arg(long, value_name = "ID", conflicts_with_all = ["team", "name"])]+ revoke: Option<String>,+ /// Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai).+ #[arg(long)]+ relay: Option<String>,+ },/// Show or change what this machine shares: its own desktop, and/// whether it creates Spaces for your other devices.#[command(after_help = "Examples:@@ -1211,6 +1248,7 @@ pub async fn run_host(match cmd {HostCmd::Setup {relay,+ pair,remote: _, // Selected by the command's SetupTokens.direct,name,@@ -1225,12 +1263,18 @@ pub async fn run_host(max_spaces,allow_any_address,} => {+ // A pasted add-machine link names its relay (`?relay=`) when the+ // code came from another relay than the default.+ let relay = relay.or_else(|| pair.as_deref().and_then(cua_host::pairing_link_relay));let mut opts = match direct {Some(addr) => SetupOptions::direct(addr.parse().map_err(|_| {CuaError::InvalidArgument(format!("--direct {addr:?} is not ip:port"))})?),None => SetupOptions::relay(relay.unwrap_or_else(cua_host::relay_url_from_env)),};+ // The code is single use: install the driver first, so a failed+ // download does not spend it.+ opts.download_first = pair.is_some();opts.name = name;opts.allow = allow;opts.driver_bin = driver_bin;@@ -1250,6 +1294,16 @@ pub async fn run_host(}opts.max_spaces = max_spaces;opts.allow_any_address = allow_any_address;+ // A pairing code stands in for the account: nothing to sign in.+ let paired = pair+ .as_deref()+ .map(cua_host::PairingCodeToken::parse)+ .transpose()+ .map_err(host_err)?;+ let tokens: &dyn AccountTokens = match &paired {+ Some(p) => p,+ None => tokens,+ };let s = host.setup_staged(opts, tokens).await@@ -1298,6 +1352,32 @@ pub async fn run_host(}}}+ HostCmd::Pair {+ team,+ name,+ expires,+ list,+ revoke,+ relay,+ } => {+ // Only the stored `cua auth login` session: making a code is+ // no reason to start a sign-in for "this machine".+ pair_codes(+ home,+ &SessionTokens,+ device,+ relay,+ team,+ name,+ expires,+ list,+ revoke,+ json,+ out,+ )+ .await+ .map_err(host_err)?;+ }HostCmd::Status => {let s = host.status().await.map_err(host_err)?;emit(&s, json, out)?;@@ -1410,6 +1490,116 @@ fn print_allow(allow: &[String], json: bool, out: &mut dyn Write) {}}+/// `cua host pair`: mints (default), lists or revokes pairing codes as the+/// account from this enrolled device.+#[allow(clippy::too_many_arguments)]+async fn pair_codes(+ home: &Path,+ tokens: &dyn AccountTokens,+ device: Option<&DeviceAuth>,+ relay: Option<String>,+ team: Option<String>,+ name: Option<String>,+ expires: u64,+ list: bool,+ revoke: Option<String>,+ json: bool,+ out: &mut dyn Write,+) -> cua_host::Result<()> {+ let url = relay_url(relay.clone(), home);+ // The device session is per relay: with --relay, this device's+ // enrollment there.+ let other = match relay {+ Some(_) => crate::devices_cmd::device_auth(&url).ok(),+ None => None,+ };+ let device = other.as_deref().or(device);+ let session = match device {+ Some(d) => d.try_session().await,+ None => None,+ };+ let client = RelayClient::new(&url)?.with_device_session(session);+ let token = tokens.access_token().await?;+ if let Some(id) = revoke {+ client.revoke_pairing_code(&token, &id).await?;+ if json {+ line(out, serde_json::json!({ "revoked": id }).to_string());+ } else {+ line(+ out,+ format!("Revoked {id}: it can no longer add a machine."),+ );+ }+ return Ok(());+ }+ if list {+ let codes = client.pairing_codes(&token).await?;+ if json {+ line(out, serde_json::json!({ "codes": codes }).to_string());+ } else if codes.is_empty() {+ line(out, "No pairing codes.");+ } else {+ for c in codes {+ let what = match (&c.state[..], &c.machine) {+ ("used", Some(m)) => format!("used by {m}"),+ (state, _) => state.to_string(),+ };+ let team = c.team.map(|t| format!(" team {t}")).unwrap_or_default();+ line(out, format!("{} {what}{team}", c.id));+ }+ }+ return Ok(());+ }+ if !(1..=1440).contains(&expires) {+ return Err(cua_host::Error::InvalidArgument(+ "--expires is 1 to 1440 minutes".into(),+ ));+ }+ let minted = client+ .create_pairing_code(+ &token,+ &cua_host::PairingCodeRequest {+ name,+ team,+ ttl_secs: Some(expires * 60),+ },+ )+ .await?;+ let code = minted+ .code+ .clone()+ .filter(|c| cua_host::normalize_pairing_code(c).is_some())+ .ok_or_else(|| cua_host::Error::Relay("the relay returned no pairing code".into()))?;+ let link = cua_host::add_machine_url(&code, &url);+ let sh = cua_host::install_command(&code, &url, "linux");+ let ps = cua_host::install_command(&code, &url, "windows");+ if json {+ line(+ out,+ serde_json::json!({+ "id": minted.id, "code": code, "url": link, "expires_at": minted.expires_at,+ "team": minted.team, "install": {"sh": sh, "powershell": ps},+ })+ .to_string(),+ );+ } else {+ for l in [+ format!(+ "Code {code} (works once, expires in {expires} min; id {})",+ minted.id+ ),+ format!("Open on the other computer: {link}"),+ "Or run there:".to_string(),+ format!(" macOS / Linux: {sh}"),+ format!(" Windows: {ps}"),+ format!(" cua installed: cua host setup --pair {code}"),+ ] {+ line(out, l);+ }+ }+ Ok(())+}+/// Adds (`add`) or removes `who` on the allowlist of `machine` (default:/// this machine) through the relay, as the account from this device, and/// mirrors it into this machine's driver policy when it is the target.diff --git a/libs/cua/crates/cua-cli/tests/host_setup.rs b/libs/cua/crates/cua-cli/tests/host_setup.rsindex 9789f91fe0..7e179518e4 100644--- a/libs/cua/crates/cua-cli/tests/host_setup.rs+++ b/libs/cua/crates/cua-cli/tests/host_setup.rs@@ -245,3 +245,40 @@ async fn remote_is_documented_and_conflicts_with_direct() {);assert!(!h.cua_home().join("host").exists());}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn pair_never_signs_in_and_keeps_the_code_when_the_download_fails() {+ let oidc = issuer(None).await;+ let relay = FakeHttp::start(|_| (500, json!({"error": "must not register"}))).await;+ let h = home(&oidc, &relay);+ // A pasted link works as well as the typed code (any case). The driver+ // is installed before the code is used, so a failed download spends+ // nothing: the relay is never asked.+ let o = setup(&h, &["--pair", "https://spaces.cua.ai/add/k7qm-4xpb-2rhd"]).await;+ assert_eq!(o.code, 2, "{o:?}");+ assert!(o.stderr.contains("host setup failed at download:"), "{o:?}");+ assert!(!o.stderr.contains("Sign in"), "{o:?}");+ assert!(oidc.requests().is_empty(), "no sign-in with a pairing code");+ assert!(relay.requests().is_empty(), "code not spent");+ assert!(!h.cua_home().join("host/machine-token").exists());+ no_account_state(&h);++ // A malformed code stops before anything else.+ let o = setup(&h, &["--pair", "not-a-code"]).await;+ assert_ne!(o.code, 0, "{o:?}");+ assert!(o.stderr.contains("is not a pairing code"), "{o:?}");+ assert!(relay.requests().is_empty());++ let o = h+ .run(&[+ "host",+ "setup",+ "--pair",+ "K7QM4XPB2RHD",+ "--direct",+ "127.0.0.1:3211",+ ])+ .await;+ assert_eq!(o.code, 2, "{o:?}");+ assert!(o.stderr.contains("cannot be used with"), "{o:?}");+}diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex d407e94807..f42cff33db 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -86,6 +86,9 @@ pub struct SetupOptions {/// Tailscale and private LAN addresses, and allow a public listen/// address (see [`crate::direct`]). Default off.pub allow_any_address: bool,+ /// Install the driver before registering (a single-use pairing code is+ /// then spent only once the download worked). Default off.+ pub download_first: bool,}impl SetupOptions {@@ -102,6 +105,7 @@ impl SetupOptions {max_spaces: None,cua_bin: None,allow_any_address: false,+ download_first: false,}}@@ -124,6 +128,7 @@ impl SetupOptions {max_spaces: None,cua_bin: None,allow_any_address: false,+ download_first: false,}}}@@ -985,6 +990,10 @@ impl Host {provide_spaces: opts.provide_spaces,..Default::default()};+ if opts.download_first {+ *stage = SetupStage::Download;+ install_driver(opts.driver_bin.as_deref(), &config.driver_bin).await?;+ }match &opts.mode {HostMode::Relay { url } => {let relay = RelayClient::new(url)?;@@ -1057,16 +1066,10 @@ impl Host {write_json(&self.paths.policy(), &policy)?;}}- *stage = SetupStage::Download;- let source = driver::locate(opts.driver_bin.as_deref())?;- match &source {- DriverSource::Download(url) => tracing::info!(%url, "downloading cua-spacesd"),- DriverSource::Release { version, url, .. } => {- tracing::info!(%version, %url, "downloading cua-spacesd")- }- DriverSource::Local(_) => {}+ if !opts.download_first {+ *stage = SetupStage::Download;+ install_driver(opts.driver_bin.as_deref(), &config.driver_bin).await?;}- driver::install_to(&source, &config.driver_bin).await?;*stage = SetupStage::Service;write_json(&self.paths.config(), &config)?;let manager = self.manager(runner);@@ -1648,6 +1651,19 @@ pub fn owned_by(policy: &HostPolicy, account: &str) -> bool {.is_some_and(|e| e.eq_ignore_ascii_case(account))}+/// Locates (or downloads) cua-spacesd and installs it at `dest`.+async fn install_driver(explicit: Option<&Path>, dest: &Path) -> Result<()> {+ let source = driver::locate(explicit)?;+ match &source {+ DriverSource::Download(url) => tracing::info!(%url, "downloading cua-spacesd"),+ DriverSource::Release { version, url, .. } => {+ tracing::info!(%version, %url, "downloading cua-spacesd")+ }+ DriverSource::Local(_) => {}+ }+ driver::install_to(&source, dest).await+}+#[cfg(test)]mod tests {#[test]diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rsindex f17e19e688..ba1560cce4 100644--- a/libs/cua/crates/cua-host/src/lib.rs+++ b/libs/cua/crates/cua-host/src/lib.rs@@ -37,6 +37,7 @@ pub mod direct;pub mod driver;mod host;pub mod machine;+pub mod pairing;pub mod preflight;pub mod provided;pub mod relay;@@ -57,6 +58,10 @@ pub use host::{SpacesDaemon, local_network_hint, permission_hints,};pub use machine::machine_id;+pub use pairing::{+ PairingCode, PairingCodeRequest, PairingCodeToken, add_machine_url, display_pairing_code,+ install_command, normalize_pairing_code, pairing_link_relay,+};pub use provided::{HostProfile, HostSpacesSettings, MachineMatch, ProvidedSpace, SpacesAuditRecord, match_machine,};diff --git a/libs/cua/crates/cua-host/src/pairing.rs b/libs/cua/crates/cua-host/src/pairing.rsnew file mode 100644index 0000000000..722f745dc4--- /dev/null+++ b/libs/cua/crates/cua-host/src/pairing.rs@@ -0,0 +1,319 @@+//! Adding a machine by link or QR code.+//!+//! An enrolled device mints a one-time pairing code on the relay+//! ([`RelayClient::create_pairing_code`]) and shows it as a link+//! ([`add_machine_url`]) and QR code. The machine being added runs+//! `cua host setup --pair <code>`, which registers it with the code+//! ([`PairingCodeToken`]) instead of a signed-in account, so it needs no+//! browser sign-in. Codes are single use, expire (30 minutes unless asked+//! otherwise) and can be revoked ([`RelayClient::revoke_pairing_code`]).+//!+//! ```text+//! POST /v1/pairing-codes enrolled device -> PairingCode (with `code`)+//! GET /v1/pairing-codes enrolled device -> {"codes": [PairingCode]}+//! DELETE /v1/pairing-codes/{id} enrolled device -> 204+//! POST /v1/machines Bearer cpc_<code> -> Registration+//! ```++use crate::relay::{AccountTokens, DEFAULT_RELAY_URL, RelayClient};+use crate::{Error, Result};+use serde::{Deserialize, Serialize};++/// Prefix of a pairing code sent as a bearer token.+pub const PAIRING_TOKEN_PREFIX: &str = "cpc_";+/// Characters of a code.+pub const PAIRING_CODE_LEN: usize = 12;+/// Where an add-machine link opens.+pub const ADD_MACHINE_BASE_URL: &str = "https://spaces.cua.ai/add";++const ALPHABET: &str = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";++/// A code in canonical form (12 upper-case Crockford base32 characters)+/// from what a person typed, pasted or scanned: any case, with or without+/// dashes and spaces, `I`/`L` read as `1` and `O` as `0`. An add-machine+/// link (`…/add/<code>`) works too. `None` when it cannot be a code.+pub fn normalize_pairing_code(input: &str) -> Option<String> {+ let s = input.trim();+ let s = match s.split_once("/add/") {+ Some((_, rest)) => rest.split(['?', '#', '/']).next().unwrap_or(""),+ None => s,+ };+ let s = s.strip_prefix(PAIRING_TOKEN_PREFIX).unwrap_or(s);+ let mut out = String::with_capacity(PAIRING_CODE_LEN);+ for c in s.chars() {+ let c = match c.to_ascii_uppercase() {+ '-' | ' ' => continue,+ 'I' | 'L' => '1',+ 'O' => '0',+ c => c,+ };+ if !ALPHABET.contains(c) {+ return None;+ }+ out.push(c);+ }+ (out.len() == PAIRING_CODE_LEN).then_some(out)+}++/// The relay an add-machine link names (`…/add/<code>?relay=<url>`), if any.+pub fn pairing_link_relay(input: &str) -> Option<String> {+ let url = url::Url::parse(input.trim()).ok()?;+ url.query_pairs()+ .find(|(k, _)| k == "relay")+ .map(|(_, v)| v.trim().to_string())+ .filter(|v| !v.is_empty())+}++/// `XXXX-XXXX-XXXX` (input that is not a code is returned as is).+pub fn display_pairing_code(code: &str) -> String {+ match normalize_pairing_code(code) {+ Some(c) => format!("{}-{}-{}", &c[..4], &c[4..8], &c[8..]),+ None => code.to_string(),+ }+}++/// The add-machine link for `code`: `https://spaces.cua.ai/add/<code>`,+/// plus `?relay=<url>` when the machine must join another relay than+/// [`DEFAULT_RELAY_URL`].+pub fn add_machine_url(code: &str, relay: &str) -> String {+ let code = display_pairing_code(code);+ let relay = relay.trim().trim_end_matches('/');+ if relay.is_empty() || relay == DEFAULT_RELAY_URL {+ format!("{ADD_MACHINE_BASE_URL}/{code}")+ } else {+ let mut url = url::Url::parse(&format!("{ADD_MACHINE_BASE_URL}/{code}"))+ .expect("static add-machine URL");+ url.query_pairs_mut().append_pair("relay", relay);+ url.to_string()+ }+}++/// The one-line command that installs `cua` and adds the machine:+/// `os` is `windows` for PowerShell, anything else for sh.+pub fn install_command(code: &str, relay: &str, os: &str) -> String {+ let code = display_pairing_code(code);+ let relay = relay.trim().trim_end_matches('/');+ let custom = !relay.is_empty() && relay != DEFAULT_RELAY_URL;+ if os.eq_ignore_ascii_case("windows") {+ let mut cmd =+ format!("& ([scriptblock]::Create((irm https://cua.ai/install.ps1))) -Pair {code}");+ if custom {+ cmd.push_str(&format!(" -Relay {relay}"));+ }+ cmd+ } else {+ let mut cmd = format!("curl -fsSL https://cua.ai/install.sh | sh -s -- --pair {code}");+ if custom {+ cmd.push_str(&format!(" --relay {relay}"));+ }+ cmd+ }+}++/// A pairing code standing in for the account during `cua host setup`: the+/// relay registers the machine to the account that minted it.+pub struct PairingCodeToken(String);++impl PairingCodeToken {+ /// From what the person typed (see [`normalize_pairing_code`]).+ pub fn parse(input: &str) -> Result<Self> {+ normalize_pairing_code(input).map(Self).ok_or_else(|| {+ Error::InvalidArgument(format!(+ "{:?} is not a pairing code (12 letters and digits, like K7QM-4XPB-2RHD)",+ input.trim()+ ))+ })+ }++ /// The canonical code.+ pub fn code(&self) -> &str {+ &self.0+ }+}++#[async_trait::async_trait]+impl AccountTokens for PairingCodeToken {+ async fn access_token(&self) -> Result<String> {+ Ok(format!("{PAIRING_TOKEN_PREFIX}{}", self.0))+ }+}++/// `POST /v1/pairing-codes` body.+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]+pub struct PairingCodeRequest {+ /// Name for the machine (else the machine's own).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ /// Team (`team-…`) the machine is added to; the caller must be its owner+ /// or an admin.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub team: Option<String>,+ /// Lifetime in seconds (the relay clamps it to 60 s ..= 24 h; 30+ /// minutes when absent).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub ttl_secs: Option<u64>,+}++/// A pairing code of the account.+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]+pub struct PairingCode {+ /// `pc_…`.+ pub id: String,+ /// `XXXX-XXXX-XXXX`: only in the reply that minted it.+ #[serde(default)]+ pub code: Option<String>,+ /// `active`, `used`, `revoked` or `expired`.+ #[serde(default)]+ pub state: String,+ /// Name for the machine.+ #[serde(default)]+ pub name: Option<String>,+ /// Team.+ #[serde(default)]+ pub team: Option<String>,+ /// Unix seconds.+ #[serde(default)]+ pub created_at: u64,+ /// Unix seconds.+ #[serde(default)]+ pub expires_at: u64,+ /// When a machine used it.+ #[serde(default)]+ pub used_at: Option<u64>,+ /// The machine it added.+ #[serde(default)]+ pub machine: Option<String>,+}++#[derive(Deserialize)]+struct PairingCodeList {+ #[serde(default)]+ codes: Vec<PairingCode>,+}++impl RelayClient {+ /// Mints a one-time pairing code (from an enrolled device: needs+ /// [`RelayClient::with_device_session`]).+ pub async fn create_pairing_code(+ &self,+ account_token: &str,+ req: &PairingCodeRequest,+ ) -> Result<PairingCode> {+ self.send_json(+ reqwest::Method::POST,+ "/v1/pairing-codes",+ Some(req),+ account_token,+ )+ .await+ }++ /// The account's pairing codes, newest first (never the codes).+ pub async fn pairing_codes(&self, account_token: &str) -> Result<Vec<PairingCode>> {+ let list: PairingCodeList = self+ .send_json::<(), _>(+ reqwest::Method::GET,+ "/v1/pairing-codes",+ None,+ account_token,+ )+ .await?;+ Ok(list.codes)+ }++ /// Revokes an unused pairing code (`pc_…`).+ pub async fn revoke_pairing_code(&self, account_token: &str, id: &str) -> Result<()> {+ let valid = id+ .strip_prefix("pc_")+ .is_some_and(|h| !h.is_empty() && h.bytes().all(|b| b.is_ascii_alphanumeric()));+ if !valid {+ return Err(Error::InvalidArgument(format!(+ "{id:?} is not a pairing code id (pc_…; see `cua host pair --list`)"+ )));+ }+ let _: serde_json::Value = self+ .send_json::<(), _>(+ reqwest::Method::DELETE,+ &format!("/v1/pairing-codes/{id}"),+ None,+ account_token,+ )+ .await?;+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn codes_read_the_way_people_type_them() {+ assert_eq!(+ normalize_pairing_code("k7qm-4xpb-2rhd").as_deref(),+ Some("K7QM4XPB2RHD")+ );+ assert_eq!(+ normalize_pairing_code("https://spaces.cua.ai/add/K7QM-4XPB-2RHD?relay=x").as_deref(),+ Some("K7QM4XPB2RHD")+ );+ assert_eq!(+ normalize_pairing_code("cpc_OILO 0000 0000").as_deref(),+ Some("011000000000")+ );+ assert_eq!(normalize_pairing_code("K7QM-4XPB-2RH"), None);+ assert_eq!(normalize_pairing_code("K7QM-4XPB-2RHU"), None);+ match PairingCodeToken::parse("nope") {+ Err(Error::InvalidArgument(m)) => assert!(m.contains("is not a pairing code"), "{m}"),+ other => panic!("expected InvalidArgument, got {:?}", other.map(|t| t.0)),+ }+ assert_eq!(+ pairing_link_relay(+ "https://spaces.cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Fr.example"+ )+ .as_deref(),+ Some("https://r.example")+ );+ assert_eq!(pairing_link_relay("K7QM-4XPB-2RHD"), None);+ assert_eq!(display_pairing_code("k7qm4xpb2rhd"), "K7QM-4XPB-2RHD");+ }++ #[test]+ fn links_and_commands_carry_a_custom_relay_only() {+ assert_eq!(+ add_machine_url("k7qm4xpb2rhd", DEFAULT_RELAY_URL),+ "https://spaces.cua.ai/add/K7QM-4XPB-2RHD"+ );+ assert_eq!(+ add_machine_url("K7QM4XPB2RHD", "https://relay.example.com/"),+ "https://spaces.cua.ai/add/K7QM-4XPB-2RHD?relay=https%3A%2F%2Frelay.example.com"+ );+ assert_eq!(+ install_command("K7QM4XPB2RHD", DEFAULT_RELAY_URL, "linux"),+ "curl -fsSL https://cua.ai/install.sh | sh -s -- --pair K7QM-4XPB-2RHD"+ );+ assert_eq!(+ install_command("K7QM4XPB2RHD", "https://r.example", "windows"),+ "& ([scriptblock]::Create((irm https://cua.ai/install.ps1))) -Pair K7QM-4XPB-2RHD -Relay https://r.example"+ );+ }++ #[tokio::test]+ async fn revoking_refuses_ids_that_are_not_code_ids() {+ let client = RelayClient::new("http://127.0.0.1:9").unwrap();+ for id in ["../machines/m_123", "pc_", "pc_a/b", "x"] {+ match client.revoke_pairing_code("t", id).await {+ Err(Error::InvalidArgument(m)) => {+ assert!(m.contains("not a pairing code id"), "{m}")+ }+ other => panic!("{id}: {other:?}"),+ }+ }+ }++ #[tokio::test]+ async fn the_code_is_the_bearer_for_registration() {+ let t = PairingCodeToken::parse("k7qm-4xpb-2rhd").unwrap();+ assert_eq!(t.access_token().await.unwrap(), "cpc_K7QM4XPB2RHD");+ }+}diff --git a/libs/cua/crates/cua-host/src/relay.rs b/libs/cua/crates/cua-host/src/relay.rsindex 8f2dacede7..001ceda6b9 100644--- a/libs/cua/crates/cua-host/src/relay.rs+++ b/libs/cua/crates/cua-host/src/relay.rs@@ -543,6 +543,21 @@ impl RelayClient {.map_err(|e| (Error::Relay(format!("bad relay response: {e}")), false))}+ /// One call with an optional JSON body (see [`RelayClient::send`]).+ pub(crate) async fn send_json<B: Serialize, T: serde::de::DeserializeOwned>(+ &self,+ method: reqwest::Method,+ path: &str,+ body: Option<&B>,+ bearer: &str,+ ) -> Result<T> {+ let mut req = self.http.request(method, self.url(path));+ if let Some(b) = body {+ req = req.json(b);+ }+ self.send(req, bearer).await+ }+/// `GET /v1/info` (no auth).pub async fn info(&self) -> Result<RelayInfo> {let resp = selfdiff --git a/libs/cua/crates/cua-host/src/setup_tests.rs b/libs/cua/crates/cua-host/src/setup_tests.rsindex c10e909de4..cdb839c7fb 100644--- a/libs/cua/crates/cua-host/src/setup_tests.rs+++ b/libs/cua/crates/cua-host/src/setup_tests.rs@@ -184,3 +184,43 @@ fn http_status_reads_relay_and_download_errors() {}assert_eq!(SetupStage::Register.as_str(), "register");}++#[tokio::test]+async fn a_pairing_code_sets_up_the_machine_once_and_a_failed_download_does_not_spend_it() {+ let relay = FakeRelay::start().await;+ relay.add_account("acct-token", "ada", Some("[email protected]"));+ let code = RelayClient::new(&relay.url)+ .unwrap()+ .create_pairing_code("acct-token", &PairingCodeRequest::default())+ .await+ .unwrap()+ .code+ .unwrap();+ let token = PairingCodeToken::parse(&code).unwrap();++ // The driver is missing: setup stops at the download, before the relay+ // is asked, so the code is still good.+ let f = fixture();+ let mut opts = f.opts(&relay.url);+ opts.download_first = true;+ opts.driver_bin = Some(f.home.join("missing-spacesd"));+ let (stage, _) = f.host().setup_staged(opts, &token).await.unwrap_err();+ assert_eq!(stage, SetupStage::Download);+ assert_eq!(relay.register_calls(), 0);++ // With the driver: registered as the account that made the code.+ let mut opts = f.opts(&relay.url);+ opts.download_first = true;+ let status = f.host().setup(opts, &token).await.unwrap();+ assert!(status.configured);+ let id = f.host().config().unwrap().unwrap().machine_id.unwrap();+ assert_eq!(relay.machine(&id).unwrap().owner.id, "ada");++ // Spent: another machine cannot use it.+ let g = fixture();+ let mut opts = g.opts(&relay.url);+ opts.download_first = true;+ let (stage, e) = g.host().setup_staged(opts, &token).await.unwrap_err();+ assert_eq!(stage, SetupStage::Register);+ assert_eq!(e.http_status(), Some(401), "{e}");+}diff --git a/libs/cua/crates/cua-host/src/testing.rs b/libs/cua/crates/cua-host/src/testing.rsindex 141a11538c..b6c4229ef0 100644--- a/libs/cua/crates/cua-host/src/testing.rs+++ b/libs/cua/crates/cua-host/src/testing.rs@@ -86,6 +86,44 @@ struct State_ {/// What `GET /v1/usage` answers; none: 404, as a relay that does not/// meter.usage: Option<serde_json::Value>,+ /// Pairing codes by canonical code.+ pairing: BTreeMap<String, FakePairing>,+}++#[derive(Clone, Debug)]+struct FakePairing {+ id: String,+ owner: Identity,+ name: Option<String>,+ team: Option<String>,+ created_at: u64,+ expires_at: u64,+ used_at: Option<u64>,+ machine: Option<String>,+ revoked: bool,+}++impl FakePairing {+ fn state(&self) -> &'static str {+ if self.used_at.is_some() {+ "used"+ } else if self.revoked {+ "revoked"+ } else if now_secs() >= self.expires_at {+ "expired"+ } else {+ "active"+ }+ }++ fn view(&self, code: Option<&str>) -> serde_json::Value {+ serde_json::json!({+ "id": self.id, "code": code.map(crate::pairing::display_pairing_code),+ "state": self.state(), "name": self.name, "team": self.team,+ "created_at": self.created_at, "expires_at": self.expires_at,+ "used_at": self.used_at, "machine": self.machine,+ })+ }}impl State_ {@@ -257,10 +295,36 @@ async fn register(let status = StatusCode::from_u16(code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);return err(status, "the fake relay failed this registration");}- let Some(Caller::Account(who)) = caller(&st, &headers) else {- return err(StatusCode::UNAUTHORIZED, "account token required");- };let id = body["id"].as_str().unwrap_or_default().to_string();+ // A pairing code registers as the account that minted it, once.+ let paired = bearer(&headers).and_then(|t| {+ t.strip_prefix(crate::pairing::PAIRING_TOKEN_PREFIX)+ .map(str::to_string)+ });+ let mut team = None;+ let mut code_name = None;+ let who = match paired {+ Some(code) => {+ let Some(p) = crate::pairing::normalize_pairing_code(&code)+ .and_then(|c| st.pairing.get_mut(&c))+ .filter(|p| p.state() == "active")+ else {+ return err(StatusCode::UNAUTHORIZED, "this pairing code is not valid");+ };+ if id.len() < 8 {+ return err(StatusCode::BAD_REQUEST, "invalid machine id");+ }+ p.used_at = Some(now_secs());+ p.machine = Some(id.clone());+ team = p.team.clone();+ code_name = p.name.clone();+ p.owner.clone()+ }+ None => match caller(&st, &headers) {+ Some(Caller::Account(who)) => who,+ _ => return err(StatusCode::UNAUTHORIZED, "account token required"),+ },+ };if id.len() < 8 {return err(StatusCode::BAD_REQUEST, "invalid machine id");}@@ -294,7 +358,7 @@ async fn register(let token = format!("cmt_{:032x}", rand::random::<u128>());let machine = Machine {id: id.clone(),- name: body["name"].as_str().unwrap_or_default().to_string(),+ name: code_name.unwrap_or_else(|| body["name"].as_str().unwrap_or_default().to_string()),owner: who.clone(),role: "owner".into(),online: false,@@ -316,6 +380,7 @@ async fn register(.map(|o| {o.iter().filter_map(|(k, v)| v.as_str().map(|v| (k.clone(), v.to_string())))+ .chain(team.map(|t| ("cua.team".to_string(), t))).collect()}).unwrap_or_default(),@@ -338,6 +403,83 @@ async fn register(.into_response()}+async fn pairing_mint(+ State(s): State<S>,+ headers: HeaderMap,+ Json(body): Json<serde_json::Value>,+) -> Response {+ let mut st = s.lock().unwrap();+ if let Err(r) = st.gate(&headers) {+ return r;+ }+ let Some(Caller::Account(who)) = caller(&st, &headers) else {+ return err(StatusCode::UNAUTHORIZED, "account token required");+ };+ let code: String = (0..12)+ .map(|_| b"0123456789ABCDEFGHJKMNPQRSTVWXYZ"[(rand::random::<u32>() % 32) as usize] as char)+ .collect();+ let now = now_secs();+ let p = FakePairing {+ id: format!("pc_{:016x}", rand::random::<u64>()),+ owner: who,+ name: body["name"].as_str().map(str::to_string),+ team: body["team"].as_str().map(str::to_string),+ created_at: now,+ expires_at: now + body["ttl_secs"].as_u64().unwrap_or(1800).clamp(60, 86_400),+ used_at: None,+ machine: None,+ revoked: false,+ };+ let view = p.view(Some(&code));+ st.pairing.insert(code, p);+ (StatusCode::CREATED, Json(view)).into_response()+}++async fn pairing_list(State(s): State<S>, headers: HeaderMap) -> Response {+ let st = s.lock().unwrap();+ if let Err(r) = st.gate(&headers) {+ return r;+ }+ let Some(Caller::Account(who)) = caller(&st, &headers) else {+ return err(StatusCode::UNAUTHORIZED, "account token required");+ };+ let mut codes: Vec<&FakePairing> = st+ .pairing+ .values()+ .filter(|p| p.owner.id == who.id)+ .collect();+ codes.sort_by_key(|p| std::cmp::Reverse(p.created_at));+ let codes: Vec<_> = codes.into_iter().map(|p| p.view(None)).collect();+ Json(serde_json::json!({ "codes": codes })).into_response()+}++async fn pairing_revoke(+ State(s): State<S>,+ Path(id): Path<String>,+ headers: HeaderMap,+) -> Response {+ let mut st = s.lock().unwrap();+ if let Err(r) = st.gate(&headers) {+ return r;+ }+ let Some(Caller::Account(who)) = caller(&st, &headers) else {+ return err(StatusCode::UNAUTHORIZED, "account token required");+ };+ match st+ .pairing+ .values_mut()+ .find(|p| p.id == id && p.owner.id == who.id)+ {+ Some(p) => {+ if p.state() == "active" {+ p.revoked = true;+ }+ StatusCode::NO_CONTENT.into_response()+ }+ None => err(StatusCode::NOT_FOUND, "no such pairing code"),+ }+}+async fn list(State(s): State<S>, headers: HeaderMap) -> Response {let st = s.lock().unwrap();if let Err(r) = st.gate(&headers) {@@ -975,6 +1117,11 @@ impl FakeRelay {).route("/v1/teams/{id}/audit", get(team_audit)).route("/v1/usage", get(usage))+ .route("/v1/pairing-codes", get(pairing_list).post(pairing_mint))+ .route(+ "/v1/pairing-codes/{id}",+ axum::routing::delete(pairing_revoke),+ ).fallback(proxied).with_state(state.clone());let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rsindex 1eef81d329..a418ddb218 100644--- a/libs/cua/crates/cua-sdk/src/native/host.rs+++ b/libs/cua/crates/cua-sdk/src/native/host.rs@@ -104,6 +104,54 @@ impl From<cua_host::Machine> for RelayMachine {}}+/// A one-time code that adds a machine to the account ("Add a machine"+/// by link or QR code).+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]+pub struct PairingCode {+ /// `pc_…` (to revoke it).+ pub id: String,+ /// `XXXX-XXXX-XXXX`: only when just made.+ pub code: Option<String>,+ /// `https://spaces.cua.ai/add/<code>` (the link and the QR code): only+ /// when just made.+ pub url: Option<String>,+ /// `curl … | sh -s -- --pair <code>` (macOS, Linux): only when just made.+ pub install_sh: Option<String>,+ /// The PowerShell one-liner (Windows): only when just made.+ pub install_powershell: Option<String>,+ /// `active`, `used`, `revoked` or `expired`.+ pub state: String,+ /// Team the machine is added for.+ pub team: Option<String>,+ /// Unix seconds.+ pub created_at: u64,+ /// Unix seconds.+ pub expires_at: u64,+ /// When a machine used it.+ pub used_at: Option<u64>,+ /// The machine it added (relay machine id).+ pub machine: Option<String>,+}++impl PairingCode {+ fn from_host(p: cua_host::PairingCode, relay: &str) -> Self {+ let made = |f: &dyn Fn(&str) -> String| p.code.as_deref().map(f);+ Self {+ url: made(&|c| cua_host::add_machine_url(c, relay)),+ install_sh: made(&|c| cua_host::install_command(c, relay, "linux")),+ install_powershell: made(&|c| cua_host::install_command(c, relay, "windows")),+ id: p.id,+ code: p.code,+ state: p.state,+ team: p.team,+ created_at: p.created_at,+ expires_at: p.expires_at,+ used_at: p.used_at,+ machine: p.machine,+ }+ }+}+/// The signed-in account's view of a cua-relay.#[derive(uniffi::Object)]pub struct Relay {@@ -922,6 +970,72 @@ impl Devices {run(async move { Ok(auth.revoke(&id).await?.into()) }).await}+ /// Makes a one-time code (link, QR, install commands) that adds another+ /// computer to the account, or to `team` (from this enrolled device).+ /// It expires after `ttl_secs` (30 minutes when `None`).+ pub async fn create_pairing_code(+ &self,+ team: Option<String>,+ ttl_secs: Option<u64>,+ ) -> Result<PairingCode> {+ let auth = self.auth.clone();+ let tokens = self.tokens.clone();+ run(async move {+ let session = auth.session().await?;+ let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;+ let relay = auth.relay_url().to_string();+ let code = cua_host::RelayClient::new(&relay)?+ .with_device_session(Some(session))+ .create_pairing_code(+ &token,+ &cua_host::PairingCodeRequest {+ name: None,+ team,+ ttl_secs,+ },+ )+ .await?;+ Ok(PairingCode::from_host(code, &relay))+ })+ .await+ }++ /// The account's pairing codes, newest first (without the codes).+ pub async fn pairing_codes(&self) -> Result<Vec<PairingCode>> {+ let auth = self.auth.clone();+ let tokens = self.tokens.clone();+ run(async move {+ let session = auth.session().await?;+ let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;+ let relay = auth.relay_url().to_string();+ let codes = cua_host::RelayClient::new(&relay)?+ .with_device_session(Some(session))+ .pairing_codes(&token)+ .await?;+ Ok(codes+ .into_iter()+ .map(|c| PairingCode::from_host(c, &relay))+ .collect())+ })+ .await+ }++ /// Revokes an unused pairing code (`pc_…`).+ pub async fn revoke_pairing_code(&self, id: String) -> Result<()> {+ let auth = self.auth.clone();+ let tokens = self.tokens.clone();+ run(async move {+ let session = auth.session().await?;+ let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;+ cua_host::RelayClient::new(auth.relay_url())?+ .with_device_session(Some(session))+ .revoke_pairing_code(&token, &id)+ .await?;+ Ok(())+ })+ .await+ }+/// Vouches for `machine_id`, a machine that registered without an/// enrolled device's signature or MFA (from this enrolled device) (S5)./// Clears [`RelayMachine::confirmed`]'s "new" flag for every accountdiff --git a/libs/cua/crates/cua-telemetry/src/cli_commands.in b/libs/cua/crates/cua-telemetry/src/cli_commands.inindex 84483f1e08..d6bc3f999d 100644--- a/libs/cua/crates/cua-telemetry/src/cli_commands.in+++ b/libs/cua/crates/cua-telemetry/src/cli_commands.in@@ -90,6 +90,7 @@"fleet.pool","fleet.pools","host.config",+ "host.pair","host.remove","host.setup","host.share",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 80f7481944..b3b6f02007 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@@ -1021,16 +1021,22 @@ external fun uniffi_cua_sdk_checksum_method_devices_check_enrolled(): Shortexternal fun uniffi_cua_sdk_checksum_method_devices_confirm_machine(): Short+external fun uniffi_cua_sdk_checksum_method_devices_create_pairing_code(+): Shortexternal fun uniffi_cua_sdk_checksum_method_devices_device_id(): Shortexternal fun uniffi_cua_sdk_checksum_method_devices_enroll(): Short+external fun uniffi_cua_sdk_checksum_method_devices_pairing_codes(+): Shortexternal fun uniffi_cua_sdk_checksum_method_devices_relay_url(): Shortexternal fun uniffi_cua_sdk_checksum_method_devices_rename(): Shortexternal fun uniffi_cua_sdk_checksum_method_devices_revoke(): Short+external fun uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code(+): Shortexternal fun uniffi_cua_sdk_checksum_method_devices_snapshot(): Shortexternal fun uniffi_cua_sdk_checksum_method_host_configure(@@ -1869,16 +1875,22 @@ external fun uniffi_cua_sdk_fn_method_devices_check_enrolled(`ptr`: Long,): Longexternal fun uniffi_cua_sdk_fn_method_devices_confirm_machine(`ptr`: Long,`machineId`: RustBuffer.ByValue,): Long+external fun uniffi_cua_sdk_fn_method_devices_create_pairing_code(`ptr`: Long,`team`: RustBuffer.ByValue,`ttlSecs`: RustBuffer.ByValue,+): Longexternal fun uniffi_cua_sdk_fn_method_devices_device_id(`ptr`: Long,uniffi_out_err: UniffiRustCallStatus,): RustBuffer.ByValueexternal fun uniffi_cua_sdk_fn_method_devices_enroll(`ptr`: Long,): Long+external fun uniffi_cua_sdk_fn_method_devices_pairing_codes(`ptr`: Long,+): Longexternal fun uniffi_cua_sdk_fn_method_devices_relay_url(`ptr`: Long,uniffi_out_err: UniffiRustCallStatus,): RustBuffer.ByValueexternal fun uniffi_cua_sdk_fn_method_devices_rename(`ptr`: Long,`id`: RustBuffer.ByValue,`name`: RustBuffer.ByValue,): Longexternal fun uniffi_cua_sdk_fn_method_devices_revoke(`ptr`: Long,`id`: RustBuffer.ByValue,): Long+external fun uniffi_cua_sdk_fn_method_devices_revoke_pairing_code(`ptr`: Long,`id`: RustBuffer.ByValue,+): Longexternal fun uniffi_cua_sdk_fn_method_devices_snapshot(`ptr`: Long,`auditLimit`: Int,): Longexternal fun uniffi_cua_sdk_fn_clone_host(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,@@ -3204,12 +3216,18 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cua_sdk_checksum_method_devices_confirm_machine() != 44995.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}+ if (lib.uniffi_cua_sdk_checksum_method_devices_create_pairing_code() != 19274.toShort()) {+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ }if (lib.uniffi_cua_sdk_checksum_method_devices_device_id() != 58064.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}if (lib.uniffi_cua_sdk_checksum_method_devices_enroll() != 25682.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}+ if (lib.uniffi_cua_sdk_checksum_method_devices_pairing_codes() != 10069.toShort()) {+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ }if (lib.uniffi_cua_sdk_checksum_method_devices_relay_url() != 39774.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}@@ -3219,6 +3237,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cua_sdk_checksum_method_devices_revoke() != 27802.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}+ if (lib.uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code() != 3143.toShort()) {+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ }if (lib.uniffi_cua_sdk_checksum_method_devices_snapshot() != 26132.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}@@ -7800,6 +7821,13 @@ public interface DevicesInterface {*/suspend fun `confirmMachine`(`machineId`: kotlin.String): RelayMachine+ /**+ * Makes a one-time code (link, QR, install commands) that adds another+ * computer to the account, or to `team` (from this enrolled device).+ * It expires after `ttl_secs` (30 minutes when `None`).+ */+ suspend fun `createPairingCode`(`team`: kotlin.String?, `ttlSecs`: kotlin.ULong?): PairingCode+/*** This device's id, when it has a key (no network).*/@@ -7813,6 +7841,11 @@ public interface DevicesInterface {*/suspend fun `enroll`(): DeviceEnrollment+ /**+ * The account's pairing codes, newest first (without the codes).+ */+ suspend fun `pairingCodes`(): List<PairingCode>+/*** The relay base URL.*/@@ -7829,6 +7862,11 @@ public interface DevicesInterface {*/suspend fun `revoke`(`id`: kotlin.String): RelayDevice+ /**+ * Revokes an unused pairing code (`pc_…`).+ */+ suspend fun `revokePairingCode`(`id`: kotlin.String)+/*** The account's devices, the grace period, the newest `audit_limit`* audit events and the machines' names. Only the device list must@@ -8018,6 +8056,32 @@ open class Devices: Disposable, AutoCloseable, DevicesInterface}+ /**+ * Makes a one-time code (link, QR, install commands) that adds another+ * computer to the account, or to `team` (from this enrolled device).+ * It expires after `ttl_secs` (30 minutes when `None`).+ */+ @Throws(CuaException::class)+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")+ override suspend fun `createPairingCode`(`team`: kotlin.String?, `ttlSecs`: kotlin.ULong?) : PairingCode {+ return uniffiRustCallAsync(+ callWithHandle { uniffiHandle ->+ UniffiLib.uniffi_cua_sdk_fn_method_devices_create_pairing_code(+ uniffiHandle,+ FfiConverterOptionalString.lower(`team`),FfiConverterOptionalULong.lower(`ttlSecs`),+ )+ },+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },+ // lift function+ { FfiConverterTypePairingCode.lift(it) },+ // Error FFI converter+ CuaException.ErrorHandler,+ )+ }++/*** This device's id, when it has a key (no network).*/@@ -8062,6 +8126,30 @@ open class Devices: Disposable, AutoCloseable, DevicesInterface}+ /**+ * The account's pairing codes, newest first (without the codes).+ */+ @Throws(CuaException::class)+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")+ override suspend fun `pairingCodes`() : List<PairingCode> {+ return uniffiRustCallAsync(+ callWithHandle { uniffiHandle ->+ UniffiLib.uniffi_cua_sdk_fn_method_devices_pairing_codes(+ uniffiHandle,++ )+ },+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer(future, continuation) },+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer(future) },+ // lift function+ { FfiConverterSequenceTypePairingCode.lift(it) },+ // Error FFI converter+ CuaException.ErrorHandler,+ )+ }++/*** The relay base URL.*/override fun `relayUrl`(): kotlin.String {@@ -8127,6 +8215,31 @@ open class Devices: Disposable, AutoCloseable, DevicesInterface}+ /**+ * Revokes an unused pairing code (`pc_…`).+ */+ @Throws(CuaException::class)+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")+ override suspend fun `revokePairingCode`(`id`: kotlin.String) {+ return uniffiRustCallAsync(+ callWithHandle { uniffiHandle ->+ UniffiLib.uniffi_cua_sdk_fn_method_devices_revoke_pairing_code(+ uniffiHandle,+ FfiConverterString.lower(`id`),+ )+ },+ { future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_void(future, callback, continuation) },+ { future, continuation -> UniffiLib.ffi_cua_sdk_rust_future_complete_void(future, continuation) },+ { future -> UniffiLib.ffi_cua_sdk_rust_future_free_void(future) },+ // lift function+ { Unit },++ // Error FFI converter+ CuaException.ErrorHandler,+ )+ }++/*** The account's devices, the grace period, the newest `audit_limit`* audit events and the machines' names. Only the device list must@@ -31485,6 +31598,127 @@ public object FfiConverterTypeOverlayResult: FfiConverterRustBuffer<OverlayResul+/**+ * A one-time code that adds a machine to the account ("Add a machine"+ * by link or QR code).+ */+data class PairingCode (+ /**+ * `pc_…` (to revoke it).+ */+ var `id`: kotlin.String+ ,+ /**+ * `XXXX-XXXX-XXXX`: only when just made.+ */+ var `code`: kotlin.String?+ ,+ /**+ * `https://spaces.cua.ai/add/<code>` (the link and the QR code): only+ * when just made.+ */+ var `url`: kotlin.String?+ ,+ /**+ * `curl … | sh -s -- --pair <code>` (macOS, Linux): only when just made.+ */+ var `installSh`: kotlin.String?+ ,+ /**+ * The PowerShell one-liner (Windows): only when just made.+ */+ var `installPowershell`: kotlin.String?+ ,+ /**+ * `active`, `used`, `revoked` or `expired`.+ */+ var `state`: kotlin.String+ ,+ /**+ * Team the machine is added for.+ */+ var `team`: kotlin.String?+ ,+ /**+ * Unix seconds.+ */+ var `createdAt`: kotlin.ULong+ ,+ /**+ * Unix seconds.+ */+ var `expiresAt`: kotlin.ULong+ ,+ /**+ * When a machine used it.+ */+ var `usedAt`: kotlin.ULong?+ ,+ /**+ * The machine it added (relay machine id).+ */+ var `machine`: kotlin.String?++){++++++ companion object+}++/**+ * @suppress+ */+public object FfiConverterTypePairingCode: FfiConverterRustBuffer<PairingCode> {+ override fun read(buf: ByteBuffer): PairingCode {+ return PairingCode(+ FfiConverterString.read(buf),+ FfiConverterOptionalString.read(buf),+ FfiConverterOptionalString.read(buf),+ FfiConverterOptionalString.read(buf),+ FfiConverterOptionalString.read(buf),+ FfiConverterString.read(buf),+ FfiConverterOptionalString.read(buf),+ FfiConverterULong.read(buf),+ FfiConverterULong.read(buf),+ FfiConverterOptionalULong.read(buf),+ FfiConverterOptionalString.read(buf),+ )+ }++ override fun allocationSize(value: PairingCode) = (+ FfiConverterString.allocationSize(value.`id`) ++ FfiConverterOptionalString.allocationSize(value.`code`) ++ FfiConverterOptionalString.allocationSize(value.`url`) ++ FfiConverterOptionalString.allocationSize(value.`installSh`) ++ FfiConverterOptionalString.allocationSize(value.`installPowershell`) ++ FfiConverterString.allocationSize(value.`state`) ++ FfiConverterOptionalString.allocationSize(value.`team`) ++ FfiConverterULong.allocationSize(value.`createdAt`) ++ FfiConverterULong.allocationSize(value.`expiresAt`) ++ FfiConverterOptionalULong.allocationSize(value.`usedAt`) ++ FfiConverterOptionalString.allocationSize(value.`machine`)+ )++ override fun write(value: PairingCode, buf: ByteBuffer) {+ FfiConverterString.write(value.`id`, buf)+ FfiConverterOptionalString.write(value.`code`, buf)+ FfiConverterOptionalString.write(value.`url`, buf)+ FfiConverterOptionalString.write(value.`installSh`, buf)+ FfiConverterOptionalString.write(value.`installPowershell`, buf)+ FfiConverterString.write(value.`state`, buf)+ FfiConverterOptionalString.write(value.`team`, buf)+ FfiConverterULong.write(value.`createdAt`, buf)+ FfiConverterULong.write(value.`expiresAt`, buf)+ FfiConverterOptionalULong.write(value.`usedAt`, buf)+ FfiConverterOptionalString.write(value.`machine`, buf)+ }+}+++/*** A persistent agent: a named harness whose memory (its home in the Cua* Drive) outlives its runs and its Space.@@ -42762,6 +42996,34 @@ public object FfiConverterSequenceTypeOverlayResult: FfiConverterRustBuffer<List+/**+ * @suppress+ */+public object FfiConverterSequenceTypePairingCode: FfiConverterRustBuffer<List<PairingCode>> {+ override fun read(buf: ByteBuffer): List<PairingCode> {+ val len = buf.getInt()+ return List<PairingCode>(len) {+ FfiConverterTypePairingCode.read(buf)+ }+ }++ override fun allocationSize(value: List<PairingCode>): ULong {+ val sizeForLength = 4UL+ val sizeForItems = value.map { FfiConverterTypePairingCode.allocationSize(it) }.sum()+ return sizeForLength + sizeForItems+ }++ override fun write(value: List<PairingCode>, buf: ByteBuffer) {+ buf.putInt(value.size)+ value.iterator().forEach {+ FfiConverterTypePairingCode.write(it, buf)+ }+ }+}++++/*** @suppress*/diff --git a/libs/cua/python/src/cua/_native.py b/libs/cua/python/src/cua/_native.pyindex d7360f5a8b..49216db555 100644--- a/libs/cua/python/src/cua/_native.py+++ b/libs/cua/python/src/cua/_native.py@@ -697,16 +697,22 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_devices_confirm_machine() != 44995:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_sdk_checksum_method_devices_create_pairing_code() != 19274:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_devices_device_id() != 58064:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_devices_enroll() != 25682:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_sdk_checksum_method_devices_pairing_codes() != 10069:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_devices_relay_url() != 39774:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_devices_rename() != 59535:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_devices_revoke() != 27802:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code() != 3143:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_devices_snapshot() != 26132:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_fleet_acquire() != 16535:@@ -2567,6 +2573,12 @@ _UniffiLib.uniffi_cua_sdk_fn_method_devices_confirm_machine.argtypes = (_UniffiRustBuffer,)_UniffiLib.uniffi_cua_sdk_fn_method_devices_confirm_machine.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_sdk_fn_method_devices_create_pairing_code.argtypes = (+ ctypes.c_uint64,+ _UniffiRustBuffer,+ _UniffiRustBuffer,+)+_UniffiLib.uniffi_cua_sdk_fn_method_devices_create_pairing_code.restype = ctypes.c_uint64_UniffiLib.uniffi_cua_sdk_fn_method_devices_device_id.argtypes = (ctypes.c_uint64,ctypes.POINTER(_UniffiRustCallStatus),@@ -2576,6 +2588,10 @@ _UniffiLib.uniffi_cua_sdk_fn_method_devices_enroll.argtypes = (ctypes.c_uint64,)_UniffiLib.uniffi_cua_sdk_fn_method_devices_enroll.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_sdk_fn_method_devices_pairing_codes.argtypes = (+ ctypes.c_uint64,+)+_UniffiLib.uniffi_cua_sdk_fn_method_devices_pairing_codes.restype = ctypes.c_uint64_UniffiLib.uniffi_cua_sdk_fn_method_devices_relay_url.argtypes = (ctypes.c_uint64,ctypes.POINTER(_UniffiRustCallStatus),@@ -2592,6 +2608,11 @@ _UniffiLib.uniffi_cua_sdk_fn_method_devices_revoke.argtypes = (_UniffiRustBuffer,)_UniffiLib.uniffi_cua_sdk_fn_method_devices_revoke.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_sdk_fn_method_devices_revoke_pairing_code.argtypes = (+ ctypes.c_uint64,+ _UniffiRustBuffer,+)+_UniffiLib.uniffi_cua_sdk_fn_method_devices_revoke_pairing_code.restype = ctypes.c_uint64_UniffiLib.uniffi_cua_sdk_fn_method_devices_snapshot.argtypes = (ctypes.c_uint64,ctypes.c_uint32,@@ -4668,12 +4689,18 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_devices_check_enrolled.restype = ctype_UniffiLib.uniffi_cua_sdk_checksum_method_devices_confirm_machine.argtypes = ()_UniffiLib.uniffi_cua_sdk_checksum_method_devices_confirm_machine.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_create_pairing_code.argtypes = (+)+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_create_pairing_code.restype = ctypes.c_uint16_UniffiLib.uniffi_cua_sdk_checksum_method_devices_device_id.argtypes = ()_UniffiLib.uniffi_cua_sdk_checksum_method_devices_device_id.restype = ctypes.c_uint16_UniffiLib.uniffi_cua_sdk_checksum_method_devices_enroll.argtypes = ()_UniffiLib.uniffi_cua_sdk_checksum_method_devices_enroll.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_pairing_codes.argtypes = (+)+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_pairing_codes.restype = ctypes.c_uint16_UniffiLib.uniffi_cua_sdk_checksum_method_devices_relay_url.argtypes = ()_UniffiLib.uniffi_cua_sdk_checksum_method_devices_relay_url.restype = ctypes.c_uint16@@ -4683,6 +4710,9 @@ _UniffiLib.uniffi_cua_sdk_checksum_method_devices_rename.restype = ctypes.c_uint_UniffiLib.uniffi_cua_sdk_checksum_method_devices_revoke.argtypes = ()_UniffiLib.uniffi_cua_sdk_checksum_method_devices_revoke.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code.argtypes = (+)+_UniffiLib.uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code.restype = ctypes.c_uint16_UniffiLib.uniffi_cua_sdk_checksum_method_devices_snapshot.argtypes = ()_UniffiLib.uniffi_cua_sdk_checksum_method_devices_snapshot.restype = ctypes.c_uint16@@ -15773,6 +15803,100 @@ class _UniffiFfiConverterTypeOverlayResult(_UniffiConverterRustBuffer):_UniffiFfiConverterUInt64.write(value.size, buf)_UniffiFfiConverterString.write(value.restarted, buf)+@dataclass+class PairingCode:+ """+ A one-time code that adds a machine to the account ("Add a machine"+ by link or QR code).+"""+ def __init__(self, *, id:str, code:typing.Optional[str], url:typing.Optional[str], install_sh:typing.Optional[str], install_powershell:typing.Optional[str], state:str, team:typing.Optional[str], created_at:int, expires_at:int, used_at:typing.Optional[int], machine:typing.Optional[str]):+ self.id = id+ self.code = code+ self.url = url+ self.install_sh = install_sh+ self.install_powershell = install_powershell+ self.state = state+ self.team = team+ self.created_at = created_at+ self.expires_at = expires_at+ self.used_at = used_at+ self.machine = machine+++++ def __str__(self):+ return "PairingCode(id={}, code={}, url={}, install_sh={}, install_powershell={}, state={}, team={}, created_at={}, expires_at={}, used_at={}, machine={})".format(self.id, self.code, self.url, self.install_sh, self.install_powershell, self.state, self.team, self.created_at, self.expires_at, self.used_at, self.machine)+ def __eq__(self, other):+ if self.id != other.id:+ return False+ if self.code != other.code:+ return False+ if self.url != other.url:+ return False+ if self.install_sh != other.install_sh:+ return False+ if self.install_powershell != other.install_powershell:+ return False+ if self.state != other.state:+ return False+ if self.team != other.team:+ return False+ if self.created_at != other.created_at:+ return False+ if self.expires_at != other.expires_at:+ return False+ if self.used_at != other.used_at:+ return False+ if self.machine != other.machine:+ return False+ return True++class _UniffiFfiConverterTypePairingCode(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return PairingCode(+ id=_UniffiFfiConverterString.read(buf),+ code=_UniffiFfiConverterOptionalString.read(buf),+ url=_UniffiFfiConverterOptionalString.read(buf),+ install_sh=_UniffiFfiConverterOptionalString.read(buf),+ install_powershell=_UniffiFfiConverterOptionalString.read(buf),+ state=_UniffiFfiConverterString.read(buf),+ team=_UniffiFfiConverterOptionalString.read(buf),+ created_at=_UniffiFfiConverterUInt64.read(buf),+ expires_at=_UniffiFfiConverterUInt64.read(buf),+ used_at=_UniffiFfiConverterOptionalUInt64.read(buf),+ machine=_UniffiFfiConverterOptionalString.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterString.check_lower(value.id)+ _UniffiFfiConverterOptionalString.check_lower(value.code)+ _UniffiFfiConverterOptionalString.check_lower(value.url)+ _UniffiFfiConverterOptionalString.check_lower(value.install_sh)+ _UniffiFfiConverterOptionalString.check_lower(value.install_powershell)+ _UniffiFfiConverterString.check_lower(value.state)+ _UniffiFfiConverterOptionalString.check_lower(value.team)+ _UniffiFfiConverterUInt64.check_lower(value.created_at)+ _UniffiFfiConverterUInt64.check_lower(value.expires_at)+ _UniffiFfiConverterOptionalUInt64.check_lower(value.used_at)+ _UniffiFfiConverterOptionalString.check_lower(value.machine)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterString.write(value.id, buf)+ _UniffiFfiConverterOptionalString.write(value.code, buf)+ _UniffiFfiConverterOptionalString.write(value.url, buf)+ _UniffiFfiConverterOptionalString.write(value.install_sh, buf)+ _UniffiFfiConverterOptionalString.write(value.install_powershell, buf)+ _UniffiFfiConverterString.write(value.state, buf)+ _UniffiFfiConverterOptionalString.write(value.team, buf)+ _UniffiFfiConverterUInt64.write(value.created_at, buf)+ _UniffiFfiConverterUInt64.write(value.expires_at, buf)+ _UniffiFfiConverterOptionalUInt64.write(value.used_at, buf)+ _UniffiFfiConverterOptionalString.write(value.machine, buf)+@dataclassclass PersistentAgentInfo:"""@@ -24180,6 +24304,29 @@ class _UniffiFfiConverterTypeLoginAttempt:def write(cls, value: LoginAttempt, buf: _UniffiRustBuffer):buf.write_u64(cls.lower(value))+class _UniffiFfiConverterSequenceTypePairingCode(_UniffiConverterRustBuffer):+ @classmethod+ def check_lower(cls, value):+ for item in value:+ _UniffiFfiConverterTypePairingCode.check_lower(item)++ @classmethod+ def write(cls, value, buf):+ items = len(value)+ buf.write_i32(items)+ for item in value:+ _UniffiFfiConverterTypePairingCode.write(item, buf)++ @classmethod+ def read(cls, buf):+ count = buf.read_i32()+ if count < 0:+ raise InternalError("Unexpected negative sequence length")++ return [+ _UniffiFfiConverterTypePairingCode.read(buf) for i in range(count)+ ]+class DevicesProtocol(typing.Protocol):"""@@ -24207,6 +24354,13 @@ class DevicesProtocol(typing.Protocol):enrolled device's signature or MFA (from this enrolled device) (S5).Clears [`RelayMachine::confirmed`]'s "new" flag for every accountmember, not just this device.+"""+ raise NotImplementedError+ async def create_pairing_code(self, team: typing.Optional[str],ttl_secs: typing.Optional[int]) -> PairingCode:+ """+ Makes a one-time code (link, QR, install commands) that adds another+ computer to the account, or to `team` (from this enrolled device).+ It expires after `ttl_secs` (30 minutes when `None`)."""raise NotImplementedErrordef device_id(self, ) -> typing.Optional[str]:@@ -24220,6 +24374,11 @@ class DevicesProtocol(typing.Protocol):a fresh sign-in it is enrolled at once (replacing this machine'solder device key, if any); otherwise the result carries a one-timecode to approve from an enrolled device.+"""+ raise NotImplementedError+ async def pairing_codes(self, ) -> typing.List[PairingCode]:+ """+ The account's pairing codes, newest first (without the codes)."""raise NotImplementedErrordef relay_url(self, ) -> str:@@ -24236,6 +24395,11 @@ class DevicesProtocol(typing.Protocol):"""Revokes a device (from this enrolled device). Revoking this devicealso deletes its key.+"""+ raise NotImplementedError+ async def revoke_pairing_code(self, id: str) -> None:+ """+ Revokes an unused pairing code (`pc_…`)."""raise NotImplementedErrorasync def snapshot(self, audit_limit: int) -> DevicesSnapshot:@@ -24348,6 +24512,31 @@ class Devices(DevicesProtocol):_uniffi_lift_return,_uniffi_error_converter,)+ async def create_pairing_code(self, team: typing.Optional[str],ttl_secs: typing.Optional[int]) -> PairingCode:+ """+ Makes a one-time code (link, QR, install commands) that adds another+ computer to the account, or to `team` (from this enrolled device).+ It expires after `ttl_secs` (30 minutes when `None`).+"""++ _UniffiFfiConverterOptionalString.check_lower(team)++ _UniffiFfiConverterOptionalUInt64.check_lower(ttl_secs)+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ _UniffiFfiConverterOptionalString.lower(team),+ _UniffiFfiConverterOptionalUInt64.lower(ttl_secs),+ )+ _uniffi_lift_return = _UniffiFfiConverterTypePairingCode.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError+ return await _uniffi_rust_call_async(+ _UniffiLib.uniffi_cua_sdk_fn_method_devices_create_pairing_code(*_uniffi_lowered_args),+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,+ _uniffi_lift_return,+ _uniffi_error_converter,+ )def device_id(self, ) -> typing.Optional[str]:"""This device's id, when it has a key (no network).@@ -24383,6 +24572,23 @@ class Devices(DevicesProtocol):_uniffi_lift_return,_uniffi_error_converter,)+ async def pairing_codes(self, ) -> typing.List[PairingCode]:+ """+ The account's pairing codes, newest first (without the codes).+"""+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ )+ _uniffi_lift_return = _UniffiFfiConverterSequenceTypePairingCode.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError+ return await _uniffi_rust_call_async(+ _UniffiLib.uniffi_cua_sdk_fn_method_devices_pairing_codes(*_uniffi_lowered_args),+ _UniffiLib.ffi_cua_sdk_rust_future_poll_rust_buffer,+ _UniffiLib.ffi_cua_sdk_rust_future_complete_rust_buffer,+ _UniffiLib.ffi_cua_sdk_rust_future_free_rust_buffer,+ _uniffi_lift_return,+ _uniffi_error_converter,+ )def relay_url(self, ) -> str:"""The relay base URL.@@ -24442,6 +24648,26 @@ class Devices(DevicesProtocol):_uniffi_lift_return,_uniffi_error_converter,)+ async def revoke_pairing_code(self, id: str) -> None:+ """+ Revokes an unused pairing code (`pc_…`).+"""++ _UniffiFfiConverterString.check_lower(id)+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ _UniffiFfiConverterString.lower(id),+ )+ _uniffi_lift_return = lambda val: None+ _uniffi_error_converter = _UniffiFfiConverterTypeCuaError+ return await _uniffi_rust_call_async(+ _UniffiLib.uniffi_cua_sdk_fn_method_devices_revoke_pairing_code(*_uniffi_lowered_args),+ _UniffiLib.ffi_cua_sdk_rust_future_poll_void,+ _UniffiLib.ffi_cua_sdk_rust_future_complete_void,+ _UniffiLib.ffi_cua_sdk_rust_future_free_void,+ _uniffi_lift_return,+ _uniffi_error_converter,+ )async def snapshot(self, audit_limit: int) -> DevicesSnapshot:"""The account's devices, the grace period, the newest `audit_limit`@@ -37667,6 +37893,7 @@ __all__ = ["NotificationInfo","Overlay","OverlayResult",+ "PairingCode","PersistentAgentInfo","PersistentAgentOptions","Point",diff --git a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swiftindex f468c50614..744a1ab67d 100644--- a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift+++ b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift@@ -2613,6 +2613,13 @@ public protocol DevicesProtocol: AnyObject, Sendable {*/func confirmMachine(machineId: String) async throws -> RelayMachine+ /**+ * Makes a one-time code (link, QR, install commands) that adds another+ * computer to the account, or to `team` (from this enrolled device).+ * It expires after `ttl_secs` (30 minutes when `None`).+ */+ func createPairingCode(team: String?, ttlSecs: UInt64?) async throws -> PairingCode+/*** This device's id, when it has a key (no network).*/@@ -2626,6 +2633,11 @@ public protocol DevicesProtocol: AnyObject, Sendable {*/func enroll() async throws -> DeviceEnrollment+ /**+ * The account's pairing codes, newest first (without the codes).+ */+ func pairingCodes() async throws -> [PairingCode]+/*** The relay base URL.*/@@ -2642,6 +2654,11 @@ public protocol DevicesProtocol: AnyObject, Sendable {*/func revoke(id: String) async throws -> RelayDevice+ /**+ * Revokes an unused pairing code (`pc_…`).+ */+ func revokePairingCode(id: String) async throws+/*** The account's devices, the grace period, the newest `audit_limit`* audit events and the machines' names. Only the device list must@@ -2775,6 +2792,28 @@ open func confirmMachine(machineId: String)async throws -> RelayMachine {)}+ /**+ * Makes a one-time code (link, QR, install commands) that adds another+ * computer to the account, or to `team` (from this enrolled device).+ * It expires after `ttl_secs` (30 minutes when `None`).+ */+open func createPairingCode(team: String?, ttlSecs: UInt64?)async throws -> PairingCode {+ return+ try await uniffiRustCallAsync(+ rustFutureFunc: {+ uniffi_cua_sdk_fn_method_devices_create_pairing_code(+ self.uniffiCloneHandle(),+ FfiConverterOptionString.lower(team),FfiConverterOptionUInt64.lower(ttlSecs)+ )+ },+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,+ liftFunc: FfiConverterTypePairingCode_lift,+ errorHandler: FfiConverterTypeCuaError_lift+ )+}+/*** This device's id, when it has a key (no network).*/@@ -2809,6 +2848,26 @@ open func enroll()async throws -> DeviceEnrollment {)}+ /**+ * The account's pairing codes, newest first (without the codes).+ */+open func pairingCodes()async throws -> [PairingCode] {+ return+ try await uniffiRustCallAsync(+ rustFutureFunc: {+ uniffi_cua_sdk_fn_method_devices_pairing_codes(+ self.uniffiCloneHandle()++ )+ },+ pollFunc: ffi_cua_sdk_rust_future_poll_rust_buffer,+ completeFunc: ffi_cua_sdk_rust_future_complete_rust_buffer,+ freeFunc: ffi_cua_sdk_rust_future_free_rust_buffer,+ liftFunc: FfiConverterSequenceTypePairingCode.lift,+ errorHandler: FfiConverterTypeCuaError_lift+ )+}+/*** The relay base URL.*/@@ -2861,6 +2920,26 @@ open func revoke(id: String)async throws -> RelayDevice {)}+ /**+ * Revokes an unused pairing code (`pc_…`).+ */+open func revokePairingCode(id: String)async throws {+ return+ try await uniffiRustCallAsync(+ rustFutureFunc: {+ uniffi_cua_sdk_fn_method_devices_revoke_pairing_code(+ self.uniffiCloneHandle(),+ FfiConverterString.lower(id)+ )+ },+ pollFunc: ffi_cua_sdk_rust_future_poll_void,+ completeFunc: ffi_cua_sdk_rust_future_complete_void,+ freeFunc: ffi_cua_sdk_rust_future_free_void,+ liftFunc: { $0 },+ errorHandler: FfiConverterTypeCuaError_lift+ )+}+/*** The account's devices, the grace period, the newest `audit_limit`* audit events and the machines' names. Only the device list must@@ -24659,6 +24738,168 @@ public func FfiConverterTypeOverlayResult_lower(_ value: OverlayResult) -> RustB}+/**+ * A one-time code that adds a machine to the account ("Add a machine"+ * by link or QR code).+ */+public struct PairingCode: Equatable, Hashable {+ /**+ * `pc_…` (to revoke it).+ */+ public var id: String+ /**+ * `XXXX-XXXX-XXXX`: only when just made.+ */+ public var code: String?+ /**+ * `https://spaces.cua.ai/add/<code>` (the link and the QR code): only+ * when just made.+ */+ public var url: String?+ /**+ * `curl … | sh -s -- --pair <code>` (macOS, Linux): only when just made.+ */+ public var installSh: String?+ /**+ * The PowerShell one-liner (Windows): only when just made.+ */+ public var installPowershell: String?+ /**+ * `active`, `used`, `revoked` or `expired`.+ */+ public var state: String+ /**+ * Team the machine is added for.+ */+ public var team: String?+ /**+ * Unix seconds.+ */+ public var createdAt: UInt64+ /**+ * Unix seconds.+ */+ public var expiresAt: UInt64+ /**+ * When a machine used it.+ */+ public var usedAt: UInt64?+ /**+ * The machine it added (relay machine id).+ */+ public var machine: String?++ // Default memberwise initializers are never public by default, so we+ // declare one manually.+ public init(+ /**+ * `pc_…` (to revoke it).+ */id: String,+ /**+ * `XXXX-XXXX-XXXX`: only when just made.+ */code: String?,+ /**+ * `https://spaces.cua.ai/add/<code>` (the link and the QR code): only+ * when just made.+ */url: String?,+ /**+ * `curl … | sh -s -- --pair <code>` (macOS, Linux): only when just made.+ */installSh: String?,+ /**+ * The PowerShell one-liner (Windows): only when just made.+ */installPowershell: String?,+ /**+ * `active`, `used`, `revoked` or `expired`.+ */state: String,+ /**+ * Team the machine is added for.+ */team: String?,+ /**+ * Unix seconds.+ */createdAt: UInt64,+ /**+ * Unix seconds.+ */expiresAt: UInt64,+ /**+ * When a machine used it.+ */usedAt: UInt64?,+ /**+ * The machine it added (relay machine id).+ */machine: String?) {+ self.id = id+ self.code = code+ self.url = url+ self.installSh = installSh+ self.installPowershell = installPowershell+ self.state = state+ self.team = team+ self.createdAt = createdAt+ self.expiresAt = expiresAt+ self.usedAt = usedAt+ self.machine = machine+ }+++++}++#if compiler(>=6)+extension PairingCode: Sendable {}+#endif++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public struct FfiConverterTypePairingCode: FfiConverterRustBuffer {+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PairingCode {+ return+ try PairingCode(+ id: FfiConverterString.read(from: &buf),+ code: FfiConverterOptionString.read(from: &buf),+ url: FfiConverterOptionString.read(from: &buf),+ installSh: FfiConverterOptionString.read(from: &buf),+ installPowershell: FfiConverterOptionString.read(from: &buf),+ state: FfiConverterString.read(from: &buf),+ team: FfiConverterOptionString.read(from: &buf),+ createdAt: FfiConverterUInt64.read(from: &buf),+ expiresAt: FfiConverterUInt64.read(from: &buf),+ usedAt: FfiConverterOptionUInt64.read(from: &buf),+ machine: FfiConverterOptionString.read(from: &buf)+ )+ }++ public static func write(_ value: PairingCode, into buf: inout [UInt8]) {+ FfiConverterString.write(value.id, into: &buf)+ FfiConverterOptionString.write(value.code, into: &buf)+ FfiConverterOptionString.write(value.url, into: &buf)+ FfiConverterOptionString.write(value.installSh, into: &buf)+ FfiConverterOptionString.write(value.installPowershell, into: &buf)+ FfiConverterString.write(value.state, into: &buf)+ FfiConverterOptionString.write(value.team, into: &buf)+ FfiConverterUInt64.write(value.createdAt, into: &buf)+ FfiConverterUInt64.write(value.expiresAt, into: &buf)+ FfiConverterOptionUInt64.write(value.usedAt, into: &buf)+ FfiConverterOptionString.write(value.machine, into: &buf)+ }+}+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypePairingCode_lift(_ buf: RustBuffer) throws -> PairingCode {+ return try FfiConverterTypePairingCode.lift(buf)+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypePairingCode_lower(_ value: PairingCode) -> RustBuffer {+ return FfiConverterTypePairingCode.lower(value)+}++/*** A persistent agent: a named harness whose memory (its home in the Cua* Drive) outlives its runs and its Space.@@ -38382,6 +38623,31 @@ fileprivate struct FfiConverterSequenceTypeOverlayResult: FfiConverterRustBuffer}}+#if swift(>=5.8)+@_documentation(visibility: private)+#endif+fileprivate struct FfiConverterSequenceTypePairingCode: FfiConverterRustBuffer {+ typealias SwiftType = [PairingCode]++ public static func write(_ value: [PairingCode], into buf: inout [UInt8]) {+ let len = Int32(value.count)+ writeInt(&buf, len)+ for item in value {+ FfiConverterTypePairingCode.write(item, into: &buf)+ }+ }++ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [PairingCode] {+ let len: Int32 = try readInt(&buf)+ var seq = [PairingCode]()+ seq.reserveCapacity(Int(len))+ for _ in 0 ..< len {+ seq.append(try FfiConverterTypePairingCode.read(from: &buf))+ }+ return seq+ }+}+#if swift(>=5.8)@_documentation(visibility: private)#endif@@ -40286,12 +40552,18 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_sdk_checksum_method_devices_confirm_machine() != 44995) {return InitializationResult.apiChecksumMismatch}+ if (uniffi_cua_sdk_checksum_method_devices_create_pairing_code() != 19274) {+ return InitializationResult.apiChecksumMismatch+ }if (uniffi_cua_sdk_checksum_method_devices_device_id() != 58064) {return InitializationResult.apiChecksumMismatch}if (uniffi_cua_sdk_checksum_method_devices_enroll() != 25682) {return InitializationResult.apiChecksumMismatch}+ if (uniffi_cua_sdk_checksum_method_devices_pairing_codes() != 10069) {+ return InitializationResult.apiChecksumMismatch+ }if (uniffi_cua_sdk_checksum_method_devices_relay_url() != 39774) {return InitializationResult.apiChecksumMismatch}@@ -40301,6 +40573,9 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_sdk_checksum_method_devices_revoke() != 27802) {return InitializationResult.apiChecksumMismatch}+ if (uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code() != 3143) {+ return InitializationResult.apiChecksumMismatch+ }if (uniffi_cua_sdk_checksum_method_devices_snapshot() != 26132) {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 8d28bb2382..b97b9af4b2 100644--- a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h+++ b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h@@ -881,6 +881,11 @@ uint64_t uniffi_cua_sdk_fn_method_devices_check_enrolled(uint64_t ptruint64_t uniffi_cua_sdk_fn_method_devices_confirm_machine(uint64_t ptr, RustBuffer machine_id);#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_CREATE_PAIRING_CODE+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_CREATE_PAIRING_CODE+uint64_t uniffi_cua_sdk_fn_method_devices_create_pairing_code(uint64_t ptr, RustBuffer team, RustBuffer ttl_secs+);+#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_DEVICE_ID#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_DEVICE_IDRustBuffer uniffi_cua_sdk_fn_method_devices_device_id(uint64_t ptr, RustCallStatus *_Nonnull out_status@@ -891,6 +896,11 @@ RustBuffer uniffi_cua_sdk_fn_method_devices_device_id(uint64_t ptr, RustCallStatuint64_t uniffi_cua_sdk_fn_method_devices_enroll(uint64_t ptr);#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_PAIRING_CODES+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_PAIRING_CODES+uint64_t uniffi_cua_sdk_fn_method_devices_pairing_codes(uint64_t ptr+);+#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_RELAY_URL#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_RELAY_URLRustBuffer uniffi_cua_sdk_fn_method_devices_relay_url(uint64_t ptr, RustCallStatus *_Nonnull out_status@@ -906,6 +916,11 @@ uint64_t uniffi_cua_sdk_fn_method_devices_rename(uint64_t ptr, RustBuffer id, Ruuint64_t uniffi_cua_sdk_fn_method_devices_revoke(uint64_t ptr, RustBuffer id);#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_REVOKE_PAIRING_CODE+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_REVOKE_PAIRING_CODE+uint64_t uniffi_cua_sdk_fn_method_devices_revoke_pairing_code(uint64_t ptr, RustBuffer id+);+#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_SNAPSHOT#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_DEVICES_SNAPSHOTuint64_t uniffi_cua_sdk_fn_method_devices_snapshot(uint64_t ptr, uint32_t audit_limit@@ -3986,6 +4001,12 @@ uint16_t uniffi_cua_sdk_checksum_method_devices_check_enrolled(void#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_CONFIRM_MACHINEuint16_t uniffi_cua_sdk_checksum_method_devices_confirm_machine(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_CREATE_PAIRING_CODE+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_CREATE_PAIRING_CODE+uint16_t uniffi_cua_sdk_checksum_method_devices_create_pairing_code(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_DEVICE_ID@@ -3998,6 +4019,12 @@ uint16_t uniffi_cua_sdk_checksum_method_devices_device_id(void#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_ENROLLuint16_t uniffi_cua_sdk_checksum_method_devices_enroll(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_PAIRING_CODES+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_PAIRING_CODES+uint16_t uniffi_cua_sdk_checksum_method_devices_pairing_codes(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_RELAY_URL@@ -4016,6 +4043,12 @@ uint16_t uniffi_cua_sdk_checksum_method_devices_rename(void#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_REVOKEuint16_t uniffi_cua_sdk_checksum_method_devices_revoke(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_REVOKE_PAIRING_CODE+#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_REVOKE_PAIRING_CODE+uint16_t uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_CHECKSUM_METHOD_DEVICES_SNAPSHOTdiff --git a/libs/cua/typescript/src/native/cua_sdk-ffi.ts b/libs/cua/typescript/src/native/cua_sdk-ffi.tsindex 75d7936d33..a1836b6cb8 100644--- a/libs/cua/typescript/src/native/cua_sdk-ffi.ts+++ b/libs/cua/typescript/src/native/cua_sdk-ffi.ts@@ -1138,6 +1138,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_sdk_fn_method_devices_create_pairing_code": {+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_fn_method_devices_device_id": {args: [FfiType.Handle],ret: FfiType.RustBuffer,@@ -1148,6 +1153,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_sdk_fn_method_devices_pairing_codes": {+ args: [FfiType.Handle],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_fn_method_devices_relay_url": {args: [FfiType.Handle],ret: FfiType.RustBuffer,@@ -1163,6 +1173,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_sdk_fn_method_devices_revoke_pairing_code": {+ args: [FfiType.Handle, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_fn_method_devices_snapshot": {args: [FfiType.Handle, FfiType.UInt32],ret: FfiType.Handle,@@ -3353,6 +3368,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_sdk_checksum_method_devices_create_pairing_code": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_checksum_method_devices_device_id": {args: [],ret: FfiType.UInt16,@@ -3363,6 +3383,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_sdk_checksum_method_devices_pairing_codes": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_checksum_method_devices_relay_url": {args: [],ret: FfiType.UInt16,@@ -3378,6 +3403,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_sdk_checksum_method_devices_snapshot": {args: [],ret: FfiType.UInt16,@@ -5354,11 +5384,14 @@ interface NativeModuleInterface {uniffi_cua_sdk_fn_method_devices_approve(uniffiSelf: bigint, code: Uint8Array, deviceId: Uint8Array): bigint;uniffi_cua_sdk_fn_method_devices_check_enrolled(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_devices_confirm_machine(uniffiSelf: bigint, machineId: Uint8Array): bigint;+ uniffi_cua_sdk_fn_method_devices_create_pairing_code(uniffiSelf: bigint, team: Uint8Array, ttlSecs: Uint8Array): bigint;uniffi_cua_sdk_fn_method_devices_device_id(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_method_devices_enroll(uniffiSelf: bigint): bigint;+ uniffi_cua_sdk_fn_method_devices_pairing_codes(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_devices_relay_url(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_method_devices_rename(uniffiSelf: bigint, id: Uint8Array, name: Uint8Array): bigint;uniffi_cua_sdk_fn_method_devices_revoke(uniffiSelf: bigint, id: Uint8Array): bigint;+ uniffi_cua_sdk_fn_method_devices_revoke_pairing_code(uniffiSelf: bigint, id: Uint8Array): bigint;uniffi_cua_sdk_fn_method_devices_snapshot(uniffiSelf: bigint, auditLimit: number): bigint;uniffi_cua_sdk_fn_method_fleet_acquire(uniffiSelf: bigint, pool: Uint8Array, name: Uint8Array, ttlSeconds: Uint8Array): bigint;uniffi_cua_sdk_fn_method_fleet_acquire_with(uniffiSelf: bigint, pool: Uint8Array, options: Uint8Array): bigint;@@ -5797,11 +5830,14 @@ interface NativeModuleInterface {uniffi_cua_sdk_checksum_method_devices_approve(): number;uniffi_cua_sdk_checksum_method_devices_check_enrolled(): number;uniffi_cua_sdk_checksum_method_devices_confirm_machine(): number;+ uniffi_cua_sdk_checksum_method_devices_create_pairing_code(): number;uniffi_cua_sdk_checksum_method_devices_device_id(): number;uniffi_cua_sdk_checksum_method_devices_enroll(): number;+ uniffi_cua_sdk_checksum_method_devices_pairing_codes(): number;uniffi_cua_sdk_checksum_method_devices_relay_url(): number;uniffi_cua_sdk_checksum_method_devices_rename(): number;uniffi_cua_sdk_checksum_method_devices_revoke(): number;+ uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code(): number;uniffi_cua_sdk_checksum_method_devices_snapshot(): number;uniffi_cua_sdk_checksum_method_fleet_acquire(): number;uniffi_cua_sdk_checksum_method_fleet_acquire_with(): number;diff --git a/libs/cua/typescript/src/native/cua_sdk.ts b/libs/cua/typescript/src/native/cua_sdk.tsindex eccde2a89c..60404cdf56 100644--- a/libs/cua/typescript/src/native/cua_sdk.ts+++ b/libs/cua/typescript/src/native/cua_sdk.ts@@ -10983,6 +10983,123 @@ const FfiConverterTypeOverlayResult = (() => {return new FFIConverter();})();+/**+ * A one-time code that adds a machine to the account ("Add a machine"+ * by link or QR code).+ */+export type PairingCode = {+ /**+ * `pc_…` (to revoke it).+ */+ id: string,+ /**+ * `XXXX-XXXX-XXXX`: only when just made.+ */+ code?: string,+ /**+ * `https://spaces.cua.ai/add/<code>` (the link and the QR code): only+ * when just made.+ */+ url?: string,+ /**+ * `curl … | sh -s -- --pair <code>` (macOS, Linux): only when just made.+ */+ installSh?: string,+ /**+ * The PowerShell one-liner (Windows): only when just made.+ */+ installPowershell?: string,+ /**+ * `active`, `used`, `revoked` or `expired`.+ */+ state: string,+ /**+ * Team the machine is added for.+ */+ team?: string,+ /**+ * Unix seconds.+ */+ createdAt: bigint,+ /**+ * Unix seconds.+ */+ expiresAt: bigint,+ /**+ * When a machine used it.+ */+ usedAt?: bigint,+ /**+ * The machine it added (relay machine id).+ */+ machine?: string+}++/**+ * Generated factory for {@link PairingCode} record objects.+ */+export const PairingCode = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<PairingCode, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<PairingCode>,+ });+})();++const FfiConverterTypePairingCode = (() => {+ type TypeName = PairingCode;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ id: FfiConverterString.read(from),+ code: FfiConverterOptionalString.read(from),+ url: FfiConverterOptionalString.read(from),+ installSh: FfiConverterOptionalString.read(from),+ installPowershell: FfiConverterOptionalString.read(from),+ state: FfiConverterString.read(from),+ team: FfiConverterOptionalString.read(from),+ createdAt: FfiConverterUInt64.read(from),+ expiresAt: FfiConverterUInt64.read(from),+ usedAt: FfiConverterOptionalUInt64.read(from),+ machine: FfiConverterOptionalString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.id, into);+ FfiConverterOptionalString.write(value.code, into);+ FfiConverterOptionalString.write(value.url, into);+ FfiConverterOptionalString.write(value.installSh, into);+ FfiConverterOptionalString.write(value.installPowershell, into);+ FfiConverterString.write(value.state, into);+ FfiConverterOptionalString.write(value.team, into);+ FfiConverterUInt64.write(value.createdAt, into);+ FfiConverterUInt64.write(value.expiresAt, into);+ FfiConverterOptionalUInt64.write(value.usedAt, into);+ FfiConverterOptionalString.write(value.machine, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.id) ++ FfiConverterOptionalString.allocationSize(value.code) ++ FfiConverterOptionalString.allocationSize(value.url) ++ FfiConverterOptionalString.allocationSize(value.installSh) ++ FfiConverterOptionalString.allocationSize(value.installPowershell) ++ FfiConverterString.allocationSize(value.state) ++ FfiConverterOptionalString.allocationSize(value.team) ++ FfiConverterUInt64.allocationSize(value.createdAt) ++ FfiConverterUInt64.allocationSize(value.expiresAt) ++ FfiConverterOptionalUInt64.allocationSize(value.usedAt) ++ FfiConverterOptionalString.allocationSize(value.machine);++ }+ };+ return new FFIConverter();+})();+/*** A persistent agent: a named harness whose memory (its home in the Cua* Drive) outlives its runs and its Space.@@ -20872,6 +20989,12 @@ export interface DevicesLike {* member, not just this device.*/confirmMachine(machineId: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<RelayMachine>;+/**+ * Makes a one-time code (link, QR, install commands) that adds another+ * computer to the account, or to `team` (from this enrolled device).+ * It expires after `ttl_secs` (30 minutes when `None`).+ */+ createPairingCode(team: string | undefined, ttlSecs: bigint | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<PairingCode>;/*** This device's id, when it has a key (no network).*/@@ -20883,6 +21006,10 @@ export interface DevicesLike {* code to approve from an enrolled device.*/enroll(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<DeviceEnrollment>;+/**+ * The account's pairing codes, newest first (without the codes).+ */+ pairingCodes(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<PairingCode>>;/*** The relay base URL.*/@@ -20896,6 +21023,10 @@ export interface DevicesLike {* also deletes its key.*/revoke(id: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<RelayDevice>;+/**+ * Revokes an unused pairing code (`pc_…`).+ */+ revokePairingCode(id: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;/*** The account's devices, the grace period, the newest `audit_limit`* audit events and the machines' names. Only the device list must@@ -21040,6 +21171,43 @@ private constructor(pointer: UniffiHandle) {}}+/**+ * Makes a one-time code (link, QR, install commands) that adds another+ * computer to the account, or to `team` (from this enrolled device).+ * It expires after `ttl_secs` (30 minutes when `None`).+ */+ async createPairingCode(team: string | undefined, ttlSecs: bigint | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<PairingCode> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_sdk_fn_method_devices_create_pairing_code(+ uniffiTypeDevicesObjectFactory.clonePointer(this),FfiConverterOptionalString.lower(team, nativeModule().rustbuffer_alloc),FfiConverterOptionalUInt64.lower(ttlSecs, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterTypePairingCode.lift.bind(FfiConverterTypePairingCode),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+/*** This device's id, when it has a key (no network).*/@@ -21099,6 +21267,41 @@ private constructor(pointer: UniffiHandle) {}}+/**+ * The account's pairing codes, newest first (without the codes).+ */+ async pairingCodes(asyncOpts_?: { signal: AbortSignal }): Promise<Array<PairingCode>> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_sdk_fn_method_devices_pairing_codes(+ uniffiTypeDevicesObjectFactory.clonePointer(this)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterSequenceTypePairingCode.lift.bind(FfiConverterSequenceTypePairingCode),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+/*** The relay base URL.*/@@ -21190,6 +21393,36 @@ private constructor(pointer: UniffiHandle) {}}+/**+ * Revokes an unused pairing code (`pc_…`).+ */+ async revokePairingCode(id: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_sdk_fn_method_devices_revoke_pairing_code(+ uniffiTypeDevicesObjectFactory.clonePointer(this),FfiConverterString.lower(id, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,+ /*cancelFunc:*/ nativeModule().ffi_cua_sdk_rust_future_cancel_void,+ /*completeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_complete_void,+ /*freeFunc:*/ nativeModule().ffi_cua_sdk_rust_future_free_void,+ /*liftFunc:*/ (_v) => {},+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeCuaError.lift.bind(FfiConverterTypeCuaError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+/*** The account's devices, the grace period, the newest `audit_limit`* audit events and the machines' names. Only the device list must@@ -36604,6 +36837,9 @@ const FfiConverterSequenceTypeAgentRunInfo = new FfiConverterArray(FfiConverterT// FfiConverter for AgentRunOptions | undefinedconst FfiConverterOptionalTypeAgentRunOptions = new FfiConverterOptional(FfiConverterTypeAgentRunOptions);+// FfiConverter for Array<PairingCode>+const FfiConverterSequenceTypePairingCode = new FfiConverterArray(FfiConverterTypePairingCode);+// FfiConverter for Array<FleetClaim>const FfiConverterSequenceTypeFleetClaim = new FfiConverterArray(FfiConverterTypeFleetClaim);@@ -37085,12 +37321,18 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_devices_confirm_machine() !== 44995) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_confirm_machine");}+ if (nativeModule().uniffi_cua_sdk_checksum_method_devices_create_pairing_code() !== 19274) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_create_pairing_code");+ }if (nativeModule().uniffi_cua_sdk_checksum_method_devices_device_id() !== 58064) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_device_id");}if (nativeModule().uniffi_cua_sdk_checksum_method_devices_enroll() !== 25682) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_enroll");}+ if (nativeModule().uniffi_cua_sdk_checksum_method_devices_pairing_codes() !== 10069) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_pairing_codes");+ }if (nativeModule().uniffi_cua_sdk_checksum_method_devices_relay_url() !== 39774) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_relay_url");}@@ -37100,6 +37342,9 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_devices_revoke() !== 27802) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_revoke");}+ if (nativeModule().uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code() !== 3143) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_revoke_pairing_code");+ }if (nativeModule().uniffi_cua_sdk_checksum_method_devices_snapshot() !== 26132) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_devices_snapshot");}@@ -38229,6 +38474,7 @@ export default Object.freeze({FfiConverterTypeNotificationInfo,FfiConverterTypeOverlay,FfiConverterTypeOverlayResult,+ FfiConverterTypePairingCode,FfiConverterTypePersistentAgentInfo,FfiConverterTypePersistentAgentOptions,FfiConverterTypePoint,diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex 3e87d0a642..74f2cb9f85 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -9262,7 +9262,7 @@"subcommands": [{"abstract": "Set this machine 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",- "after_help": "Examples:\n # Join the cua.ai relay as your account (shares this desktop)\n cua host setup\n # A spare machine: do not share its desktop, run Spaces for your devices\n cua host setup --profile spare --name \"Mac mini (spare)\"\n cua host setup --no-desktop --provide-spaces\n # Serve on the LAN instead of the relay\n cua host setup --direct 0.0.0.0:3211 --name studio-mac\n # A spare Mac on your tailnet that runs Spaces, without the relay\n # (prints the command that adds it on your laptop)\n cua host setup --direct 100.101.102.103:3211 --profile spare",+ "after_help": "Examples:\n # Join the cua.ai relay as your account (shares this desktop)\n cua host setup\n # A spare machine: do not share its desktop, run Spaces for your devices\n cua host setup --profile spare --name \"Mac mini (spare)\"\n cua host setup --no-desktop --provide-spaces\n # Serve on the LAN instead of the relay\n cua host setup --direct 0.0.0.0:3211 --name studio-mac\n # A spare Mac on your tailnet that runs Spaces, without the relay\n # (prints the command that adds it on your laptop)\n cua host setup --direct 100.101.102.103:3211 --profile spare\n # Add this machine with a one-time code from the Cua Spaces app\n # (Add a machine) or `cua host pair`: no sign-in needed here\n cua host setup --pair K7QM-4XPB-2RHD","aliases": [],"arguments": [],"flags": [@@ -9353,6 +9353,22 @@"type": "string","value_name": "RELAY"},+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Join with a one-time pairing code (or add-machine link) made in the Cua Spaces app or with `cua host pair`, instead of signing in here. The machine joins the account (or team) that made it",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "pair",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "string",+ "value_name": "CODE"+ },{"aliases": [],"default_value": null,@@ -9473,6 +9489,113 @@"subcommands": [],"usage": "cua host setup [OPTIONS]"},+ {+ "abstract": "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. Codes work once and expire (30 minutes by default). Run from an enrolled device",+ "after_help": "Examples:\n cua host pair\n cua host pair --team team-aigis --expires 60\n cua host pair --list\n cua host pair --revoke pc_0123456789abcdef",+ "aliases": [],+ "arguments": [],+ "flags": [+ {+ "aliases": [],+ "default_value": false,+ "env": null,+ "help": "List your codes (used, unused, revoked, expired) instead",+ "hidden": false,+ "name": "list",+ "repeatable": false,+ "short_name": null,+ "takes_value": false+ }+ ],+ "hidden": false,+ "hidden_aliases": [],+ "name": "pair",+ "options": [+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Add the machine for this team (its id)",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "team",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "string",+ "value_name": "TEAM"+ },+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Name the machine gets (default: its own host name)",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "name",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "string",+ "value_name": "NAME"+ },+ {+ "aliases": [],+ "default_value": "30",+ "env": null,+ "help": "Minutes until the code expires (1 to 1440)",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "expires",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "integer",+ "value_name": "MINUTES"+ },+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Revoke an unused code by id (`pc_…`)",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "revoke",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "string",+ "value_name": "ID"+ },+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai)",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "relay",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "string",+ "value_name": "RELAY"+ }+ ],+ "subcommand_optional": false,+ "subcommands": [],+ "usage": "cua host pair [OPTIONS]"+ },{"abstract": "Show or change what this machine 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",diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1index 56f09ef92f..b1dd8148d5 100644--- a/scripts/install/install.ps1+++ b/scripts/install/install.ps1@@ -6,6 +6,7 @@ Cua installer for Windows: the `cua` CLI, the Cua Spaces app and agent extras.irm https://cua.ai/install.ps1 | iex& ([scriptblock]::Create((irm https://cua.ai/install.ps1))) -Select cua-driver& ([scriptblock]::Create((irm https://cua.ai/install.ps1))) -CliOnly -Yes+ & ([scriptblock]::Create((irm https://cua.ai/install.ps1))) -Pair K7QM-4XPB-2RHDAt a console it first shows a numbered checklist of what to install. Items:cli the cua CLI (always installed, except with -AppOnly)@@ -31,6 +32,12 @@ Install only the `cua` CLI (same as -Only cli).Install only the Cua Spaces app (no CLI)..PARAMETER ModePreselect the app's first-run choice: host or client (implies spaces).+.PARAMETER Pair+Add this machine to your account with a one-time code from the Cua Spaces app+(Add a machine): installs the CLI and runs `cua host setup --pair <code>`, with+no sign-in and no checklist.+.PARAMETER Relay+Relay for -Pair (default https://relay.cua.ai)..PARAMETER VersionInstall this CLI release (default: latest)..PARAMETER Prefix@@ -55,6 +62,8 @@ param([switch]$CliOnly,[switch]$AppOnly,[ValidateSet('host', 'client', '')][string]$Mode = '',+ [string]$Pair = '',+ [string]$Relay = '',[string]$Version = '',[string]$Prefix = '',[switch]$ModifyPath,@@ -148,18 +157,23 @@ function Get-CuaSelection {if ($Cli -and $App) { Stop-Install '-CliOnly and -AppOnly are mutually exclusive' }if ($OnlyList -and $SelectList) { Stop-Install '-Only and -Select are mutually exclusive' }$extra = @(ConvertTo-CuaItems "$SelectList,$OnlyList")- if ($Cli -and $extra.Count) { Stop-Install "-CliOnly installs only the CLI; use -Only $($extra -join ',') instead" }+ if ($Cli -and $extra.Count -and -not $Pair) { Stop-Install "-CliOnly installs only the CLI; use -Only $($extra -join ',') instead" }if ($App -and ($extra -contains 'cua-driver' -or $extra -contains 'host')) { Stop-Install '-AppOnly skips the CLI, which cua-driver and host need' }$sel = [ordered]@{ cli = -not $App; spaces = $false; 'cua-driver' = $false; host = $false }$list = if ($OnlyList -or $Cli) { $OnlyList } else { $SelectList }foreach ($item in @(ConvertTo-CuaItems $list)) { $sel[$item] = $true }+ # A pairing code adds this machine: the CLI and host setup.+ if ($Pair) {+ if ($App) { Stop-Install '-Pair needs the CLI; drop -AppOnly' }+ $sel.host = $true+ }# Legacy: -AppOnly and -Mode mean the app, as they always did.if ($App -or ($InstallMode -and -not $Cli)) { $sel.spaces = $true }return $sel}function Test-WantsChecklist {- return (-not $Yes -and -not $Only -and -not $CliOnly -and -not $AppOnly -and+ return (-not $Pair -and -not $Yes -and -not $Only -and -not $CliOnly -and -not $AppOnly -and$env:CUA_INSTALL_NONINTERACTIVE -ne '1' -and (Test-Interactive))}@@ -434,8 +448,31 @@ function Install-CuaDriver([string]$Cua, [string]$Tmp, [string]$ManifestUrl) {if ($LASTEXITCODE -ne 0) { Write-Warning 'agent setup for cua-driver did not finish; rerun: cua agents setup --cua-driver' }}+# Checks -Pair / -Relay: they end up on a command line.+function Test-PairArgs {+ if ($Pair -and $Pair -notmatch '^[A-Za-z0-9-]+$') { Stop-Install "-Pair: '$Pair' is not a pairing code (like K7QM-4XPB-2RHD)" }+ if ($Relay) {+ if (-not $Pair) { Stop-Install '-Relay goes with -Pair' }+ if ($Relay -notmatch '^(https://[A-Za-z0-9.-]+(:[0-9]+)?|http://(localhost|127\.0\.0\.1)(:[0-9]+)?)(/[A-Za-z0-9._%/-]*)?$') { Stop-Install '-Relay must be a plain https:// URL (plain http only for localhost)' }+ }+}++# Add this machine with a pairing code: joins the account (or team) that+# made it, with no sign-in here.+function Invoke-HostPair([string]$Cua) {+ $pairArgs = @('host', 'setup', '--pair', $Pair)+ if ($Relay) { $pairArgs += @('--relay', $Relay) }+ if ($DryRun) { Write-Host "[dry-run] $Cua $($pairArgs -join ' ')"; return }+ Write-Info 'adding this machine to your account (cua host setup --pair)'+ $null | & $Cua @pairArgs+ if ($LASTEXITCODE -ne 0) { Stop-Install 'adding this machine did not finish; if the code expired or was used, make a new one in Cua Spaces (Add a machine) and run: cua host setup --pair <code>' }+ Write-Host ''+ Write-Host 'This machine is added. It shows up in Cua Spaces on your other devices in a few seconds.'+}+# Host this machine: joins the relay as the signed-in account.function Invoke-HostSetup([string]$Cua) {+ if ($Pair) { Invoke-HostPair $Cua; return }if ($DryRun) { Write-Host "[dry-run] $Cua host setup"; return }Write-Info 'setting up this machine as a host (cua host setup)'if (Test-Interactive) { & $Cua host setup } else { $null | & $Cua host setup }@@ -447,6 +484,7 @@ function Invoke-CuaInstall {Set-StrictMode -Version 3$ErrorActionPreference = 'Stop'$ProgressPreference = 'SilentlyContinue'+ Test-PairArgs$sel = Get-CuaSelectionif ($sel.spaces -and -not $script:SpacesSupported) {Write-Info 'Cua Spaces is macOS-only for now; skipping the app on Windows'@@ -493,11 +531,11 @@ function Invoke-CuaInstall {$env:CUA_INSTALL_CHANNEL = 'install_script'if ($sel['cua-driver']) { Install-CuaDriver $cua $tmp $manifestUrl }Write-Info 'done'- if ($cua -and -not $NoOnboarding -and -not $DryRun -and (Test-Interactive)) {+ if ($cua -and -not $Pair -and -not $NoOnboarding -and -not $DryRun -and (Test-Interactive)) {Write-Info 'signing in (cua auth login)'& $cua auth loginif ($LASTEXITCODE -ne 0) { Write-Warning "sign-in did not finish; run 'cua auth login' later" }- } else {+ } elseif (-not $Pair) {Write-Host ''Write-Host 'Next steps:'if ($sel.cli) {diff --git a/scripts/install/install.sh b/scripts/install/install.shindex 1415de88bd..bb48af8797 100755--- a/scripts/install/install.sh+++ b/scripts/install/install.sh@@ -4,6 +4,7 @@# curl -fsSL https://cua.ai/install.sh | sh# curl -fsSL https://cua.ai/install.sh | sh -s -- --select cua-driver# curl -fsSL https://cua.ai/install.sh | sh -s -- --cli-only --yes+# curl -fsSL https://cua.ai/install.sh | sh -s -- --pair K7QM-4XPB-2RHD## In a terminal it shows a checklist of what to install. Items:# cli the cua CLI (always installed, except with --app-only)@@ -17,6 +18,10 @@# --cli-only install only the `cua` CLI (same as --only cli)# --app-only install only the Cua Spaces app (no CLI)# --mode host|client preselect the app's first-run choice (implies spaces)+# --pair CODE add this machine to your account with a one-time code+# from the Cua Spaces app (Add a machine): installs and+# runs `cua host setup --pair CODE`, no sign-in, no checklist+# --relay URL relay for --pair (default https://relay.cua.ai)# --version VERSION install this CLI release (default: latest)# --prefix DIR install under DIR (DIR/bin, DIR/Applications)# --modify-path add the bin dir to your shell profile@@ -60,6 +65,8 @@ sel_host=0picked=0tty_saved=""mode=""+pair_code=""+relay_url=""version=""prefix=""modify_path=0@@ -126,6 +133,18 @@ parse_args() {shift;;--mode=*) mode="${1#--mode=}" ;;+ --pair)+ [ $# -ge 2 ] || die "--pair needs the code from the Cua Spaces app"+ pair_code="$2"+ shift+ ;;+ --pair=*) pair_code="${1#--pair=}" ;;+ --relay)+ [ $# -ge 2 ] || die "--relay needs a URL"+ relay_url="$2"+ shift+ ;;+ --relay=*) relay_url="${1#--relay=}" ;;--version)[ $# -ge 2 ] || die "--version needs a value"version="$2"@@ -158,7 +177,7 @@ parse_args() {die "--only and --select are mutually exclusive"fiextra="$(items_in "$select_list$only_list")"- if [ "$cli_only" = 1 ] && [ -n "$extra" ]; then+ if [ "$cli_only" = 1 ] && [ -n "$extra" ] && [ -z "$pair_code" ]; thendie "--cli-only installs only the CLI; use --only $extra instead"fiif [ "$app_only" = 1 ]; then@@ -167,6 +186,27 @@ parse_args() {esacwant_cli=0fi+ if [ -n "$pair_code" ]; then+ # Letters, digits and dashes only: it ends up on a command line.+ case "$pair_code" in+ *[!A-Za-z0-9-]*) die "--pair: '$pair_code' is not a pairing code (like K7QM-4XPB-2RHD)" ;;+ esac+ [ "$app_only" = 0 ] || die "--pair needs the CLI; drop --app-only"+ [ "$cli_only" = 0 ] || only_list="$only_list,host"+ select_list="$select_list,host"+ if [ "$only_set" = 1 ]; then only_list="$only_list,host"; fi+ # The code stands in for the account: no sign-in here.+ onboarding=0+ fi+ if [ -n "$relay_url" ]; then+ [ -n "$pair_code" ] || die "--relay goes with --pair"+ case "$relay_url" in+ *[!A-Za-z0-9:/._%-]*) die "--relay: '$relay_url' is not a plain URL" ;;+ esac+ # https anywhere; plain http only to this machine (local relays).+ printf '%s\n' "$relay_url" | grep -Eq '^(https://[A-Za-z0-9.-]+(:[0-9]+)?|http://(localhost|127\.0\.0\.1)(:[0-9]+)?)(/[A-Za-z0-9._%/-]*)?$' ||+ die "--relay must be an https:// URL (plain http only for localhost)"+ ficase "$mode" in"" | host | client) ;;*) die "--mode must be host or client, not '$mode'" ;;@@ -289,7 +329,7 @@ spaces_supported() {# Show the checklist only when a human can answer it.wants_checklist() {- [ "$assume_yes" = 0 ] && [ "$only_set" = 0 ] && [ "$cli_only" = 0 ] &&+ [ -z "$pair_code" ] && [ "$assume_yes" = 0 ] && [ "$only_set" = 0 ] && [ "$cli_only" = 0 ] &&[ "$app_only" = 0 ] && [ "${CUA_INSTALL_NONINTERACTIVE:-}" != 1 ] && tty_ok}@@ -829,6 +869,10 @@ install_driver() {# provide Spaces for other devices (macOS VMs) needs Lume too, installed# separately with `cua runtime setup lume`.host_setup() {+ if [ -n "$pair_code" ]; then+ host_pair+ return+ fiif [ "$dry_run" = 1 ]; thensay "[dry-run] $cua_bin host setup"return@@ -848,6 +892,24 @@ host_setup() {warn "host setup did not finish; run 'cua auth login --remote' (over ssh) or 'cua auth login', then 'cua host setup' again"}+# Add this machine with a pairing code (Add a machine in the app): joins+# the account (or team) that made the code, with no sign-in here.+host_pair() {+ set -- "$cua_bin" host setup --pair "$pair_code"+ if [ -n "$relay_url" ]; then set -- "$@" --relay "$relay_url"; fi+ if [ "$dry_run" = 1 ]; then+ say "[dry-run] $*"+ return+ fi+ info "adding this machine to your account (cua host setup --pair)"+ if "$@" </dev/null; then+ say ""+ say "This machine is added. It shows up in Cua Spaces on your other devices in a few seconds."+ return+ fi+ die "adding this machine did not finish; if the code expired or was used, make a new one in Cua Spaces (Add a machine) and run: cua host setup --pair <code>"+}+# ---------------------------------------------------------------- onboardingnext_steps() {@@ -870,6 +932,8 @@ next_steps() {}run_onboarding() {+ # --pair: the code stands in for the account; nothing to sign in to.+ [ -z "$pair_code" ] || return 0if [ "$want_cli" = 0 ] || [ "$onboarding" = 0 ] || [ "$dry_run" = 1 ]; thennext_stepsreturndiff --git a/scripts/install/tests/install.Tests.ps1 b/scripts/install/tests/install.Tests.ps1index 278161f279..ba74741567 100644--- a/scripts/install/tests/install.Tests.ps1+++ b/scripts/install/tests/install.Tests.ps1@@ -208,6 +208,21 @@ Describe 'install.ps1' {Join-Path $prefix 'bin/cua.exe' | Should -Not -Exist}+ It 'dry run: -Pair installs the CLI and runs host setup with the code, no sign-in or checklist' {+ $out = Invoke-Installer @{ DryRun = $true; Pair = 'K7QM-4XPB-2RHD'; Relay = 'https://relay.example.com' }+ $out | Should -Match 'cua-cli-1.2.3-windows-x64.zip'+ $out | Should -Match 'host setup --pair K7QM-4XPB-2RHD --relay https://relay.example.com'+ $out | Should -Not -Match 'auth login'+ $out | Should -Not -Match 'Choose what to install'+ }++ It '-Pair refuses codes and relays with shell characters' {+ { Invoke-Installer @{ DryRun = $true; Pair = 'K7QM;calc' } } | Should -Throw '*not a pairing code*'+ { Invoke-Installer @{ DryRun = $true; Pair = 'K7QM-4XPB-2RHD'; Relay = 'http://evil.example' } } | Should -Throw '*https*'+ { Invoke-Installer @{ DryRun = $true; Pair = 'K7QM-4XPB-2RHD'; Relay = 'http://localhost.evil.example' } } | Should -Throw '*https*'+ { Invoke-Installer @{ DryRun = $true; Relay = 'https://relay.example.com' } } | Should -Throw '*goes with -Pair*'+ }+It 'rejects -CliOnly with -AppOnly' {{ Invoke-Installer @{ CliOnly = $true; AppOnly = $true } } | Should -Throw '*mutually exclusive*'}diff --git a/scripts/install/tests/run.sh b/scripts/install/tests/run.shindex 27173c700c..ff470cec6c 100755--- a/scripts/install/tests/run.sh+++ b/scripts/install/tests/run.sh@@ -209,6 +209,25 @@ check "CUA_INSTALL_NONINTERACTIVE + --select host: runs 'cua host setup'" sh -cinst -- --yes --only host --prefix "$work/h2"check "--only host: runs 'cua host setup', no app" sh -c "[ $status = 0 ] && grep -qx 'host setup' '$home/cua.log' && [ ! -e '$work/h2/bin/cua-spaces' ]"+inst -- --pair k7qm-4xpb-2rhd --prefix "$work/pr1"+check "--pair: runs 'cua host setup --pair', no sign-in, no checklist" sh -c "[ $status = 0 ] && grep -qx 'host setup --pair k7qm-4xpb-2rhd' '$home/cua.log' && ! grep -q 'auth login' '$home/cua.log' && grep -q 'This machine is added' '$work/out'"++inst -- --pair K7QM-4XPB-2RHD --relay https://relay.example.com --cli-only --prefix "$work/pr2"+check "--pair --relay --cli-only: passes the relay on" sh -c "[ $status = 0 ] && grep -qx 'host setup --pair K7QM-4XPB-2RHD --relay https://relay.example.com' '$home/cua.log'"++inst -- --pair 'K7QM;rm -rf /' --prefix "$work/pr3"+check "--pair: refuses a code with shell characters before installing" sh -c "[ $status != 0 ] && grep -q 'not a pairing code' '$work/out' && [ ! -e '$work/pr3/bin/cua' ]"++inst -- --pair K7QM-4XPB-2RHD --relay http://evil.example --prefix "$work/pr4"+check "--pair: refuses a plain-http relay" sh -c "[ $status != 0 ] && grep -q 'must be an https' '$work/out'"++inst -- --pair K7QM-4XPB-2RHD --relay http://localhost.evil.example --prefix "$work/pr5"+check "--pair: refuses a plain-http relay that only starts like localhost" sh -c "[ $status != 0 ] && grep -q 'must be an https' '$work/out'"++inst -- --pair K7QM-4XPB-2RHD --relay http://127.0.0.1:8080 --prefix "$work/pr6"+check "--pair: allows a local plain-http relay" sh -c "[ $status = 0 ] && grep -qx 'host setup --pair K7QM-4XPB-2RHD --relay http://127.0.0.1:8080' '$home/cua.log'"+check "--pair: no sign-in next steps" sh -c "! grep -q 'cua auth login' '$work/out'"+inst CUA_INSTALL_DRIVER_URL="$driver_url" -- --dry-run --select cua-driver,host --prefix "$work/dr"check "--dry-run prints the driver, agents and host steps" sh -c "grep -q 'dry-run. download $driver_url' '$work/out' && grep -q 'dry-run. bash cua-driver-install.sh --bin-dir' '$work/out' && grep -q 'dry-run. .* agents setup --cua-driver --agents all --yes' '$work/out' && grep -q 'dry-run. .* host setup' '$work/out'"check "--dry-run runs nothing" sh -c "[ ! -e '$home/cua.log' ] && [ ! -e '$home/driver.log' ] && [ ! -e '$work/dr' ]"