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 • 18.8 kB
JavaScript
import{Mn as e,jn as t,wn as n}from"./sdk-batch.js";import{v as r}from"./sdk-contracts.js";import{Z as i}from"./sdk-io.js";import{J as a}from"./sdk-device.js";import"./command.js";import{n as o}from"./device-shell.js";import{a as s,r as c}from"./durable-resource.js";import{n as l}from"./screen-recording-runtime.js";import{n as u,t as d}from"./application-lifecycle-runtime.js";import{n as f}from"./async-lifecycle.js";import{i as p}from"./touch-runtime.js";import{r as m}from"./gesture-admission.js";import{i as h,n as g}from"./perf-runtime-operation-builder.js";import{C as ee,D as te,F as ne,M as re,O as ie,R as ae,V as oe,W as se,_ as ce,j as le,l as ue,o as de,p as fe,r as pe,v as me,x as he}from"./tv-remote-runtime.js";import{n as ge}from"./audio-probe-runtime.js";import{n as _e}from"./perf-runtime.js";import{a as ve,i as ye}from"./screenshot-runtime2.js";import{t as be}from"./viewport-runtime.js";import{r as xe,u as _}from"./application-lifecycle-interaction.js";import{t as v}from"./local-interactor-operation-set.js";import{n as y,t as b}from"./src10.js";import{n as x,t as S}from"./screen-recording-completion.js";import{t as C}from"./screen-recording-options.js";import{t as w}from"./app-log-runtime.js";import{n as T,r as E}from"./app-lifecycle2.js";import{randomUUID as D}from"node:crypto";import{setTimeout as O}from"node:timers/promises";const k=Object.freeze({resourceKind:w,version:1,encode:e=>({...e}),decode:e=>e.transport!==`harmony-hilog`||!j(e.outputPath)||!j(e.pidPath)?{status:`invalid`,message:`Invalid HarmonyOS app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`harmony-hilog`,outputPath:e.outputPath,pidPath:e.pidPath})}});function A(e){return c({resourceKind:w,sessionId:e.sessionId,device:{id:e.device.id,family:`harmonyos`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:s(k,e.descriptor)})}function j(e){return typeof e==`string`&&e.trim().length>0}function M(e){return b(e,{family:`harmonyos`,backend:`harmonyos`,label:`HarmonyOS`,codec:k,startUnavailableHint:`The selected HarmonyOS transport cannot start a background hilog stream.`,cleanupFailureMessage:`HarmonyOS app-log cleanup did not settle every owned resource`,doctor:async(e,t)=>({backend:`harmonyos`,checks:{},notes:t?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}),process:async({host:e,device:t,input:n,signal:r})=>{let i=await Se(e,r);return{resolvePid:async r=>await y(e,{executable:i,args:o(`hdc`,`shell`,[`pidof`,n.appBundleId],[`-t`,t.id]),allowFailure:!0,timeoutMs:5e3},r),command:e=>({kind:`host`,request:{executable:i,args:o(`hdc`,`shell`,[`hilog`,`-P`,e],[`-t`,t.id]),allowFailure:!0}})}},descriptor:({artifacts:e})=>({transport:`harmony-hilog`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>A({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function Se(e,t){t.throwIfAborted(),await N(async()=>await e.toolchains.prepare(`harmonyos`),t),t.throwIfAborted();let n=await N(async()=>await e.commands.which(`hdc`),t);if(t.throwIfAborted(),!n)throw new r(`TOOL_MISSING`,`hdc not found in PATH`,{hint:`Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.`});return n}async function N(e,t){try{return await e()}catch(e){throw t.throwIfAborted(),e}}function Ce(e){let{resolveHost:t,device:n}=e,r={available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`};return Object.freeze({perfFrames:async()=>({metric:r,sampling:r}),perfMemorySample:async({appId:e})=>({metric:e?await h(t().sampleMemory(n,e)):g(`HarmonyOS`,`bundle`),sampling:{method:`hdc-shell-proc-status`,description:`Resident memory snapshot from HarmonyOS /proc/<pid>/status. Values are reported in kilobytes.`,unit:`kB`,topConsumerLimit:1}}),perfMemorySnapshot:async({kind:e})=>({artifact:{available:!1,kind:e??`memgraph`,reason:`Memory snapshot artifacts are not supported on harmonyos.`,hint:`Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS.`,support:{platform:`harmonyos`,defaultKind:`memgraph`,androidHprof:!1,memgraph:!1,heapprofd:!1}},sampling:{method:`unsupported`,description:`HarmonyOS memory snapshot capture is not available through HDC.`,artifactOnly:!0}})})}const P=Object.freeze({resourceKind:l,version:1,encode:e=>({...e}),decode:e=>e.backend===`harmony-screen-recorder`&&typeof e.fileName==`string`&&Ee(e.fileName)&&e.remotePath===`/data/local/tmp/${e.fileName}`?{status:`decoded`,descriptor:Object.freeze({backend:`harmony-screen-recorder`,fileName:e.fileName,remotePath:e.remotePath})}:{status:`invalid`,message:`Invalid HarmonyOS screen-recording descriptor`}});function we(e){let{device:t,owner:n,input:r,descriptor:i}=e;return c({resourceKind:l,sessionId:r.sessionId,device:a(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:s(P,i)})}function Te(e){return P.decode(e).status===`decoded`?{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`HarmonyOS recorder ownership cannot be proven after daemon restart; no recorder was stopped.`}:{status:`cleanup-pending`,reason:`manual-recovery-required`}}function Ee(e){return/^agent-device-recording-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.mp4$/i.test(e)}function De(e){return e.kind===`device`?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS recording is supported on physical devices only.`})}function Oe(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await ke({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`HarmonyOS recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async e=>Te(e.envelope.descriptor.body)})}async function ke(e){let{host:t,device:n,owner:i,input:a,signal:o}=e;if(a.scope===`app`)throw new r(`INVALID_ARGS`,`HarmonyOS recording captures the whole physical-device screen; use --scope device or --scope system`);C(a,{scopes:[`device`,`system`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`HarmonyOS recordings do not support ${e.join(`, `)}`),o.throwIfAborted(),await t.screenRecording.outputs.prepare(a.outputPath);let s=`agent-device-recording-${D()}.mp4`,c={backend:`harmony-screen-recorder`,fileName:s,remotePath:`/data/local/tmp/${s}`},l;try{l=await t.screenRecording.harmony.start(n,s,o),o.throwIfAborted()}catch(e){throw o.aborted?(await I(t,n,c).catch(()=>{}),o.reason):e}R(l,`start`);try{o.throwIfAborted()}catch(e){throw await I(t,n,c).catch(()=>{}),e}let u=Ae(a),d=!1,p=async()=>{d||=(R(await t.screenRecording.harmony.stop(n),`stop`),!0)},m=x(u,{finish:async e=>await je(t,n,e,c,p),forceCleanup:async()=>await I(t,n,c,p)});return Object.freeze({pendingHandle:new f(m),envelope:we({device:n,owner:i,input:a,descriptor:c})})}function Ae(e){return Object.freeze({backend:`HarmonyOS ScreenRecorder`,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:Date.now(),scope:e.scope,showTouches:!1,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},gestureEvents:[]})}async function je(e,t,n,r,i){await i();let a=await e.screenRecording.harmony.findMedia(t,r.fileName);if(!a)throw Error(`failed to find finalized HarmonyOS recording '${r.fileName}'`);if(!await Pe(e,t,r,a))throw Error(`failed to finalize HarmonyOS recording: ${r.fileName} did not produce a non-empty media file`);try{if((await e.screenRecording.harmony.pull(t,{remotePath:r.remotePath,outputPath:n.outPath})).exitCode!==0)throw Error(`failed to retrieve HarmonyOS recording`);let i=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!1,gestureEvents:n.gestureEvents,targetLabel:`HarmonyOS recording`}),o=await Me(e,t,r,a);return S(n,{...i,...Ne(i.warning,o)},{stopObservation:{recorder:`confirmed`},nativePathDisposition:o===void 0?`retired`:`retirable`,showTouches:!1})}catch(n){throw await e.screenRecording.harmony.remove(t,r.remotePath).catch(()=>{}),n}}async function Me(e,t,n,r){let i=[];return await F(()=>e.screenRecording.harmony.remove(t,n.remotePath))||i.push(`staging artifact`),await F(()=>e.screenRecording.harmony.removeMedia(t,r))||i.push(`media-library artifact`),i.length===0?void 0:`HarmonyOS recording completed, but cleanup was not confirmed for the ${i.join(` and `)}.`}async function F(e){try{return await e()}catch{return!1}}function Ne(e,t){let n=[e,t].filter(e=>e!==void 0).join(` `);return n.length===0?{}:{warning:n}}async function Pe(e,t,n,r){let i;for(let a=0;a<40;a+=1){if(await e.screenRecording.harmony.remove(t,n.remotePath).catch(()=>{}),await e.screenRecording.harmony.stageMedia(t,{mediaUri:r,remotePath:n.remotePath})){let r=await e.screenRecording.harmony.stagedFileSize(t,n.remotePath);if(r!==void 0&&r>0&&r===i)return!0;i=r!==void 0&&r>0?r:void 0}else i=void 0;a<39&&await e.clock.sleep(250)}return!1}async function I(e,t,n,r=async()=>{R(await e.screenRecording.harmony.stop(t),`stop`)}){let i=[await L(r),await L(async()=>{if(!await e.screenRecording.harmony.remove(t,n.remotePath))throw Error(`HarmonyOS recording staging artifact removal was not confirmed`)}),await L(async()=>await Fe(e,t,n.fileName))].find(e=>e!==void 0);return i===void 0?{status:`cleaned`}:{status:`cleanup-pending`,reason:`transport-failed`,message:i instanceof Error?i.message:`HarmonyOS recording cleanup failed`}}async function Fe(e,t,n){let r=await e.screenRecording.harmony.findMedia(t,n);if(r&&!await e.screenRecording.harmony.removeMedia(t,r))throw Error(`HarmonyOS recording media removal was not confirmed`)}async function L(e){try{await e();return}catch(e){return e}}function R(e,t){if(e.exitCode===0&&e.stdout.includes(`start ability successfully`))return;let n=e.stdout.trim()||e.stderr.trim()||`hdc exit ${e.exitCode}`;throw Error(`failed to ${t} HarmonyOS screen recording: ${n}`)}async function Ie(e,t){t.throwIfAborted();let{runHarmonyShell:n}=await import(`./hdc.js`).then(e=>e.t),i=await n(e,[`aa`,`dump`,`-l`],{timeoutMs:15e3,signal:t});t.throwIfAborted();let a=Le(i.stdout);if(!a)throw new r(`COMMAND_FAILED`,`Could not determine the foreground HarmonyOS app`,{hint:`Open an app on the target, then retry appstate.`});return a}function Le(e){let t=e.split(/(?=^\s*Mission ID #)/m);for(let e of t){if(!/\bstate #FOREGROUND\b/.test(e))continue;let t=e.match(/mission name #\[#([^:]+):[^:]*:([^\]]+)]/);if(!t)continue;let[,n,r]=t;if(!(!n||!r))return{package:n,activity:r}}}const Re=Object.freeze({available:!0}),ze=Object.freeze({available:!1,reason:`unsupported-device-kind`}),z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function B(e){let t=e.kind===`emulator`||e.kind===`device`?Re:ze;return Object.freeze({deployApp:t,materializeAppSource:z,deployMaterializedApp:z,sendPushNotification:z,uninstallApp:t})}function Be(e){let t=B(e.device);return Object.freeze({...t.deployApp.available?{deployApp:async t=>await He(e.commands,e.device,t,e.signal)}:{},...t.uninstallApp.available?{uninstallApp:async t=>await Ve(e.commands,e.device,t,e.signal)}:{}})}async function Ve(e,t,n,i){let a=n.app.trim();if(!a)throw new r(`INVALID_ARGS`,`Uninstall requires a HarmonyOS bundle name`,{hint:`Pass the bundle name reported by bm dump, such as com.example.app.`});if(!(await V(e,t,i)).includes(a))return{wasInstalled:!1};let o=await H(e,t,[`bm`,`uninstall`,`-n`,a],i);if((await V(e,t,i)).includes(a))throw new r(`COMMAND_FAILED`,`${a} is still installed after bm uninstall`,{exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr,hint:`Read the bm uninstall output above for the bm reason; system and shared bundles refuse removal.`});return{wasInstalled:!0,packageName:a}}async function V(e,t,n){let a=await H(e,t,[`bm`,`dump`,`-a`],n,{allowFailure:!0,timeoutMs:15e3});if(a.exitCode!==0)throw new r(`COMMAND_FAILED`,`Could not read the installed bundle inventory`,i(a));let o=T(a.stdout);if(o.length===0)throw new r(`COMMAND_FAILED`,`Could not read the installed bundle inventory`,{exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr,hint:`Confirm the device connection, then check bm dump -a output on the device.`});return o}async function He(e,t,n,i){let a=await Ue(e,n.appPath,i)??n.app.trim();if(!a)throw new r(`INVALID_ARGS`,`Could not determine the bundle name from the HAP archive`,{hint:`Pass the HarmonyOS bundle name before the HAP path, or provide a valid HAP containing module.json.`});return await Ge(e,t,[`install`,`-r`,n.appPath],i,18e4),n.replaceExisting&&(await O(1e3,void 0,{signal:i}),await We(e,t,a,i)),{packageName:a,launchTarget:a}}async function Ue(e,t,n){let r=await e.run({executable:`unzip`,args:[`-p`,t,`module.json`],allowFailure:!0,timeoutMs:15e3},n);if(r.exitCode===0&&r.stdout.trim().length!==0)try{return JSON.parse(r.stdout).app?.bundleName?.trim()||void 0}catch{return}}async function We(e,t,n,i){let a=await H(e,t,[`bm`,`dump`,`-n`,n],i),o=E(a.stdout);if(!o)throw new r(`COMMAND_FAILED`,`Could not determine a launchable ability for ${n}`,{hint:`Check that the HarmonyOS bundle exposes a main ability.`});await H(e,t,[`aa`,`start`,`-b`,n,...o.module?[`-m`,o.module]:[],`-a`,o.ability],i)}async function Ge(e,t,n,r,i=15e3){return await e.run({executable:`hdc`,args:[`-t`,t.id,...n],timeoutMs:i},r)}async function H(e,t,n,r,i={}){return await e.run({executable:`hdc`,args:o(`hdc`,`shell`,n,[`-t`,t.id]),timeoutMs:i.timeoutMs??15e3,allowFailure:i.allowFailure},r)}const U=n(`harmonyos`),Ke=t(`unsupported-platform-leaf`,`HarmonyOS reads element text from the captured tree only.`),qe=t(`unsupported-device-kind`,`focus is supported on HarmonyOS emulators and physical devices.`),W=Object.freeze({available:!0}),G=t(`unsupported-platform-leaf`),Je=t(`unsupported-device-kind`,`HarmonyOS appstate is supported only for HarmonyOS emulators and devices.`),Ye=t(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),K=Object.freeze({available:!0}),Xe=t(`unsupported-device-kind`,`open is supported only for HarmonyOS emulators and devices.`),Ze=t(`unsupported-device-kind`,`close is supported only for HarmonyOS emulators and devices.`),Qe=t(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),q=t(`unsupported-device-kind`,`snapshot is supported only for HarmonyOS emulators and devices.`),$e=t(`unsupported-device-kind`,`screenshot is supported only for HarmonyOS emulators and devices.`),J=t(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),et=t(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web).`);function tt(e){let t=nt(e),n=rt(e);return d({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:G,clearRuntimeHints:G,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:Ye,configureProviderPortReverse:Qe})}function nt(e){return e.kind===`emulator`||e.kind===`device`?K:Xe}function rt(e){return e.kind===`emulator`||e.kind===`device`?K:Ze}const Y=t(`unsupported-device-kind`,`Gestures are supported on HarmonyOS emulators and physical devices.`),it=t(`unsupported-platform-leaf`),at=t(`unsupported-platform-leaf`,m);function X(e){return e.kind===`emulator`||e.kind===`device`?W:Y}function Z(e){return e.kind===`emulator`||e.kind===`device`?W:qe}const Q=t(`unsupported-platform-leaf`),ot=t(`unsupported-platform-leaf`,`HarmonyOS supports settings clear-app-state only.`),st=t(`unsupported-platform-leaf`,`keyboard status/get is not available through the public HarmonyOS HDC API; use keyboard dismiss or enter`),$=t(`unsupported-platform-leaf`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`);function ct(t){let n=M(t),r=async e=>{let t=await n.inspectFacts(e),r=B(e),i=De(e);return Object.freeze({device:t.device,operations:{...t.operations,...r,appState:e.kind===`simulator`?Je:W,networkDump:G,screenRecordingStart:i,screenRecordingReattach:i,screenRecordingCleanup:i,...le({capture:e.kind===`emulator`||e.kind===`device`?W:q,customActions:J,withoutActiveApp:e.kind===`emulator`||e.kind===`device`?W:q}),...ve({capture:e.kind===`emulator`||e.kind===`device`?W:$e}),...re({findText:q,querySelector:q}),...be({setViewport:et}),...oe({focus:Z(e)}),...ae({unsupported:Y,plan:X(e),directionalFling:X(e),multiTouch:it,targetAuthoredDrag:at,viewport:X(e)}),...ne({scroll:X(e)}),...te({type:Z(e)}),...p({unsupported:G,tap:Z(e),longPress:Z(e),fill:Z(e)}),...se({readTextAtPoint:Ke}),...ee({back:Z(e)}),...ce({unsupported:Q,home:Z(e),appSwitcher:Z(e)}),setFoldPose:Q,sendTelephonyEvent:Q,...me({triggerAppEvent:Q}),..._({target:Z(e),unsupported:ot,write:{"clear-app-state":W}}),...he({read:Q,wait:Q,accept:Q,dismiss:Q}),...de({orientation:Q}),...pe({tvRemote:Q}),...ue({unsupported:Q,status:st,dismiss:Z(e),enter:Z(e)}),...fe({unsupported:Q}),...ge({capture:$,query:$}),..._e({frames:Z(e),memorySample:Z(e),memorySnapshot:Z(e),nativeCapture:Q,profileReport:Q}),ensureReady:W,bootTarget:G,bootTargetHeadless:G,listApps:W,...tt(e),shutdownTarget:G}})};return Object.freeze({owner:U,ownsDevice:e=>e.platform===`harmonyos`,inspectFacts:r,bind:async i=>{let a=await n.bind(i),o=await r(i.device),s=o.operations.screenRecordingStart;return Object.freeze({device:a.device,owner:U,facts:o,operations:Object.freeze({...a.operations,...Be({commands:t.commands,device:i.device,signal:i.scope.signal}),...o.operations.appState.available?{appState:async()=>await Ie(i.device,i.scope.signal)}:{},ensureReady:async()=>({...i.device,booted:!0}),...s.available?Oe({host:t,device:i.device,owner:U,signal:i.scope.signal}):{},...o.operations.captureSnapshot.available?ie({device:i.device,signal:i.scope.signal,resolveInteractor:t.localInteractors.resolve}):{},...v({device:i.device,signal:i.scope.signal,resolveInteractor:t.localInteractors.resolve,facts:o.operations,captureCapabilities:ye(`a HarmonyOS device captures through hdc`),pause:async e=>await t.clock.sleep(e,i.scope.signal)}),...e(o.operations.perfFrames,()=>Ce({resolveHost:()=>t.perf.harmony,device:i.device})),listApps:async e=>{i.scope.signal.throwIfAborted();let{listHarmonyApps:t}=await import(`./app-lifecycle2.js`).then(e=>e.t);return(await t(e.device,e.filter,{signal:i.scope.signal})).map(e=>({id:e.package,name:e.name}))},...u(xe({owner:`HarmonyOS`,openTargetIdentity:`bundle-id`,host:t.localInteractors,device:i.device,signal:i.scope.signal}),o.operations)}),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>await n.shutdown()})}export{ct as createHarmonyPlatformRuntime};