UNPKG

agent-device

Version:

Open source device layer for AI coding agents: a CLI, MCP server, and typed Node.js API to control mobile, web, TV, and desktop apps on devices and simulators, locally or in the cloud.

1 lines • 17.1 kB
import{Ci as e,Si as t,wi as n}from"./sdk-batch.js";import{v as r}from"./sdk-contracts.js";import{r as i}from"./tap-keyboard-occlusion.js";import{t as a}from"./ios-node-interpretation.js";import{n as o,r as s}from"./host3.js";import{n as c}from"./detached-attempt.js";import{n as l,r as u,t as d}from"./errors.js";import{Buffer as f}from"node:buffer";function p(e,t,n=Date.now){if(t?.aborted)throw u(`cancelled`,`abort-signal`);return o(e,t,n)}function m(e,t){try{return s(e,t)}catch(e){throw l(e)}}async function h(e,t,n,r){let i=Math.min(t,m(e,n));await c({waitMs:i,signal:e.signal,stop:r,cancelled:()=>u(`cancelled`,`abort-signal`)})}const g=16777216,_=12e4,v=1e4,ee=Object.freeze({maxRequestBytes:65536,maxResponseBytes:4194304,maxNodes:5e3,maxTraversalDepth:128,maxDurationMs:5e3});function y(e){let t={...ee,...e??{}};for(let[e,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0)throw new r(`INVALID_ARGS`,`Snapshot source limit ${e} must be a positive integer`,{name:e,value:n});if(t.maxRequestBytes>t.maxResponseBytes)throw new r(`INVALID_ARGS`,`Snapshot source request bytes cannot exceed response bytes`,{maxRequestBytes:t.maxRequestBytes,maxResponseBytes:t.maxResponseBytes});if(t.maxRequestBytes>g||t.maxResponseBytes>g)throw new r(`INVALID_ARGS`,`Snapshot source frame limits exceed the bridge bound`,{maxRequestBytes:t.maxRequestBytes,maxResponseBytes:t.maxResponseBytes,maximumFrameBytes:g});if(t.maxNodes>v||t.maxTraversalDepth>128)throw new r(`INVALID_ARGS`,`Snapshot source tree limits exceed the bridge bound`,{maxNodes:t.maxNodes,maxTraversalDepth:t.maxTraversalDepth,maximumNodes:v,maximumDepth:128});if(t.maxDurationMs>_)throw new r(`INVALID_ARGS`,`Snapshot source duration exceeds the bridge bound`,{maxDurationMs:t.maxDurationMs,maximumDurationMs:_});if(t.maxRequestBytes<=4||t.maxResponseBytes<=4)throw new r(`INVALID_ARGS`,`Snapshot source frame limits must leave room for a body`,{maxRequestBytes:t.maxRequestBytes,maxResponseBytes:t.maxResponseBytes});return Object.freeze(t)}var te=class{entries=new Map;probeBackAfterUses;constructor(e=8){this.probeBackAfterUses=e}consume(e,t,n){if(n)return{nativeLevels:void 0,reason:`explicit-depth`};let r=this.currentEntry(e);return r===`unidentified`?{nativeLevels:void 0,reason:`unidentified-target`}:!r||r.nativeLevels>=b(t)?{nativeLevels:void 0,reason:`no-hint`}:r.remainingUses<=0?{nativeLevels:void 0,reason:`probe-back`}:(--r.remainingUses,{nativeLevels:r.nativeLevels,reason:`hinted`})}learn(e,t,n,r){if(n||!e.targetId)return`ignored`;let i=b(t);return r.rejected>0&&r.acceptedLevels<i?(this.remember(e.targetId,{generation:e.generation,nativeLevels:r.acceptedLevels,remainingUses:this.probeBackAfterUses}),`learned`):r.rejected===0&&r.acceptedLevels>=i?this.entries.delete(e.targetId)?`forgotten`:`ignored`:this.currentEntry(e)?`kept`:`ignored`}currentEntry(e){if(!e.targetId)return`unidentified`;let t=this.entries.get(e.targetId);if(t){if(t.generation!==e.generation){this.entries.delete(e.targetId);return}return t}}remember(e,t){if(this.entries.delete(e),this.entries.size>=32){let e=this.entries.keys().next().value;e!==void 0&&this.entries.delete(e)}this.entries.set(e,t)}};function b(e){return Math.min(e,65)}const x=`agent-device-simulator-ax-v1.10.0`;Object.freeze([`verb`,`requestId`,`pid`,`generation`,`snapshotTree`,`automationMode`,`maxDepth`,`maxNodes`,`maxDurationMs`,`maxResponseBytes`,`nativeLevelsHint`,`surfaceHostExecutables`,`simulatorUdid`]),Object.freeze([`protocolVersion`,`sourceVersion`,`requestId`,`generation`,`ok`,`pid`,`tree`,`truncated`,`automationEnabled`,`recovery`,`error_kind`,`error_code`,`error`,`surfaceHostExecutable`]),Object.freeze([`XC_kAXXCAttributeElementType`,`XC_kAXXCAttributeElementBaseType`,`XC_kAXXCAttributeLabel`,`XC_kAXXCAttributeValue`,`XC_kAXXCAttributePlaceholderValue`,`XC_kAXXCAttributeIdentifier`,`XC_kAXXCAttributeFrame`,`XC_kAXXCAttributeAutomationType`,`XC_kAXXCAttributeTraits`,`XC_kAXXCAttributeIsUserInteractionEnabled`,`XC_kAXXCAttributeChildren`]);const S=[`requests`,`rejected`,`continuations`,`acceptedLevels`];function C(e){let t=e.recovery;if(!O(t))throw u(`malformed-tree`,`recovery-invalid`);let n=S.map(e=>[e,t[e]]);if(n.some(([,e])=>!Number.isSafeInteger(e)||e<0))throw u(`malformed-tree`,`recovery-invalid`);return Object.freeze(Object.fromEntries(n))}function w(e,t){let n;try{n=f.from(JSON.stringify(e),`utf8`)}catch(e){throw u(`malformed-tree`,`request-not-json`,{},e)}let r=n.length+4;if(r>t.maxRequestBytes)throw u(`transport-failure`,`request-limit-exceeded`,{frameBytes:r,maxRequestBytes:t.maxRequestBytes});let i=f.alloc(4);return i.writeUInt32BE(n.length,0),f.concat([i,n])}var T=class{header=f.alloc(4);headerBytes=0;chunks=[];payloadBytes=0;expectedBodyBytes;frame;maxFrameBytes;constructor(e){if(!Number.isSafeInteger(e)||e<=0)throw u(`malformed-tree`,`frame-limit-invalid`,{maxFrameBytes:e});this.maxFrameBytes=e}push(e){if(this.frame)return this.acceptTrailingChunk(e);let t=this.readHeader(e);if(t&&(this.appendPayload(e,t.offset,t.bodyBytes),this.payloadBytes===t.bodyBytes))return this.frame=f.concat(this.chunks,t.bodyBytes),this.frame}acceptTrailingChunk(e){if(e.length>0)throw u(`malformed-tree`,`multiple-frames`,{trailingBytes:e.length});return this.frame}readHeader(e){if(this.headerBytes===4)return{offset:0,bodyBytes:this.expectedBodyBytes};let t=Math.min(4-this.headerBytes,e.length);if(e.copy(this.header,this.headerBytes,0,t),this.headerBytes+=t,this.headerBytes<4)return;let n=this.header.readUInt32BE(0);if(n===0||n>this.maxFrameBytes)throw u(`malformed-tree`,`frame-limit-exceeded`,{bodyBytes:n,maxFrameBytes:this.maxFrameBytes});return this.expectedBodyBytes=n,{offset:t,bodyBytes:n}}appendPayload(e,t,n){let r=n-this.payloadBytes,i=e.length-t;if(i>r)throw u(`malformed-tree`,`multiple-frames`,{trailingBytes:i-r});i!==0&&(this.chunks.push(e.subarray(t)),this.payloadBytes+=i)}finish(){if(this.frame)return this.frame;throw u(`transport-failure`,`bridge-frame-incomplete`,{headerBytes:this.headerBytes,payloadBytes:this.payloadBytes,expectedBodyBytes:this.expectedBodyBytes})}};function ne(e){let t;try{t=JSON.parse(e.toString(`utf8`))}catch(e){throw u(`malformed-tree`,`response-not-json`,{},e)}if(!O(t))throw u(`malformed-tree`,`response-not-object`);return t}function re(e){return Object.freeze({verb:`describe`,requestId:e.requestId,pid:e.pid,generation:e.generation,snapshotTree:!0,automationMode:!0,maxDepth:e.maxDepth,maxNodes:e.maxNodes,maxDurationMs:e.maxDurationMs,maxResponseBytes:e.maxResponseBytes,...e.nativeLevelsHint===void 0?{}:{nativeLevelsHint:e.nativeLevelsHint},...e.surfaceHosts?{surfaceHostExecutables:e.surfaceHosts.executables,simulatorUdid:e.surfaceHosts.simulatorUdid}:{}})}function ie(e,t){if(e.protocolVersion!==1)throw u(`transport-failure`,`protocol-version-mismatch`,{expected:1,observed:e.protocolVersion});if(e.sourceVersion!==`agent-device-simulator-ax-v1.10.0`)throw u(`transport-failure`,`source-version-mismatch`,{expected:x,observed:e.sourceVersion});if(e.requestId!==t)throw u(`transport-failure`,`request-id-mismatch`,{expected:t,observed:e.requestId})}function ae(e,t){if(typeof e.pid!=`number`||e.pid!==t.pid)throw u(`stale-target`,`bridge-pid-mismatch`,{expectedPid:t.pid,observedPid:e.pid});if(e.generation!==t.generation)throw u(`stale-target`,`bridge-generation-mismatch`,{expectedGeneration:t.generation,observedGeneration:e.generation})}function E(e,t){if(ie(e,t.requestId),e.ok!==!0&&D(e),ae(e,t),typeof e.truncated!=`boolean`)throw u(`malformed-tree`,`truncated-invalid`);return e}function D(e){let t=e.error_kind,n=typeof e.error_code==`string`?e.error_code:`guest-error`,r=typeof e.error==`string`?e.error:void 0,i=typeof e.surfaceHostExecutable==`string`?e.surfaceHostExecutable:void 0,a={...r?{guestMessage:r.slice(0,1024)}:{},...i?{surfaceHostExecutable:i}:{}};throw u(t===`unsupported`?`unsupported`:t===`malformed_tree`?`malformed-tree`:t===`application_not_responding`?`timeout`:t===`application_unavailable`?`transport-failure`:t===`bad_request`?`malformed-tree`:t===`stale_target`?`stale-target`:`transport-failure`,n,a)}function O(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function k(t,n){return!e(t)||!e(n)||Math.abs(n.width-n.height)<=1?!1:Math.abs(t.width-n.height)<=1&&Math.abs(t.height-n.width)<=1}const A=Object.freeze({elementType:`XC_kAXXCAttributeElementType`,elementBaseType:`XC_kAXXCAttributeElementBaseType`,label:`XC_kAXXCAttributeLabel`,value:`XC_kAXXCAttributeValue`,placeholder:`XC_kAXXCAttributePlaceholderValue`,identifier:`XC_kAXXCAttributeIdentifier`,frame:`XC_kAXXCAttributeFrame`,automationType:`XC_kAXXCAttributeAutomationType`,traits:`XC_kAXXCAttributeTraits`,userInteractionEnabled:`XC_kAXXCAttributeIsUserInteractionEnabled`,children:`XC_kAXXCAttributeChildren`}),j=`Other.Other.Application.Group.Window.Sheet.Drawer.Alert.Dialog.Button.RadioButton.RadioGroup.CheckBox.DisclosureTriangle.PopUpButton.ComboBox.MenuButton.ToolbarButton.Popover.Keyboard.Key.NavigationBar.TabBar.TabGroup.Toolbar.StatusBar.Table.TableRow.TableColumn.Outline.OutlineRow.Browser.CollectionView.Slider.PageIndicator.ProgressIndicator.ActivityIndicator.SegmentedControl.Picker.PickerWheel.Switch.Toggle.Link.Image.Icon.SearchField.ScrollView.ScrollBar.StaticText.TextField.SecureTextField.DatePicker.TextView.Menu.MenuItem.MenuBar.MenuBarItem.Map.WebView.IncrementArrow.DecrementArrow.Timeline.RatingIndicator.ValueIndicator.SplitGroup.Splitter.RelevanceIndicator.ColorWell.HelpTag.Matte.DockItem.Ruler.RulerMarker.Grid.LevelIndicator.Cell.LayoutArea.LayoutItem.Handle.Stepper.Tab.TouchBar.StatusItem`.split(`.`),M={UIApplication:`Application`,UIWindow:`Window`},N=new Set(Object.values(A)),P=1n<<8n,F=1n<<3n,I=1n<<21n,L=1n<<28n,R=1n<<10n,z=1n<<18n,B=1n<<24n,V=1n<<47n,H={x:0,y:0,width:0,height:0};function U(e,t,n){let r=Array.isArray(e)?e:[e];if(r.length===0||r.some(e=>!O(e)))throw u(`malformed-tree`,`guest-tree-root-invalid`);let i=[],o=[],s=0;for(let e of r)l(e,void 0,0,!1);if(i.length>n.maxNodes)throw u(`malformed-tree`,`node-limit-exceeded`,{nodeCount:i.length,maxNodes:n.maxNodes});if(s>n.maxTraversalDepth)throw u(`malformed-tree`,`traversal-depth-exceeded`,{maxTraversalDepth:s,maxAllowedDepth:n.maxTraversalDepth});if(typeof t.truncated!=`boolean`)throw u(`malformed-tree`,`truncated-invalid`);let c=le(i.filter(J)[0]);return c.kind===`reported`&&ue(i,c.rect),{nodes:i,maxTraversalDepth:s,viewport:c,opaqueRemoteElements:o.filter(e=>se(e,c)).length,unresolvedCoordinateSpaceWindows:de(i,c)};function l(e,t,r,c){if(i.length>=n.maxNodes)throw u(`malformed-tree`,`node-limit-exceeded`,{maxNodes:n.maxNodes});for(let t of Object.keys(e))if(!N.has(t))throw u(`malformed-tree`,`node-contains-unknown-field`,{key:t});let d=e[A.children];if(!Array.isArray(d))throw u(`malformed-tree`,`children-invalid`);let f=i.length,p=W(e,f,t,r);i.push(a(p)),s=Math.max(s,r),q(p,d.length,c)&&o.push(p.rect);let m=c||K(p);for(let e of d){if(!O(e))throw u(`malformed-tree`,`child-invalid`);l(e,f,r+1,m)}}}function W(e,t,n,r){let i=Y(e[A.elementType]),a=Y(e[A.elementBaseType]),o=me(e[A.automationType]),s=ce(e[A.frame]),c=Z(e[A.traits]),l=c===void 0?void 0:(c&P)===0n,u=c===void 0||(c&F)===0n?void 0:!0,d=c===void 0||(c&I)===0n?void 0:!0,f=pe(e[A.userInteractionEnabled]),p=Y(e[A.placeholder])?.trim();return{index:t,...n===void 0?{}:{parentIndex:n},...G(i,o,c)?{type:G(i,o,c)}:{},...i?{role:i}:{},...a&&a!==i?{subrole:a}:{},...Y(e[A.label])?{label:Y(e[A.label])}:{},...X(e[A.value])?{value:X(e[A.value])}:{},...p?{placeholder:p}:{},...Y(e[A.identifier])?{identifier:Y(e[A.identifier])}:{},...s?{rect:s}:{},...l===void 0?{}:{enabled:l},...u===void 0?{}:{selected:u},...d===void 0?{}:{focused:d},...f===void 0?{}:{userInteractionEnabled:f},depth:r}}function G(e,t,n){if(e!==void 0&&M[e])return M[e];if(n!==void 0&&(n&L)!==0n)return`Button`;if(e!==void 0&&j.includes(e))return e;let r=t===void 0?void 0:j[t]??`Other`;return r!==void 0&&r!==`Other`?r:oe(n)??r}function oe(e){if(e!==void 0&&(e&z)!==0n)return(e&B)===0n?(e&R)===0n?(e&V)===0n?`TextField`:`TextView`:`SearchField`:`SecureTextField`}function K(e){return e.type===`WebView`||e.role===`_UISceneHostingView`}function q(e,t,n){return n&&e.role===`AXRemoteElement`&&t===0}function se(t,r){return t===void 0?!0:e(t)?r.kind!==`reported`||n(t,r.rect):!1}function ce(e){if(e===void 0)return;if(!O(e))throw u(`malformed-tree`,`frame-invalid`);let t=[`X`,`Y`,`Width`,`Height`].map(t=>e[t]);if(!t.every(e=>typeof e==`number`&&Number.isFinite(e)))throw u(`malformed-tree`,`frame-invalid`);let[n,r,i,a]=t;if(i<0||a<0)throw u(`malformed-tree`,`frame-invalid`);return{x:n,y:r,width:i,height:a}}function le(t){return!t||!J(t)?{kind:`missing`,reason:`not-provided`}:e(t.rect)?{kind:`reported`,rect:t.rect}:{kind:`missing`,reason:t.rect?`invalid`:`not-provided`}}function J(e){return e.type===`Application`||e.type===`Window`}function ue(e,n){for(let r of e)r.hittable=r.parentIndex!==void 0&&t(r.enabled!==!1,r.rect,n)}function de(e,t){return t.kind===`reported`?e.filter(n=>fe(n,e)&&k(n.rect??H,t.rect)).length:0}function fe(e,t){return J(e)?!0:e.parentIndex!==void 0&&J(t[e.parentIndex]??e)}function Y(e){return typeof e==`string`&&e.length>0?e:void 0}function X(e){if(typeof e==`string`)return e.length>0?e:void 0;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(e!=null)throw u(`malformed-tree`,`scalar-invalid`)}function Z(e){if(e!=null){if(typeof e!=`string`||!/^\d{1,20}$/.test(e))throw u(`malformed-tree`,`traits-invalid`);return BigInt(e)}}function pe(e){if(e!=null){if(typeof e!=`boolean`)throw u(`malformed-tree`,`user-interaction-invalid`);return e}}function me(e){if(e!=null){if(!Number.isSafeInteger(e))throw u(`malformed-tree`,`automation-type-invalid`);return e}}const Q=`simulator-ax-bridge`;function he(e){let t=e.transport,n=new te,r=e.diagnostics,i=!1,a;return{acquire:async a=>{try{if(i)throw u(`unsupported`,`source-closed`);t.validateTarget(a.target),ge(a.hint);let o=y({...e.limits,...a.limits}),s=p(o.maxDurationMs,a.signal),c=ve(a.hint,o.maxTraversalDepth),l=c+1,d=a.hint.rawTraversalDepth!==null;return await r.withDiagnosticTimer(`ios.snapshot-source.acquire`,async()=>{let e=await t.prepare(a.target,s),i=n.consume(a.target,l,d),u=await e({limits:o,maxDepth:c,...i.nativeLevels===void 0?{}:{nativeLevelsHint:i.nativeLevels},...a.surfaceHostExecutables?{surfaceHostExecutables:a.surfaceHostExecutables}:{},deadline:s});m(s,`snapshot-decode-deadline`);let f=ye(a.hint,a.target,u,o);return _e(r,n,a.target,l,d,i,u),{stage:`acquired`,acquisition:f}},{producer:Q,transport:t.name})}catch(e){let t=d(e);return{stage:`failed`,failure:{kind:t.failureKind,code:t.failureCode,...t.details?{details:t.details}:{}}}}},close:()=>a||(i=!0,a=t.close(),a)}}function ge(e){if(e.projection!==`raw`&&e.projection!==`regular`||![`full`,`surface-observation`].includes(e.acquisitionIntent)||typeof e.interactiveOnly!=`boolean`||typeof e.customActions!=`boolean`||!$(e.rawTraversalDepth)||!$(e.regularPresentedDepth))throw new r(`INVALID_ARGS`,`Simulator snapshot source capture hint is invalid`)}function _e(e,t,n,r,i,a,o){let s=C(o),c=o.truncated===!0,l=t.learn(n,r,i,s);e.emitDiagnostic({level:`debug`,phase:`ios_snapshot_source_recovery`,data:{producer:Q,...n.targetId?{targetId:n.targetId}:{},generation:n.generation,requestedLevels:r,hint:a.reason,...a.nativeLevels===void 0?{}:{hintedLevels:a.nativeLevels},...s,truncated:c,learning:l}})}function ve(e,t){let n=e.rawTraversalDepth??t;if(n>t)throw new r(`INVALID_ARGS`,`Simulator snapshot source depth exceeds its bound`,{requested:n,maximum:t});return n}function $(e){return e===null||Number.isSafeInteger(e)&&e>=0}function ye(e,t,n,r){if(n.automationEnabled!==!0)throw u(`unsupported`,`automation-mode-unavailable`);let a=n.tree,o=n.truncated;if(typeof o!=`boolean`)throw u(`malformed-tree`,`truncated-invalid`);let s=U(a,{truncated:o},r),c=n.generation;if(typeof c!=`string`||!c)throw u(`malformed-tree`,`generation-invalid`);if(s.opaqueRemoteElements>0)throw u(`unsupported`,`remote-content-boundary`,{remoteElements:s.opaqueRemoteElements});if(s.unresolvedCoordinateSpaceWindows>0)throw u(`unsupported`,`window-coordinate-space-unresolved`,{windows:s.unresolvedCoordinateSpaceWindows});let l=Object.freeze(s.nodes.map(e=>Object.freeze({...e,pid:t.pid}))),d=be(e,o,s.viewport),f=Object.freeze({...t.targetId?{targetId:t.targetId}:{},generation:c}),p={producer:Q,nodes:l,truncated:o,viewport:s.viewport,keyboard:i({nodes:l,viewport:s.viewport.kind===`reported`?s.viewport.rect:null,complete:!o}),lineage:f,residue:d};return e.acquisitionIntent===`full`?{...p,intent:`full`,hint:{...e,acquisitionIntent:`full`}}:{...p,intent:`surface-observation`,hint:{...e,acquisitionIntent:`surface-observation`}}}function be(e,t,n){let r=n.kind===`reported`?[]:[{kind:`unavailable-fact`,fact:`hittability`}];return Object.freeze([...r,...e.interactiveOnly?[{kind:`unavailable-fact`,fact:`interactive-query`}]:[],...t?[{kind:`truncated`}]:[],...n.kind===`missing`?[{kind:`missing-viewport`,reason:n.reason}]:[]])}export{E as a,O as c,p as d,m as f,T as i,ne as l,he as n,re as o,h as p,x as r,w as s,Q as t,y as u};