agent-device 0.21.29 → 0.21.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.29.apk → agent-device-android-ime-helper-0.21.30.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.30.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.29.manifest.json → agent-device-android-ime-helper-0.21.30.manifest.json} +4 -4
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.29.manifest.json → agent-device-android-snapshot-helper-0.21.30.manifest.json} +7 -7
- package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift +4 -2
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift +2 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +12 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +25 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +8 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +9 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +3 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +35 -9
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +44 -26
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +20 -1
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentation.swift +4 -3
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationProjection.swift +4 -2
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFold.swift +20 -2
- package/dist/src/adapter.js +1 -1
- package/dist/src/agent-browser-lifecycle.js +1 -1
- package/dist/src/agent-browser-process-record.js +1 -1
- package/dist/src/agent-browser-provider.js +1 -1
- package/dist/src/agent-device-client.js +1 -1
- package/dist/src/alert2.js +1 -1
- package/dist/src/android.js +1 -1
- package/dist/src/app-lifecycle.js +1 -1
- package/dist/src/app-log-runtime2.js +3 -3
- package/dist/src/auth.js +1 -1
- package/dist/src/automation-helper.js +1 -1
- package/dist/src/back-mode.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +13 -10
- package/dist/src/cli.js +3 -3
- package/dist/src/client-types.d.ts +82 -13
- package/dist/src/cloud-artifacts.d.ts +99 -3
- package/dist/src/command-metadata.js +42 -42
- package/dist/src/composed-inventory-gateways.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection.js +1 -1
- package/dist/src/contract.d.ts +2 -2
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/daemon-client-ensure.js +1 -1
- package/dist/src/daemon-client-ensuring.js +1 -1
- package/dist/src/daemon-client-lease-beat.js +1 -1
- package/dist/src/daemon-client-lifecycle.js +1 -1
- package/dist/src/daemon-client.js +2 -2
- package/dist/src/daemon-lifecycle-errors.js +1 -1
- package/dist/src/daemon-registration-owner.js +3 -3
- package/dist/src/daemon-registration.js +1 -1
- package/dist/src/daemon-resolution.js +1 -1
- package/dist/src/daemon-shutdown-report.js +1 -1
- package/dist/src/daemon-startup-diagnostics.js +1 -1
- package/dist/src/daemon.js +3 -3
- package/dist/src/device-claim-recovery.js +1 -1
- package/dist/src/durable-capture-resource.js +1 -1
- package/dist/src/durable-resource.js +1 -1
- package/dist/src/ended-lease.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/gesture-plan-types.d.ts +14 -4
- package/dist/src/gesture-plan.js +1 -1
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/host4.js +1 -1
- package/dist/src/index.d.ts +3 -3
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions2.js +1 -1
- package/dist/src/interaction-positionals.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -1
- package/dist/src/interactor-operation-catalog.js +1 -1
- package/dist/src/interactor.js +5 -5
- package/dist/src/interactor3.js +1 -1
- package/dist/src/interactor4.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +1 -1
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/inventory6.js +1 -1
- package/dist/src/ios-node-interpretation.js +1 -1
- package/dist/src/ios-snapshot-acquisition.js +1 -1
- package/dist/src/ios-snapshot-engine.js +1 -1
- package/dist/src/ios-snapshot-runtime.js +1 -1
- package/dist/src/keyboard-occlusion.js +1 -1
- package/dist/src/launch-confirmation.js +1 -1
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease-registry-scope.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/local-interactor-operation-set.js +1 -1
- package/dist/src/mechanics.js +12 -12
- package/dist/src/metro-session-hints.js +1 -1
- package/dist/src/mobile-snapshot-semantics.js +1 -1
- package/dist/src/observability.js +1 -1
- package/dist/src/observation.js +1 -1
- package/dist/src/parameterized-recorded-fill.js +1 -1
- package/dist/src/perf-facade.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +1 -1
- package/dist/src/platform-runtime-unavailable.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -1
- package/dist/src/plugins2.js +1 -1
- package/dist/src/png-resize.js +1 -1
- package/dist/src/png-worker-client.js +1 -1
- package/dist/src/png-worker-contract.js +1 -1
- package/dist/src/provider-device-runtime.d.ts +20 -1
- package/dist/src/provider-plugin.d.ts +1 -1
- package/dist/src/react-native-overlay2.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/replay-maestro-backend.js +3 -3
- package/dist/src/replay-script-selection.js +1 -1
- package/dist/src/replay.d.ts +1 -1
- package/dist/src/request-runtime-binding.js +1 -1
- package/dist/src/result-serialization.js +1 -1
- package/dist/src/runner-error-classification.js +1 -1
- package/dist/src/runtime-admission.js +1 -1
- package/dist/src/runtime-deployment.js +1 -1
- package/dist/src/runtime-factory.js +1 -1
- package/dist/src/runtime-session.js +1 -1
- package/dist/src/runtime.js +5 -5
- package/dist/src/runtime10.js +2 -2
- package/dist/src/runtime3.js +5 -5
- package/dist/src/runtime5.js +1 -1
- package/dist/src/runtime6.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/runtime8.js +1 -1
- package/dist/src/runtime9.js +2 -2
- package/dist/src/screenshot-image-size.js +1 -0
- package/dist/src/screenshot-image.js +1 -1
- package/dist/src/screenshot-runtime.js +1 -1
- package/dist/src/screenshot3.js +2 -2
- package/dist/src/sdk-batch.js +1 -1
- package/dist/src/sdk-contracts.d.ts +7 -1
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-selectors.d.ts +1 -1
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selection.js +0 -0
- package/dist/src/selector-pipeline-policy.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server-startup.js +1 -1
- package/dist/src/session-replay-vars.js +1 -1
- package/dist/src/session-store.js +2 -2
- package/dist/src/session.js +1 -1
- package/dist/src/session2.js +5 -5
- package/dist/src/settle-observation-capture.js +1 -1
- package/dist/src/snapshot-capture-annotations.js +1 -1
- package/dist/src/snapshot-chrome.js +1 -1
- package/dist/src/snapshot-desktop-projection.js +1 -1
- package/dist/src/snapshot-helper-install.js +7 -5
- package/dist/src/snapshot-node-lookup.js +1 -1
- package/dist/src/snapshot-occlusion.js +1 -1
- package/dist/src/snapshot-runtime-binding.js +1 -1
- package/dist/src/snapshot-runtime-capture-input.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-state.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src3.js +1 -1
- package/dist/src/src4.js +1 -1
- package/dist/src/tap-keyboard-occlusion.js +1 -1
- package/dist/src/target-evidence-tree.js +1 -1
- package/dist/src/target-evidence.js +1 -1
- package/dist/src/telephony-runtime.js +1 -1
- package/dist/src/text-entry-focus.js +1 -1
- package/dist/src/touch-reference-frame.js +1 -1
- package/dist/src/touch-runtime2.js +1 -1
- package/dist/src/tree.js +1 -1
- package/dist/src/tv-remote-runtime.js +1 -1
- package/dist/src/tv-remote.js +2 -2
- package/dist/src/type-text-runtime.js +1 -1
- package/dist/src/video.js +1 -1
- package/dist/src/webdriver-source.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.29.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.29.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.29.apk.sha256 +0 -1
- package/dist/src/daemon-client-lifecycle-request.js +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime.js";import{R as t,et as n}from"./sdk-contracts.js";import{
|
|
2
|
-
`:``;
|
|
3
|
-
`)){if(!n.includes(`"startupPhase"`))continue;let e;try{e=JSON.parse(n)}catch{continue}let r=e.data?.startupPhase,i=e.data?.timestampMs;if(typeof r!=`string`||!
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{R as t,et as n}from"./sdk-contracts.js";import{D as r,V as i,b as a,c as o,d as s,et as c,gt as l,ht as u,j as d,k as f,lt as p,xt as m}from"./sdk-io.js";import"./diagnostics.js";import{i as ee,n as te,r as ne}from"./file.js";import"./command.js";import{m as h}from"./daemon-resolution.js";import"./retry.js";import{c as g,i as _,s as re}from"./daemon-registration.js";import{r as v,t as ie}from"./daemon-shutdown-report.js";import y from"node:fs";import b from"node:os";import x from"node:path";function S(e){return x.join(e,`repair-tombstone.json`)}function ae(e,t){try{let n=C(e);return n?.owner===t&&n.expiresAt>Date.now()?n:void 0}catch{return}}function oe(e,t){try{C(e)?.owner===t&&y.rmSync(e,{force:!0})}catch{}}function C(e){let t;try{t=y.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw e}return se(t,e)}function se(e,n){try{let t=JSON.parse(e);if(!ce(t))throw Error(`Invalid repair tombstone fields`);return t}catch(e){throw new t(`COMMAND_FAILED`,`Repair evidence could not be inspected.`,{reason:`repair_evidence_invalid`,path:n},e instanceof Error?e:void 0)}}function ce(e){let t=e;return Number.isFinite(t?.reapedAt)&&Number.isFinite(t?.expiresAt)&&typeof t?.owner==`string`&&(t.sourcePath===void 0||typeof t.sourcePath==`string`)&&le(t.commitFailure)}function le(e){let t=e;return e===void 0||typeof t?.code==`string`&&typeof t?.message==`string`}function ue(e){let t;try{t=y.readdirSync(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return;throw e}for(let n of t){if(!n.isDirectory())continue;let t=C(S(x.join(e,n.name)));if(t?.commitFailure&&t.expiresAt>Date.now())return{sessionName:n.name,tombstone:{...t,commitFailure:t.commitFailure}}}}async function w(e,t){let{logPath:n,command:r=`daemon`,debug:i=!0}=e;return await m({command:r,session:`daemon`,logPath:n,debug:i},async()=>{try{return await t()}finally{l({force:!0})}})}const de=[/\/dist\/src\/daemon\.js($|[\s"'])/,/\/dist\/src\/internal\/daemon\.js($|[\s"'])/,/\/src\/daemon\.ts($|[\s"'])/];function fe(e){let t=e.toLowerCase().replaceAll(`\\`,`/`);return de.some(e=>e.test(t))}function pe(e,t){if(!t||!a(e))return!1;let n=d(e);if(!n||n!==t)return!1;let r=f(e);return r?fe(r):!1}function T(e,t){try{return process.kill(e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}async function E(e,t){if(!o(e.pid))return{exited:!1,elapsedMs:0};let n=Date.now(),s=n+t.timeoutMs,c=t.pollMs??100,l=()=>{if(!a(e.pid))return!0;let t=r([e.pid]).get(e.pid);return!!(t?.state.startsWith(`Z`)||t?.startTime&&t.startTime!==e.startTime)},u=l();for(;!u&&Date.now()<s;)await i(Math.min(c,Math.max(0,s-Date.now()))),u=l();return{exited:u,elapsedMs:Date.now()-n}}async function D(e,t){if(!o(e.pid))return{status:`retained`,reason:`identity-unverified`};if(!e.startTime?.trim())return a(e.pid)?{status:`retained`,reason:`missing-start-time`}:{status:`not-running`};let n={pid:e.pid,startTime:e.startTime};if((await E(n,{timeoutMs:0})).exited)return{status:`exited`,identity:n,mode:`already-exited`};let r;if(t.mode===`graceful`){let e=await O(n,{signal:`SIGTERM`,timeoutMs:t.termTimeoutMs});if(e.status!==`survived`)return e;r=`SIGTERM`}let i=await O(n,{signal:`SIGKILL`,timeoutMs:t.killTimeoutMs,previousSignal:r});return i.status===`survived`?{status:`retained`,reason:`exit-timeout`}:i}async function O(e,t){let n=pe(e.pid,e.startTime),r=n&&T(e.pid,t.signal),i=r?t.signal===`SIGTERM`?`graceful`:`forced`:t.previousSignal?`graceful`:`already-exited`;return(await E(e,{timeoutMs:i===`already-exited`?0:t.timeoutMs})).exited?{status:`exited`,identity:e,mode:i}:r?{status:`survived`}:{status:`retained`,signal:t.signal,reason:n?`signal-failed`:`identity-unverified`}}const k=Object.freeze([`modules-loaded`,`composition-loaded`,`lock-acquired`,`recovery-finished`,`listening`,`registered`]),A=new Set(k),j=/^daemon-startup-phases-(\d*)\.jsonl$/;function M(e,t){return x.join(e,`daemon-startup-phases-${t}.jsonl`)}function N(e,t,r){try{let n=Date.now();y.mkdirSync(x.dirname(e),{recursive:!0});let r=P(e)?`
|
|
2
|
+
`:``;y.appendFileSync(e,`${r}${JSON.stringify({data:{startupPhase:t,timestampMs:n}})}\n`)}catch(e){r?.(n(e))}}function P(e){let t;try{let n=y.statSync(e);if(n.size===0)return!1;let r=Buffer.alloc(1);return t=y.openSync(e,`r`),y.readSync(t,r,0,1,n.size-1)===1&&r[0]!==10}catch{return!1}finally{t!==void 0&&y.closeSync(t)}}function F(e,t){try{y.rmSync(e,{force:!0})}catch(e){t?.(n(e))}}function I(e){let t;try{t=y.readdirSync(e)}catch{return}for(let n of t){let t=j.exec(n);if(t===null)continue;let r=Number(t[1]);r!==process.pid&&(!Number.isSafeInteger(r)||r<=0||!a(r))&&F(x.join(e,n))}}function L(e){let t={};for(let n of e.split(`
|
|
3
|
+
`)){if(!n.includes(`"startupPhase"`))continue;let e;try{e=JSON.parse(n)}catch{continue}let r=e.data?.startupPhase,i=e.data?.timestampMs;if(typeof r!=`string`||!A.has(r)||typeof i!=`number`||!Number.isFinite(i))continue;let a=t[r];(a===void 0||i<a)&&(t[r]=i)}return t}var R=e({DAEMON_STARTUP_EXIT_CODES:()=>z,createOwnedReplayStateDir:()=>W,launchDaemonProcess:()=>G,recoverAbandonedDaemonRegistration:()=>Y,stopAndRetireDaemon:()=>q,tryAcquireDaemonRegistration:()=>B});const z=Object.freeze({busy:75,unproven:78});async function B(e){let t={...e},n=s(),r=ee({lockDirPath:t.lockPath,owner:{...n,acquiredAtMs:Date.now()},description:`daemon registration`});if(r.status!==`acquired`)return r;let{acquisition:i}=r;try{i.assertHeld(),y.rmSync(v(t.baseDir),{force:!0}),I(t.baseDir)}catch(e){await H(i,e,t.logPath)}let a;return{status:`acquired`,owner:Object.freeze({publish({socketPort:e,httpPort:r,...o}){i.assertHeld(),me(t.logPath);let s=e&&r?`dual`:r?`http`:`socket`;i.assertHeld(),p({destination:t.infoPath,contents:JSON.stringify({...o,port:e,httpPort:r,transport:s,pid:n.pid,processStartTime:n.startTime??void 0,stateDir:t.baseDir},null,2),mode:384}),a={ownership:o.ownership}},async finish(e,r){let s;try{i.assertHeld(),s=r?.retainRegistration?{state:`retained`}:V(t.infoPath,n,i)}catch(n){if(await o(e),a?.ownership===`embedded`)throw n;return await H(i,n,t.logPath)}let c=s.state===`removed`||s.state===`absent`;return await o(e),s.state!==`retained`&&(c||a?.ownership!==`embedded`)&&await i.release(),s}})};async function o(e){if(e)try{i.assertHeld(),p({destination:v(t.baseDir),contents:`${JSON.stringify(ie(e))}\n`,mode:384})}catch(e){await Q(t.logPath,`daemon_shutdown_record_failed`,e).catch(()=>{})}}}function V(e,t,n){n.assertHeld();let r=g(e,t);if(r.state!==`match`)return r;n.assertHeld();try{y.unlinkSync(e)}catch(e){if(e.code!==`ENOENT`)throw e}return{state:`removed`}}async function H(e,t,n){try{await e.release()}catch(e){await Q(n,`daemon_registration_release_failed`,e).catch(()=>{})}throw t}function me(e){if(process.platform===`win32`){he(e);return}let t=y.openSync(e,`a`,384);try{y.ftruncateSync(t,0)}finally{y.closeSync(t)}}function he(e){let t;try{t=y.openSync(e,`r+`,384)}catch(n){if(n.code!==`ENOENT`)throw n;y.closeSync(y.openSync(e,`a`,384)),t=y.openSync(e,`r+`,384)}try{y.ftruncateSync(t,0)}finally{y.closeSync(t)}}const U=new WeakMap;function W(){let e=Object.freeze(h(y.mkdtempSync(x.join(b.tmpdir(),`agent-device-replay-daemon-`)))),t=Object.freeze({paths:e});return U.set(t,{paths:e,startups:[],sealed:!1}),t}function G(e){let n=e.ownedStateDir&&K(e.ownedStateDir,e.paths);if(n?.sealed)throw new t(`COMMAND_FAILED`,`Replay daemon startup admission is closed.`,{reason:`daemon_startup_admission_closed`});y.mkdirSync(e.paths.baseDir,{recursive:!0});let r=y.openSync(e.paths.logPath,`a`);try{let t=c(process.execPath,e.args,{cwd:e.cwd,env:{...e.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode},stdio:[`ignore`,r,r]}),i={...e.paths},a={launch:Object.freeze({...t,get startTime(){return a.startTime},readIdentity(){return ge(i,a),{pid:t.pid,startTime:a.startTime??null}}}),joined:!1};return n&&n.startups.push(a),t.exited.then(()=>{a.joined=!0}),a.startTime=d(t.pid)??void 0,a.launch}finally{y.closeSync(r)}}function ge(e,t){if(t.startTime||t.joined)return;let n=re(e.infoPath);if(n?.pid!==t.launch.pid||!n.startTime)return;let r=ne(e.lockPath);_(r,n)&&(t.startTime=n.startTime)}function K(e,n){let r=U.get(e);if(!r||Object.entries(r.paths).some(([e,t])=>n[e]!==t))throw new t(`COMMAND_FAILED`,`Private replay directory ownership could not be verified.`,{reason:`daemon_private_state_unowned`});return r}async function q(e){let t,r=e.observed;try{if(e.ownedStateDir&&(t=K(e.ownedStateDir,e.paths),t.sealed=!0,r=_e(t,r),t.retirement))return await t.retirement}catch(r){return await $(t,e.startupJoinTimeoutMs??1e3),{status:`retained`,reason:`ownership-unproven`,removedInfo:!1,error:n(r)}}let i=r?.ownership,a=Z({...e,observed:r},r&&i!==`detached`?e=>X(e,i===`embedded`?`embedded-owner`:`owner-unproven`):t=>D(t,{mode:e.mode,termTimeoutMs:e.termTimeoutMs??3e3,killTimeoutMs:e.killTimeoutMs??1e3}),t,e.startupJoinTimeoutMs??1e3);t&&(t.retirement=a);let o=await a;return t&&(o.status===`absent`||!o.removedStateDir)&&(t.retirement=void 0),o}function _e(e,t){if(!t){if(e.startups.length===0)return null;throw J()}let n=e.startups.find(({launch:e})=>e.pid===t.pid);if(!n)throw J();let{launch:r}=n,i=t.startTime?t:{...t,...r.readIdentity()};if(r.startTime&&r.startTime===i.startTime)return i;throw J()}function J(){return new t(`COMMAND_FAILED`,`The observed daemon is not an owned startup lifetime.`,{reason:`daemon_private_startup_unowned`})}async function Y(e){return await Z(e,e=>X(e))}function ve(e){return e===`embedded-owner`||e===`owner-unproven`}async function X(e,t=`identity-unverified`){if(!e.startTime?.trim())return{status:`retained`,reason:t===`identity-unverified`?`missing-start-time`:t};let n={pid:e.pid,startTime:e.startTime};return(await E(n,{timeoutMs:0})).exited?{status:`exited`,identity:n,mode:`already-exited`}:{status:`retained`,reason:t}}async function Z(e,t,r,i=1e3){let a={...e.paths},o=e.observed&&{...e.observed},s,c;if(o)try{s=await t(o)}catch(e){c=n(e)}let l=await $(r,i);return c?{status:`retained`,reason:`stop-failed`,removedInfo:!1,error:c}:s?.status===`retained`&&ve(s.reason)?{status:`retained`,reason:s.reason,termination:s,removedInfo:!1}:s&&s.status!==`exited`?{status:`retained`,reason:`exit-unconfirmed`,termination:s,removedInfo:!1}:l?await ye({...e,paths:a},s,r):{status:`retained`,reason:`startup-unconfirmed`,termination:s,removedInfo:!1}}async function ye(e,t,r){let i=e.paths,a;try{a=await te({lockDirPath:i.lockPath,owner:{...s(),acquiredAtMs:Date.now()},description:`daemon registration retirement`,timeoutMs:e.lockTimeoutMs??1e3})}catch(e){let r=n(e);return{status:`retained`,reason:r.details?.reason===`process_lock_timeout`?`lock-busy`:`retirement-unconfirmed`,termination:t,removedInfo:!1,error:r}}let o={status:`retained`,reason:`retirement-unconfirmed`,removedInfo:!1};try{o=xe(V(i.infoPath,t?.identity??null,a),t),o=Se(r,a,o)}catch(e){o={status:`retained`,reason:`retirement-unconfirmed`,termination:t,removedInfo:o.removedInfo,error:n(e)}}return await be(a,o,i.logPath)}async function be(e,t,r){try{await e.release()}catch(e){let i=t.status===`retained`?t.error:void 0;i&&await Q(r,`daemon_retirement_release_failed`,e),t={...t,status:`retained`,reason:`retirement-unconfirmed`,error:i??n(e)}}return t}function xe(e,t){return t&&(e.state===`removed`||e.state===`absent`)?{status:`retired`,termination:t,removedInfo:e.state===`removed`}:e.state===`absent`?{status:`absent`,removedInfo:!1}:{status:`retained`,termination:t,removedInfo:!1,reason:e.state===`replaced`?`registration-replaced`:e.state===`unreadable`?`metadata-unreadable`:`ownership-unproven`}}async function Q(e,t,r){await w({logPath:e},()=>{u({level:`warn`,phase:t,data:{error:n(r)}})})}async function $(e,t){if(!e||e.startups.every(e=>e.joined))return!0;let n;try{return await Promise.race([Promise.all(e.startups.map(({launch:e})=>e.exited)).then(()=>!0),new Promise(e=>{n=setTimeout(()=>e(!1),t)})])}finally{n&&clearTimeout(n)}}function Se(e,t,r){if(!e||r.status!==`retired`&&(r.status!==`absent`||e.startups.length!==0))return r;try{t.assertHeld();let n=ue(e.paths.sessionsDir);return n?r.status===`retired`?{...r,removedStateDir:!1,repairCommitFailure:n}:{status:`retained`,reason:`retirement-unconfirmed`,removedInfo:!1,removedStateDir:!1,repairCommitFailure:n}:(t.assertHeld(),y.rmSync(e.paths.baseDir,{recursive:!0,force:!0}),{...r,removedStateDir:!0})}catch(e){return{...r,status:`retained`,reason:`retirement-unconfirmed`,removedStateDir:!1,error:n(e)}}}export{Y as a,L as c,M as d,E as f,S as g,ae as h,G as i,N as l,oe as m,W as n,q as o,w as p,R as r,B as s,z as t,F as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as e,c as t,j as n,l as r,u as i}from"./sdk-io.js";import{d as a,f as o,
|
|
1
|
+
import{b as e,c as t,j as n,l as r,u as i}from"./sdk-io.js";import{d as a,f as o,m as s,p as c}from"./daemon-resolution.js";function l(e){let t=d(e);return t.status===`present`?t.identity:null}function u(e,t){return e.state===`held`&&typeof t.startTime==`string`&&t.startTime.trim().length>0&&i(e.owner,t)}function d(e){let t=o(e);if(t.status!==`present`)return{status:t.status};let n=f(t.record);return{status:`present`,record:t.record,identity:n.pid===null?null:{pid:n.pid,startTime:n.startTime},ownership:a(t.record.ownership)}}function f(e){let n=e.pid;return t(n)?{pid:n,startTime:g(e.processStartTime)}:{pid:null,startTime:null}}function p(e,t){let n=d(e);return n.status===`present`?n.identity?t?r(n.identity,t)?{state:`replaced`,identity:n.identity}:i(n.identity,t)&&n.identity.startTime!==null?{state:`match`}:{state:`unproven`}:{state:`unproven`}:{state:`ownerless`}:{state:n.status===`invalid`?`ownerless`:n.status}}function m(e){return e.state===`unreadable`||e.state===`invalid`}function h(t){let i={stateDir:t.baseDir},a=d(t.infoPath);if(a.status!==`present`)return a.status===`absent`?{state:`stopped`,...i}:{state:a.status,...i};let{record:o}=a;if(a.identity===null)return{state:`stopped`,...i};let s=a.identity;if(s.startTime===null||!e(s.pid)||r(s,{pid:s.pid,startTime:n(s.pid)}))return{state:`stopped`,...i};let l=c(o.transport);return{state:`running`,stateDir:t.baseDir,pid:s.pid,ownership:a.ownership,...typeof o.version==`string`?{version:o.version}:{},...l?{transport:l}:{},plugins:o.plugins}}function g(e){return typeof e==`string`&&e.trim().length>0?e:null}function _(e){let t=d(e);return t.status===`present`?{ownership:t.ownership,identity:t.identity}:{ownership:t.status===`absent`?`absent`:`unreadable`,identity:null}}function v(e){return!e.identity||e.ownership===`absent`||e.ownership===`unreadable`?null:{...e.identity,ownership:e.ownership}}function y(e){return e.ownership!==`detached`||!e.identity?.startTime?null:{pid:e.identity.pid,processStartTime:e.identity.startTime}}function b(e){if(e.pid===process.pid)return!1;let t=l(s(e.stateDir).infoPath);return t!==null&&r(t,e)}export{h as a,p as c,u as i,y as l,m as n,_ as o,v as r,l as s,b as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{R as e}from"./sdk-contracts.js";import{c as t,o as n}from"./file.js";import{c as r,r as i}from"./version.js";import a from"node:crypto";import o from"node:fs";import s from"node:path";function c(e,t={}){let n=l(e,t);return{baseDir:n,infoPath:s.join(n,`daemon.json`),lockPath:s.join(n,`daemon.lock`),logPath:s.join(n,`daemon.log`),allocationsDir:s.join(n,`allocations`),sessionsDir:s.join(n,`sessions`)}}function l(r,i){let a=(r??``).trim();if(!a)return u(i);let o=n(a,{env:i.env});if(s.isAbsolute(o))return o;if(i.cwd===void 0)throw new e(`INVALID_ARGS`,`State dir "${a}" is relative and no working directory was given.`,{reason:`relative_state_dir_without_cwd`});return t(a,{env:i.env,cwd:i.cwd})}function u(e={}){let t=s.join(n(`~`,{env:e.env}),`.agent-device`),a=e.projectRoot??i();return r(a)?s.join(t,`dev`,d(a)):t}function d(e){let t=f(e),n=s.basename(t).replaceAll(/[^a-zA-Z0-9._-]+/g,`-`),r=a.createHash(`sha1`).update(t).digest(`hex`).slice(0,12);return`${n||`agent-device`}-${r}`}function f(e){try{return o.realpathSync.native(e)}catch{return s.resolve(e)}}function p(e){let t;try{t=o.readFileSync(e,`utf8`)}catch(e){let t=e?.code;return{status:t===`ENOENT`||t===`ENOTDIR`?`absent`:`unreadable`}}try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{status:`present`,record:e}:{status:`invalid`}}catch{return{status:`invalid`}}}function m(e){return e===`socket`||e===`http`||e===`dual`?e:void 0}function h(e){let t=(e??``).trim().toLowerCase();return t===`http`?`http`:t===`dual`?`dual`:`socket`}function g(e){let t=(e??``).trim().toLowerCase();return t===`auto`?`auto`:t===`socket`?`socket`:t===`http`?`http`:`auto`}const _=[`quiesce`],v=[`detached`,`embedded`,`unknown`];function y(e){return v.includes(e)?e:e===void 0?`detached`:`unknown`}const b
|
|
1
|
+
import{R as e}from"./sdk-contracts.js";import{c as t,o as n}from"./file.js";import{c as r,r as i}from"./version.js";import a from"node:crypto";import o from"node:fs";import s from"node:path";function c(e,t={}){let n=l(e,t);return{baseDir:n,infoPath:s.join(n,`daemon.json`),lockPath:s.join(n,`daemon.lock`),logPath:s.join(n,`daemon.log`),allocationsDir:s.join(n,`allocations`),sessionsDir:s.join(n,`sessions`)}}function l(r,i){let a=(r??``).trim();if(!a)return u(i);let o=n(a,{env:i.env});if(s.isAbsolute(o))return o;if(i.cwd===void 0)throw new e(`INVALID_ARGS`,`State dir "${a}" is relative and no working directory was given.`,{reason:`relative_state_dir_without_cwd`});return t(a,{env:i.env,cwd:i.cwd})}function u(e={}){let t=s.join(n(`~`,{env:e.env}),`.agent-device`),a=e.projectRoot??i();return r(a)?s.join(t,`dev`,d(a)):t}function d(e){let t=f(e),n=s.basename(t).replaceAll(/[^a-zA-Z0-9._-]+/g,`-`),r=a.createHash(`sha1`).update(t).digest(`hex`).slice(0,12);return`${n||`agent-device`}-${r}`}function f(e){try{return o.realpathSync.native(e)}catch{return s.resolve(e)}}function p(e){let t;try{t=o.readFileSync(e,`utf8`)}catch(e){let t=e?.code;return{status:t===`ENOENT`||t===`ENOTDIR`?`absent`:`unreadable`}}try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{status:`present`,record:e}:{status:`invalid`}}catch{return{status:`invalid`}}}function m(e){return e===`socket`||e===`http`||e===`dual`?e:void 0}function h(e){let t=(e??``).trim().toLowerCase();return t===`http`?`http`:t===`dual`?`dual`:`socket`}function g(e){let t=(e??``).trim().toLowerCase();return t===`auto`?`auto`:t===`socket`?`socket`:t===`http`?`http`:`auto`}const _=[`quiesce`],v=[`detached`,`embedded`,`unknown`];function y(e){return v.includes(e)?e:e===void 0?`detached`:`unknown`}const b=`daemon_quiesce`,x=`daemon_shutting_down`,S={busy:`daemon-busy`,instanceMismatch:`daemon-instance-mismatch`,ownerEmbedded:`daemon-owner-embedded`},C=`daemon-owner-unrecognized`;function w(e){let{token:t,fence:n,requestId:r}=e;return{token:t,session:`default`,command:b,positionals:[],input:{pid:n.pid,processStartTime:n.processStartTime},meta:{requestId:r}}}function T(e){if(typeof e!=`object`||!e)return;let{pid:t,processStartTime:n}=e;if(Number.isInteger(t)&&(n===null||typeof n==`string`))return{pid:t,processStartTime:n}}function E(e){return Array.isArray(e)?_.filter(t=>e.includes(t)):[]}function D(e){if(typeof e!=`object`||!e)return;let{startingUp:t,inFlightRequests:n,sessions:r,repairSessions:i,leases:a}=e;if((t===void 0||typeof t==`boolean`)&&[n,r,i,a].every(e=>Number.isSafeInteger(e)&&e>=0))return{startingUp:t===!0,inFlightRequests:n,sessions:r,repairSessions:i,leases:a}}function O(e){return`${e===void 0?`The runtime is owned by its host process.`:`The runtime is owned by host process ${e}.`} Close it there with the handle returned by startAgentDevice(). Recovery with daemon stop or ensureDaemon() for this state directory retires the abandoned registration only when the recorded host lifetime has provably exited.`}export{x as a,E as c,y as d,p as f,g,h,C as i,D as l,c as m,S as n,w as o,m as p,b as r,O as s,_ as t,T as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"node:fs";import t from"node:path";function n(e){return{providerReleases:{released:e.providerReleases.released.map(a),pending:e.providerReleases.pending.map(a)},claims:{released:[...e.claims.released],orphaned:[...e.claims.orphaned],superseded:[...e.claims.superseded],unattributable:[...e.claims.unattributable]}}}function r(t){try{let n=JSON.parse(e.readFileSync(i(t),`utf8`));return o(n)?{providerReleases:n.providerReleases,claims:s(n)}:null}catch{return null}}function i(e){return t.join(e,`daemon-shutdown.json`)}function a(e){return{leaseId:e.leaseId,...e.leaseProvider?{provider:e.leaseProvider}:{}}}function o(e){if(!e||typeof e!=`object`)return!1;let t=e.providerReleases;if(!t||typeof t!=`object`)return!1;let n=t;return Array.isArray(n.released)&&Array.isArray(n.pending)&&n.released.every(u)&&n.pending.every(u)}function s(e){let t=e.claims;if(!t||typeof t!=`object`)return{released:[],orphaned:[],superseded:[],unattributable:[]};let n=t;return{released:c(n.released),orphaned:c(n.orphaned),superseded:c(n.superseded),unattributable:c(n.unattributable)}}function c(e){return Array.isArray(e)?e.filter(l):[]}function l(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.deviceKey==`string`&&typeof t.session==`string`&&typeof t.platform==`string`&&typeof t.deviceId==`string`}function u(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.leaseId==`string`&&t.leaseId.trim().length>0&&(t.provider===void 0||typeof t.provider==`string`)}export{r as n,i as r,n as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{et as e}from"./sdk-contracts.js";import{ht as t}from"./sdk-io.js";import"./diagnostics.js";import{n}from"./verified-file.js";import"./file.js";import{
|
|
1
|
+
import{et as e}from"./sdk-contracts.js";import{ht as t}from"./sdk-io.js";import"./diagnostics.js";import{n}from"./verified-file.js";import"./file.js";import{p as r}from"./daemon-registration-owner.js";import{c as i}from"./daemon-registration.js";const a=Object.freeze({match:!1,replaced:!0,absent:!0,unreadable:!1,ownerless:!1,unproven:!1});function o(e){let t=i(e.infoPath,e.owner);if(a[t.state]&&!(t.state===`absent`&&c(e.stateDir)))return t.state===`replaced`?{state:`replaced`,registeredPid:t.identity.pid}:{state:`absent`}}function s(e){let t,n=()=>{t&&=(clearInterval(t),void 0)};return t=setInterval(()=>{if(c(e.stateDir)){n();return}let t=o(e);t&&(n(),e.onLoss(t))},15e3),t.unref?.(),n}function c(e){try{return n(e)===void 0}catch{return!1}}async function l(e,n){n.length!==0&&await r({logPath:e,command:`daemon-startup`,debug:!1},()=>{for(let e of n)t({level:`warn`,phase:e.phase,data:{resourcePath:e.resourcePath,...e.data}})})}async function u(e,n,i){await r({logPath:e},()=>{t({level:`warn`,phase:n,data:i})})}async function d(t){try{let e=await t.registration.finish(t.outcome,t.close);e.state!==`removed`&&e.state!==`absent`&&await u(t.logPath,`daemon_info_removal_declined`,{infoPath:t.infoPath,removed:!1,reason:e.state,...e.state===`replaced`?{registeredPid:e.identity.pid}:{}})}catch(n){await u(t.logPath,`daemon_registration_finish_failed`,{error:e(n)})}}function f(e,t,n,r){return s({infoPath:t,stateDir:e,owner:r,onLoss:e=>void u(n,`daemon_metadata_lost`,{infoPath:t,...e}).catch(()=>{})})}export{f as armDaemonMetadataLossWatch,u as emitDaemonDiagnostic,d as finishDaemonRegistration,l as flushDaemonStartupDiagnostics};
|
package/dist/src/daemon.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{R as e}from"./sdk-contracts.js";import{
|
|
2
|
-
`)}function
|
|
3
|
-
`)}export{
|
|
1
|
+
import{R as e}from"./sdk-contracts.js";import{i as t,m as n,n as r,s as i}from"./daemon-resolution.js";import{c as a}from"./device-shell.js";import{a as o,l as s,n as c,o as l,r as u}from"./daemon-registration.js";import{n as d}from"./daemon-shutdown-report.js";import{i as f}from"./plugin-inventory.js";import{n as p}from"./shared.js";async function m(e){let t=e.observed;if(!t)return _();let{stopAndRetireDaemon:n}=await import(`./daemon-registration-owner.js`).then(e=>e.r),r=await n({paths:e.paths,observed:t,mode:`graceful`,termTimeoutMs:e.graceTimeoutMs??1e4,killTimeoutMs:e.killTimeoutMs??2e3});if(r.status===`retained`&&r.termination?.status===`not-running`)return _();if(r.status!==`retired`)throw g(t,r);return r.termination.mode===`already-exited`?_():r.termination.mode===`graceful`?{stopped:!0,mode:`graceful`,cleanupConfidence:`known`,claimsReleased:[],claimsOrphaned:[],claimsSuperseded:[],claimsUnattributable:[],providerReleases:{status:`completed`,released:[],pending:[]},warnings:[]}:{stopped:!0,mode:`forced`,cleanupConfidence:`unknown`,claimsReleased:[],claimsOrphaned:[],claimsSuperseded:[],claimsUnattributable:[],providerReleases:{status:`unknown`,released:[],pending:null},warnings:[`The daemon was force-killed before provider lease state could be finalized. Provider allocations may remain active.`]}}function h(e,n){return e===`embedded-owner`?{reason:r.ownerEmbedded,hint:i(n)}:{reason:t,hint:`Nothing was signaled. Check what owns that process, then repair the record: stop it by its own means and remove its daemon.json so a daemon can register again.`}}function g(t,n){let r=n.status===`retained`?n.termination:void 0,i=r?.status===`retained`?r:void 0,{hint:a,diagnosticId:o,logPath:s}=(n.status===`retained`?n.error:void 0)??{},c=n.status===`retained`&&(n.reason===`embedded-owner`||n.reason===`owner-unproven`)?h(n.reason,t.pid):void 0;return new e(`COMMAND_FAILED`,c?`The daemon was not stopped, because its owner ends it.`:`Daemon retirement could not be confirmed.`,{pid:t.pid,processStartTime:t.startTime,reason:c?.reason??(i?`daemon_exit_unconfirmed`:`daemon_retirement_unconfirmed`),terminationReason:i?.reason,signal:i?.signal,retirement:n,hint:a??c?.hint,diagnosticId:o,logPath:s})}function _(){return{stopped:!1,mode:`not-running`,cleanupConfidence:`known`,claimsReleased:[],claimsOrphaned:[],claimsSuperseded:[],claimsUnattributable:[],providerReleases:{status:`completed`,released:[],pending:[]},warnings:[]}}function v(e,t){return e.mode!==`graceful`||t?t?{...e,providerReleases:{status:`completed`,...t.providerReleases},claimsReleased:t.claims.released,claimsOrphaned:t.claims.orphaned,claimsSuperseded:t.claims.superseded,claimsUnattributable:t.claims.unattributable,warnings:[...e.warnings,...y(t.claims.superseded),...b(t.claims.orphaned),...x(t.claims.unattributable)]}:e:{...e,cleanupConfidence:`unknown`,providerReleases:{status:`unknown`,released:[],pending:null},warnings:[...e.warnings,`The graceful shutdown report is unavailable, so provider cleanup state is unknown. Provider allocations may remain active.`]}}function y(e){return e.length===0?[]:[`Another owner had already claimed ${e.map(e=>e.deviceId).join(`, `)} before this daemon released it, so those devices are now owned elsewhere.`]}function b(e){return e.length===0?[]:[`Ownership of ${e.map(e=>e.deviceId).join(`, `)} was not released cleanly; the claim now blocks other owners until it is settled. Inspect with: agent-device device status --stale, then release with: agent-device device release --stale.`]}function x(e){return e.length===0?[]:[`A claim for ${e.map(e=>e.deviceId).join(`, `)} remains whose owner could not be read, so this daemon cannot say whether those devices are free. No device release route settles it: --stale proves staleness from the recorded owner and refuses records that name none, and open refuses to overwrite them. Inspect with: agent-device device status.`]}function S(e){return Object.freeze({cleanup:async t=>{let{setAppleRunnerHostEnvironment:n}=await import(`./runner-owner-facade.js`);n(e);let{cleanupRunnerLeasesForOwner:r}=await import(`./runner-operations-facade.js`);await r(t)}})}async function C(e,t){if(e.ownership===`unreadable`)throw w(t.paths);let n=await m({paths:t.paths,observed:u(e)});return v(n,n.mode===`graceful`?d(t.paths.baseDir):null)}function w(t){return new e(`COMMAND_FAILED`,`The daemon record on ${t.baseDir} cannot be read, so this stop cannot tell whether a daemon runs.`,{reason:`daemon-record-unreadable`,stateDir:t.baseDir,hint:`Nothing was signaled. Inspect or remove that record, then retry.`})}const T=async({positionals:t,flags:r,host:i})=>{let a=S(i),c=t[0];if(c!==`stop`&&c!==`status`||t.length!==1)throw new e(`INVALID_ARGS`,`daemon accepts only: stop, status`);let u=n(r.stateDir,{cwd:i.cwd,env:i.env});if(c===`status`){let e=o(u),t={...e,plugins:f(e.plugins)};return await p(r,t,()=>k(t)),!0}let d=l(u.infoPath);if(r.clean===!0&&d.ownership!==`absent`&&d.ownership!==`detached`)throw E(u,d);let m=await C(d,{paths:u,host:i}),h=s(d),g=r.clean===!0&&h!==null&&m.stopped;g&&await a.cleanup({pid:h.pid,startTime:h.processStartTime});let _={...m,clean:g};return await p(r,_,()=>O(_)),!0};function E(t,n){return new e(`COMMAND_FAILED`,`This daemon record does not prove the process is a daemon of its own, so its retained-runner cleanup cannot be run from here.`,{reason:`daemon-clean-not-detached`,stateDir:t.baseDir,ownership:n.ownership,hint:D(t,n)})}function D(e,t){return t.ownership===`unreadable`?`Nothing was signaled. Check what owns that process, then repair the record: stop it by its own means and remove ${a(`${e.baseDir}/daemon.json`)} so a daemon can register again.`:h(t.ownership===`embedded`?`embedded-owner`:`owner-unproven`,t.identity?.pid).hint}function O(e){return[e.stopped?`Daemon stopped (${e.mode}).`:`No running daemon found.`,e.clean?`Retained runner cleanup completed.`:null,...e.warnings].filter(e=>!!e).join(`
|
|
2
|
+
`)}function k(e){return c(e)?`The daemon record for ${e.stateDir} is ${e.state===`invalid`?`not a valid record`:`unreadable`}, so whether a daemon runs there is unknown.`:e.state===`stopped`?`No running daemon for ${e.stateDir}.`:[`Daemon running (${[`pid ${e.pid}`,e.ownership===`embedded`?`host-owned`:e.ownership===`unknown`?`owner-not-recognized`:null,e.version,e.transport].filter(Boolean).join(`, `)}) for ${e.stateDir}.`,...e.plugins.length===0?[`No providers registered.`]:[`Providers:`,...e.plugins.map(e=>{let t=e.package?`${e.package}${e.version?`@${e.version}`:``}`:e.source,n=e.state===`active`?`active`:`failed: ${e.error?.message??`unknown`}`;return` ${e.provider??`(unknown provider)`} [${e.source}] ${t} - ${n}`})]].join(`
|
|
3
|
+
`)}export{T as daemonCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{R as e}from"./sdk-contracts.js";import{ht as t,i as n}from"./sdk-io.js";import"./diagnostics.js";import{R as r}from"./sdk-device.js";import{At as i,M as a,Mt as o,Nt as s,O as ee,Pt as te,Qt as c,ht as l,jt as u,kt as d}from"./sdk-batch.js";import{m as f}from"./observability.js";import{r as p}from"./session-paths.js";import{a as m,i as h,r as ne}from"./session-artifact-paths.js";import{p as g}from"./daemon-resolution.js";import{n as _,t as v}from"./durable-capture-resource.js";import{n as y}from"./screen-recording-runtime.js";import b from"node:path";const x=_({resourceKind:`app-log`,fileName:`app-log.resource.json`,displayName:`App-log`}),S=v({resourceKind:`app-log`,displayName:`app-log`,store:x,completionMetadata:e=>({backend:e.backend,outputPath:e.outputPath,completedAt:e.completedAt}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no app log stream active`,cleanupPendingHint:`Keep app-log.resource.json and retry cleanup through its exact runtime owner.`}});async function C(e){let t;try{return t=await e.gateway.bind({device:w(e.envelope),intent:{kind:`exact-owner`,owner:e.envelope.owner,fence:e.envelope.fence},scope:e.scope}),e.scope.signal.throwIfAborted(),e.create(t)}catch(e){throw t&&await t[Symbol.asyncDispose](),e}}function w(e){return{platform:e.device.family,id:e.device.id,name:e.device.id,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.appleOs===void 0?{}:{appleOs:e.device.appleOs},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}}}const T=l({required:[`appLogReattach`,`appLogCleanup`]});function E(e){return S.recoverAll({sessionsDir:e.sessionsDir,...O(e)})}function D(e){return S.recoverOne({sessionsDir:e.sessionsDir,...O(e)},e.resourcePath)}function O(e){return{scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await k(e.gateway,t,n)}}async function k(e,t,n){return await C({gateway:e,envelope:t,scope:n,create:e=>{let t=c(e,T);return Object.freeze({reattach:async e=>await t.operations.appLogReattach({envelope:e}),cleanup:async e=>await t.operations.appLogCleanup({envelope:e}),[Symbol.asyncDispose]:async()=>await e[Symbol.asyncDispose]()})}})}const A=_({resourceKind:`audio-probe`,fileName:`audio-probe.resource.json`,displayName:`Audio probe`}),j=v({resourceKind:`audio-probe`,displayName:`audio probe`,store:A,completionMetadata:e=>({backend:e.backend??`unknown`,source:e.source,durationMs:e.durationMs,elapsedMs:e.elapsedMs,bucketMs:e.bucketMs,sampleCount:e.sampleCount,heard:e.heard}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no active audio probe`,cleanupPendingHint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`}});function M(e){return j.adoptStarted(e)}function N(e){return j.finishLive(e)}function P(e){return j.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await F(e.gateway,t,n)},e.resourcePath)}async function F(e,t,n){return await C({gateway:e,envelope:t,scope:n,create:e=>I({runtime:c(e,a),dispose:async()=>await e[Symbol.asyncDispose]()})})}function I(e){return Object.freeze({reattach:async t=>await e.runtime.operations.audioProbeReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.audioProbeCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}function L(e){if(e.area===`frames`)return Object.freeze({kind:`frames`,request:e,use:d});if(e.area===`memory`)return e.action===`snapshot`?Object.freeze({kind:`memory-snapshot`,request:e,use:u}):Object.freeze({kind:`memory-sample`,request:e,use:i});if(e.area===`trace`)return e.action===`start`?Object.freeze({kind:`capture-start`,request:e,use:s}):Object.freeze({kind:`capture-stop`,request:e});switch(e.action){case`start`:return Object.freeze({kind:`capture-start`,request:e,use:s});case`stop`:return Object.freeze({kind:`capture-stop`,request:e});case`report`:return Object.freeze({kind:`profile-report`,request:e,use:te})}}function R(t){let n=t.positionals??[],r=n[0]?.toLowerCase();if(r===`frames`){let i=n[1]?.toLowerCase();if(i!==void 0&&i!==`sample`||n.length>2||t.kind!==void 0)throw new e(`INVALID_ARGS`,`perf action must be frames, memory sample|snapshot, cpu profile start|stop|report, or trace start|stop`);return Object.freeze({area:r,action:`sample`})}if(r===`memory`)return z(n,t);if(r===`cpu`)return B(n,t.outPath);if(r===`trace`)return V(n,t.outPath);throw new e(`INVALID_ARGS`,`perf requires frames, memory, cpu, or trace`)}function z(t,n){let r=(t[1]??`sample`).toLowerCase();if(r!==`sample`&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(n.kind!==void 0&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(r===`sample`&&t.length>2)throw new e(`INVALID_ARGS`,`perf memory sample does not accept additional positionals`);if(r===`snapshot`&&t.length>3)throw new e(`INVALID_ARGS`,`perf memory snapshot accepts at most one positional kind`);let i=n.kind??t[2];if(i!==void 0&&!f(i))throw new e(`INVALID_ARGS`,`perf memory snapshot --kind must be android-hprof or memgraph`);return Object.freeze({area:`memory`,action:r,...i===void 0?{}:{kind:i},...n.outPath===void 0?{}:{outPath:n.outPath}})}function B(t,n){if(t[1]?.toLowerCase()!==`profile`)throw new e(`INVALID_ARGS`,`perf cpu requires profile`);let r=t[2]?.toLowerCase();if(r!==`start`&&r!==`stop`&&r!==`report`)throw new e(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`);let i=t[3]?.toLowerCase();if(i!==`xctrace`&&i!==`simpleperf`)throw new e(`INVALID_ARGS`,`perf cpu profile requires --kind xctrace or simpleperf`);let a=n??t[5];return Object.freeze({area:`cpu`,subject:`profile`,action:r,kind:i,...t[4]?{template:t[4]}:{},...a?{outPath:a}:{},...t[6]?{tracePath:t[6]}:{}})}function V(t,n){let r=t[1]?.toLowerCase();if(r!==`start`&&r!==`stop`)throw new e(`INVALID_ARGS`,`perf trace action must be start or stop`);let i=t[2]?.toLowerCase();if(i!==`xctrace`&&i!==`perfetto`)throw new e(`INVALID_ARGS`,`perf trace requires --kind xctrace or perfetto`);let a=n??t[4];return Object.freeze({area:`trace`,action:r,kind:i,...t[3]?{template:t[3]}:{},...a?{outPath:a}:{}})}const re=_({resourceKind:`perf-capture`,fileName:`perf-capture.resource.json`,displayName:`Perf capture`}),H=v({resourceKind:`perf-capture`,displayName:`perf capture`,store:re,completionMetadata:e=>({kind:typeof e.kind==`string`?e.kind:`unknown`,mode:typeof e.mode==`string`?e.mode:`unknown`,...typeof e.outPath==`string`?{outPath:e.outPath}:{}}),failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active native perf capture`,cleanupPendingHint:`Keep perf-capture.resource.json and retry stop through its exact runtime owner.`}});function U(e){return H.adoptStarted(e)}function W(e){return H.finishLive(e)}function G(e){return H.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await K(e.gateway,t,n)},e.resourcePath)}async function K(e,t,n){return await C({gateway:e,envelope:t,scope:n,create:e=>q({runtime:c(e,o),dispose:async()=>await e[Symbol.asyncDispose]()})})}function q(e){return Object.freeze({reattach:async t=>await e.runtime.operations.perfNativeCaptureReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.perfNativeCaptureCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}const J=_({resourceKind:y,fileName:`screen-recording.resource.json`,displayName:`screen recording`}),Y=v({resourceKind:`screen-recording`,displayName:`screen recording`,store:J,completionMetadata:ae,failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active recording`,cleanupPendingHint:`Keep screen-recording.resource.json and retry stop through its exact runtime owner.`}});function X(e){return Y.adoptStarted(e)}function ie(e){return Y.finishLive(e)}const Z=`completion`;function ae(e){return{[Z]:{backend:e.backend,outPath:e.outPath,startedAt:e.startedAt,completedAt:e.completedAt,...e.capturedDurationMs===void 0?{}:{capturedDurationMs:e.capturedDurationMs},...e.stopObservation===void 0?{}:{stopObservation:se(e.stopObservation)},...e.nativePathDisposition===void 0?{}:{nativePathDisposition:e.nativePathDisposition},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath},...e.telemetryPath===void 0?{}:{telemetryPath:e.telemetryPath},...e.warning===void 0?{}:{warning:e.warning},...e.overlayWarning===void 0?{}:{overlayWarning:e.overlayWarning},...e.activeSessionApp===void 0?{}:{activeSessionApp:oe(e.activeSessionApp)},...e.chunks===void 0?{}:{chunks:e.chunks.map(ce)}}}}function oe(e){return{bundleId:e.bundleId,...e.name===void 0?{}:{name:e.name}}}function se(e){return e.recorder===`confirmed`?{recorder:e.recorder}:{recorder:e.recorder,why:e.why}}function ce(e){return{index:e.index,path:e.path,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath}}}function le(e){return Y.finishRecovered(e)}function ue(e){return Y.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await de(e.gateway,t,n)},e.resourcePath)}async function de(e,t,n){return await C({gateway:e,envelope:t,scope:n,create:e=>Q({runtime:c(e,ee),dispose:async()=>await e[Symbol.asyncDispose]()})})}function Q(e){return Object.freeze({reattach:async t=>await e.runtime.operations.screenRecordingReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.screenRecordingCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}function fe(e){return async n=>{let r=g(n.stateDir).sessionsDir,i=b.join(r,p(n.session));try{for(let t of Object.values(pe)){let a=$(t,n,i);if(a.status===`retained`)return{status:`retained`,reason:a.reason};if(a.status===`owned`&&await t.recover(e,r,a.resourcePath)===`retained`)return{status:`retained`,reason:`${t.resourceKind}-cleanup-pending`}}return{status:`reconciled`}}catch(e){return t({level:`warn`,phase:`device_claim_orphan_reconciliation_failed`,data:{deviceKey:n.deviceKey,ownerSession:n.session,error:e instanceof Error?e.message:String(e)}}),{status:`retained`,reason:`durable-resource-reconciliation-failed`}}}}const pe={"app-log":{resourceKind:`app-log`,store:S.store,recover:async(e,t,n)=>await D({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"screen-recording":{resourceKind:`screen-recording`,store:Y.store,recover:async(e,t,n)=>await ue({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"audio-probe":{resourceKind:`audio-probe`,store:j.store,recover:async(e,t,n)=>await P({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"perf-capture":{resourceKind:`perf-capture`,store:H.store,recover:async(e,t,n)=>await G({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})}};function $(e,t,n){let i=e.store.resolvePath(n),a=e.store.read(i);return a.status===`missing`?{status:`missing`}:a.status===`unreattachable`?{status:`retained`,reason:`${e.resourceKind}-${a.reason}`}:a.envelope.sessionId!==t.session||!r(a.envelope.device,t.device)?{status:`retained`,reason:`${e.resourceKind}-owner-mismatch`}:{status:`owned`,resourcePath:i}}function me(e){let t=e.composeRecovery??(t=>he(t,e.scope,e.composeGateway));return async e=>{let n=t(e.stateDir);try{return await n.reconcile(e)}finally{await n.dispose()}}}function he(e,t,r){let i=g(e),a=r({sessionsDir:i.sessionsDir,ownedProcesses:n({stateDir:i.baseDir,sessionsDir:i.sessionsDir,resolveSessionDir:e=>m(i.sessionsDir,e)}),resolveSessionArtifacts:e=>({outputPath:ne(i.sessionsDir,e),pidPath:h(i.sessionsDir,e)})});return{reconcile:fe({gateway:a,scope:t}),dispose:async()=>{await a.shutdown()}}}const ge=new AbortController().signal;function _e(){return Object.freeze({signal:ge,diagnostics:Object.freeze({emit:e=>t(e)}),progress:Object.freeze({report:()=>{}})})}export{E as _,X as a,Y as c,H as d,R as f,N as g,j as h,Z as i,U as l,M as m,me as n,ie as o,L as p,Q as r,le as s,_e as t,W as u,S as v,x as y};
|
|
1
|
+
import{R as e}from"./sdk-contracts.js";import{ht as t,i as n}from"./sdk-io.js";import"./diagnostics.js";import{R as r}from"./sdk-device.js";import{At as i,M as a,Mt as o,Nt as s,O as ee,Pt as te,ht as c,jt as l,kt as u,tn as d}from"./sdk-batch.js";import{m as f}from"./observability.js";import{r as p}from"./session-paths.js";import{a as m,i as h,r as ne}from"./session-artifact-paths.js";import{m as g}from"./daemon-resolution.js";import{n as _,t as v}from"./durable-capture-resource.js";import{n as y}from"./screen-recording-runtime.js";import b from"node:path";const x=_({resourceKind:`app-log`,fileName:`app-log.resource.json`,displayName:`App-log`}),S=v({resourceKind:`app-log`,displayName:`app-log`,store:x,completionMetadata:e=>({backend:e.backend,outputPath:e.outputPath,completedAt:e.completedAt}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no app log stream active`,cleanupPendingHint:`Keep app-log.resource.json and retry cleanup through its exact runtime owner.`}});async function C(e){let t;try{return t=await e.gateway.bind({device:w(e.envelope),intent:{kind:`exact-owner`,owner:e.envelope.owner,fence:e.envelope.fence},scope:e.scope}),e.scope.signal.throwIfAborted(),e.create(t)}catch(e){throw t&&await t[Symbol.asyncDispose](),e}}function w(e){return{platform:e.device.family,id:e.device.id,name:e.device.id,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.appleOs===void 0?{}:{appleOs:e.device.appleOs},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}}}const T=c({required:[`appLogReattach`,`appLogCleanup`]});function E(e){return S.recoverAll({sessionsDir:e.sessionsDir,...O(e)})}function D(e){return S.recoverOne({sessionsDir:e.sessionsDir,...O(e)},e.resourcePath)}function O(e){return{scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await k(e.gateway,t,n)}}async function k(e,t,n){return await C({gateway:e,envelope:t,scope:n,create:e=>{let t=d(e,T);return Object.freeze({reattach:async e=>await t.operations.appLogReattach({envelope:e}),cleanup:async e=>await t.operations.appLogCleanup({envelope:e}),[Symbol.asyncDispose]:async()=>await e[Symbol.asyncDispose]()})}})}const A=_({resourceKind:`audio-probe`,fileName:`audio-probe.resource.json`,displayName:`Audio probe`}),j=v({resourceKind:`audio-probe`,displayName:`audio probe`,store:A,completionMetadata:e=>({backend:e.backend??`unknown`,source:e.source,durationMs:e.durationMs,elapsedMs:e.elapsedMs,bucketMs:e.bucketMs,sampleCount:e.sampleCount,heard:e.heard}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no active audio probe`,cleanupPendingHint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`}});function M(e){return j.adoptStarted(e)}function N(e){return j.finishLive(e)}function P(e){return j.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await F(e.gateway,t,n)},e.resourcePath)}async function F(e,t,n){return await C({gateway:e,envelope:t,scope:n,create:e=>I({runtime:d(e,a),dispose:async()=>await e[Symbol.asyncDispose]()})})}function I(e){return Object.freeze({reattach:async t=>await e.runtime.operations.audioProbeReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.audioProbeCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}function L(e){if(e.area===`frames`)return Object.freeze({kind:`frames`,request:e,use:u});if(e.area===`memory`)return e.action===`snapshot`?Object.freeze({kind:`memory-snapshot`,request:e,use:l}):Object.freeze({kind:`memory-sample`,request:e,use:i});if(e.area===`trace`)return e.action===`start`?Object.freeze({kind:`capture-start`,request:e,use:s}):Object.freeze({kind:`capture-stop`,request:e});switch(e.action){case`start`:return Object.freeze({kind:`capture-start`,request:e,use:s});case`stop`:return Object.freeze({kind:`capture-stop`,request:e});case`report`:return Object.freeze({kind:`profile-report`,request:e,use:te})}}function R(t){let n=t.positionals??[],r=n[0]?.toLowerCase();if(r===`frames`){let i=n[1]?.toLowerCase();if(i!==void 0&&i!==`sample`||n.length>2||t.kind!==void 0)throw new e(`INVALID_ARGS`,`perf action must be frames, memory sample|snapshot, cpu profile start|stop|report, or trace start|stop`);return Object.freeze({area:r,action:`sample`})}if(r===`memory`)return z(n,t);if(r===`cpu`)return B(n,t.outPath);if(r===`trace`)return V(n,t.outPath);throw new e(`INVALID_ARGS`,`perf requires frames, memory, cpu, or trace`)}function z(t,n){let r=(t[1]??`sample`).toLowerCase();if(r!==`sample`&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(n.kind!==void 0&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(r===`sample`&&t.length>2)throw new e(`INVALID_ARGS`,`perf memory sample does not accept additional positionals`);if(r===`snapshot`&&t.length>3)throw new e(`INVALID_ARGS`,`perf memory snapshot accepts at most one positional kind`);let i=n.kind??t[2];if(i!==void 0&&!f(i))throw new e(`INVALID_ARGS`,`perf memory snapshot --kind must be android-hprof or memgraph`);return Object.freeze({area:`memory`,action:r,...i===void 0?{}:{kind:i},...n.outPath===void 0?{}:{outPath:n.outPath}})}function B(t,n){if(t[1]?.toLowerCase()!==`profile`)throw new e(`INVALID_ARGS`,`perf cpu requires profile`);let r=t[2]?.toLowerCase();if(r!==`start`&&r!==`stop`&&r!==`report`)throw new e(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`);let i=t[3]?.toLowerCase();if(i!==`xctrace`&&i!==`simpleperf`)throw new e(`INVALID_ARGS`,`perf cpu profile requires --kind xctrace or simpleperf`);let a=n??t[5];return Object.freeze({area:`cpu`,subject:`profile`,action:r,kind:i,...t[4]?{template:t[4]}:{},...a?{outPath:a}:{},...t[6]?{tracePath:t[6]}:{}})}function V(t,n){let r=t[1]?.toLowerCase();if(r!==`start`&&r!==`stop`)throw new e(`INVALID_ARGS`,`perf trace action must be start or stop`);let i=t[2]?.toLowerCase();if(i!==`xctrace`&&i!==`perfetto`)throw new e(`INVALID_ARGS`,`perf trace requires --kind xctrace or perfetto`);let a=n??t[4];return Object.freeze({area:`trace`,action:r,kind:i,...t[3]?{template:t[3]}:{},...a?{outPath:a}:{}})}const re=_({resourceKind:`perf-capture`,fileName:`perf-capture.resource.json`,displayName:`Perf capture`}),H=v({resourceKind:`perf-capture`,displayName:`perf capture`,store:re,completionMetadata:e=>({kind:typeof e.kind==`string`?e.kind:`unknown`,mode:typeof e.mode==`string`?e.mode:`unknown`,...typeof e.outPath==`string`?{outPath:e.outPath}:{}}),failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active native perf capture`,cleanupPendingHint:`Keep perf-capture.resource.json and retry stop through its exact runtime owner.`}});function U(e){return H.adoptStarted(e)}function W(e){return H.finishLive(e)}function G(e){return H.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await K(e.gateway,t,n)},e.resourcePath)}async function K(e,t,n){return await C({gateway:e,envelope:t,scope:n,create:e=>q({runtime:d(e,o),dispose:async()=>await e[Symbol.asyncDispose]()})})}function q(e){return Object.freeze({reattach:async t=>await e.runtime.operations.perfNativeCaptureReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.perfNativeCaptureCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}const J=_({resourceKind:y,fileName:`screen-recording.resource.json`,displayName:`screen recording`}),Y=v({resourceKind:`screen-recording`,displayName:`screen recording`,store:J,completionMetadata:ae,failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active recording`,cleanupPendingHint:`Keep screen-recording.resource.json and retry stop through its exact runtime owner.`}});function X(e){return Y.adoptStarted(e)}function ie(e){return Y.finishLive(e)}const Z=`completion`;function ae(e){return{[Z]:{backend:e.backend,outPath:e.outPath,startedAt:e.startedAt,completedAt:e.completedAt,...e.capturedDurationMs===void 0?{}:{capturedDurationMs:e.capturedDurationMs},...e.stopObservation===void 0?{}:{stopObservation:se(e.stopObservation)},...e.nativePathDisposition===void 0?{}:{nativePathDisposition:e.nativePathDisposition},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath},...e.telemetryPath===void 0?{}:{telemetryPath:e.telemetryPath},...e.warning===void 0?{}:{warning:e.warning},...e.overlayWarning===void 0?{}:{overlayWarning:e.overlayWarning},...e.activeSessionApp===void 0?{}:{activeSessionApp:oe(e.activeSessionApp)},...e.chunks===void 0?{}:{chunks:e.chunks.map(ce)}}}}function oe(e){return{bundleId:e.bundleId,...e.name===void 0?{}:{name:e.name}}}function se(e){return e.recorder===`confirmed`?{recorder:e.recorder}:{recorder:e.recorder,why:e.why}}function ce(e){return{index:e.index,path:e.path,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath}}}function le(e){return Y.finishRecovered(e)}function ue(e){return Y.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await de(e.gateway,t,n)},e.resourcePath)}async function de(e,t,n){return await C({gateway:e,envelope:t,scope:n,create:e=>Q({runtime:d(e,ee),dispose:async()=>await e[Symbol.asyncDispose]()})})}function Q(e){return Object.freeze({reattach:async t=>await e.runtime.operations.screenRecordingReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.screenRecordingCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}function fe(e){return async n=>{let r=g(n.stateDir).sessionsDir,i=b.join(r,p(n.session));try{for(let t of Object.values(pe)){let a=$(t,n,i);if(a.status===`retained`)return{status:`retained`,reason:a.reason};if(a.status===`owned`&&await t.recover(e,r,a.resourcePath)===`retained`)return{status:`retained`,reason:`${t.resourceKind}-cleanup-pending`}}return{status:`reconciled`}}catch(e){return t({level:`warn`,phase:`device_claim_orphan_reconciliation_failed`,data:{deviceKey:n.deviceKey,ownerSession:n.session,error:e instanceof Error?e.message:String(e)}}),{status:`retained`,reason:`durable-resource-reconciliation-failed`}}}}const pe={"app-log":{resourceKind:`app-log`,store:S.store,recover:async(e,t,n)=>await D({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"screen-recording":{resourceKind:`screen-recording`,store:Y.store,recover:async(e,t,n)=>await ue({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"audio-probe":{resourceKind:`audio-probe`,store:j.store,recover:async(e,t,n)=>await P({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"perf-capture":{resourceKind:`perf-capture`,store:H.store,recover:async(e,t,n)=>await G({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})}};function $(e,t,n){let i=e.store.resolvePath(n),a=e.store.read(i);return a.status===`missing`?{status:`missing`}:a.status===`unreattachable`?{status:`retained`,reason:`${e.resourceKind}-${a.reason}`}:a.envelope.sessionId!==t.session||!r(a.envelope.device,t.device)?{status:`retained`,reason:`${e.resourceKind}-owner-mismatch`}:{status:`owned`,resourcePath:i}}function me(e){let t=e.composeRecovery??(t=>he(t,e.scope,e.composeGateway));return async e=>{let n=t(e.stateDir);try{return await n.reconcile(e)}finally{await n.dispose()}}}function he(e,t,r){let i=g(e),a=r({sessionsDir:i.sessionsDir,ownedProcesses:n({stateDir:i.baseDir,sessionsDir:i.sessionsDir,resolveSessionDir:e=>m(i.sessionsDir,e)}),resolveSessionArtifacts:e=>({outputPath:ne(i.sessionsDir,e),pidPath:h(i.sessionsDir,e)})});return{reconcile:fe({gateway:a,scope:t}),dispose:async()=>{await a.shutdown()}}}const ge=new AbortController().signal;function _e(){return Object.freeze({signal:ge,diagnostics:Object.freeze({emit:e=>t(e)}),progress:Object.freeze({report:()=>{}})})}export{E as _,X as a,Y as c,H as d,R as f,N as g,j as h,Z as i,U as l,M as m,me as n,ie as o,L as p,Q as r,le as s,_e as t,W as u,S as v,x as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{R as e,q as t}from"./sdk-contracts.js";import{ct as n,ht as r}from"./sdk-io.js";import"./diagnostics.js";import{F as i,I as a,R as o}from"./sdk-device.js";import{en as s}from"./sdk-batch.js";import{i as c}from"./verified-file.js";import"./file.js";import{r as l}from"./session-paths.js";import{n as u,r as d,t as f}from"./durable-resource.js";import ee from"node:crypto";import p from"node:fs";import m from"node:path";function h(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function g(e){return e.replaceAll(`-`,`_`)}async function te(e,t,n){let r={kind:`pending`};try{t.binding.assertAdoptable();let i=w(S(e,t),`active`);e.store.write(n,i),r={kind:`persisted`},t.throwIfCanceled();let a=t.pendingHandle.transfer();r={kind:`transferred`,handle:a},t.binding.adopt({handle:a,envelope:i})}catch(i){throw await _(e,t,n,r,i),i}}async function _(e,t,n,r,i){let a=t.binding.canPersist(),o=r.kind!==`pending`||a&&b(e,t,n),s=v(e,t,n,await y(t,r));t.reportUndurableCleanup(t.device,!o&&s.cleanupError===void 0||s.confirmed?{confirmed:!0}:{confirmed:!1,reason:s.cleanupError instanceof Error?s.cleanupError.message:`The durable cleanup transition could not be confirmed`}),s.cleanupError!==void 0&&C(e,t,i,s.cleanupError)}function v(e,t,n,i){try{return{confirmed:ie(e,n,t.fence,i),cleanupError:i}}catch(n){return r({level:`error`,phase:`${g(e.resourceKind)}_pending_adoption_transition_failed`,data:{session:t.binding.address,transitionError:n instanceof Error?n.message:String(n)}}),{confirmed:!1,cleanupError:i??n}}}async function y(e,t){try{t.kind===`transferred`?await t.handle[Symbol.asyncDispose]():await e.pendingHandle[Symbol.asyncDispose]();return}catch(e){return e}}function b(e,t,n){try{return e.store.write(n,ne(e,t)),!0}catch(i){try{return e.store.write(n,x(e,t,{version:0,body:{reason:`runtime-contract-invalid`}})),!0}catch(n){return r({level:`error`,phase:`${g(e.resourceKind)}_runtime_contract_tombstone_failed`,data:{session:t.binding.address,descriptorError:i instanceof Error?i.message:String(i),persistenceError:n instanceof Error?n.message:String(n)}}),!1}}}function ne(e,t){try{return w(S(e,t),`active`)}catch{return x(e,t,t.envelope.descriptor)}}function x(e,t,n){return u({resourceKind:e.resourceKind,sessionId:t.binding.address,device:i(t.device),owner:t.owner,fence:t.fence,lifecycle:`open`,descriptor:n,metadata:{phase:`runtime-contract-invalid`,runtimeContractInvalid:!0}})}function S(t,n){let r=d(n.envelope);if(r.status===`decoded`&&re(r.envelope,n,t.resourceKind))return r.envelope;throw new e(`COMMAND_FAILED`,`${h(t.displayName)} runtime returned an incoherent durable envelope`,{reason:`runtime-contract-invalid`,hint:`Retain the runtime diagnostics and report the selected device and owner.`})}function re(e,t,n){return e.resourceKind===n&&e.sessionId===t.binding.address&&o(e.device,i(t.device))&&s(e.owner)===s(t.owner)&&e.fence.token===t.fence.token&&e.fence.generation===t.fence.generation&&e.lifecycle===`open`}function ie(e,t,n,r){let i=e.store.read(t);return i.status!==`decoded`||i.envelope.fence.token!==n.token||i.envelope.fence.generation!==n.generation?!1:(e.store.write(t,{...i.envelope,lifecycle:r===void 0?`completed`:`open`,metadata:{...i.envelope.metadata??{},phase:r===void 0?`completed`:`cleanup-pending`,cleanupStatus:r===void 0?`cleaned`:`cleanup-pending`}}),!0)}function C(e,t,n,i){r({level:`error`,phase:`${g(e.resourceKind)}_pending_adoption_cleanup_failed`,data:{session:t.binding.address,primaryError:n instanceof Error?n.message:String(n),cleanupError:i instanceof Error?i.message:String(i)}})}function w(e,t){return Object.freeze({...e,lifecycle:`open`,metadata:{...e.metadata??{},phase:t}})}async function T(e){e.scope.signal.throwIfAborted();let t=new AbortController,n={...e.scope,signal:AbortSignal.any([e.scope.signal,t.signal])},r=()=>{},i=new Promise((e,t)=>{r=t}),a=()=>{},o=new Promise((t,n)=>{let r=()=>{try{e.scope.signal.throwIfAborted()}catch(e){n(e)}};if(e.scope.signal.aborted){r();return}e.scope.signal.addEventListener(`abort`,r,{once:!0}),a=()=>e.scope.signal.removeEventListener(`abort`,r)}),s=setTimeout(()=>{let n=new k(e.displayName,e.deadlineMs);t.abort(n),r(n)},e.deadlineMs);s.unref?.();let c=D(e,n),l,u=c.then(e=>(l??={kind:`acquisition`},e),e=>{throw l??={kind:`acquisition-error`},e}),d=i.catch(e=>{throw l??={kind:`deadline`,error:e},e}),f=o.catch(e=>{throw l??={kind:`cancellation`,error:e},e});try{return await Promise.race([u,d,f])}finally{if(clearTimeout(s),a(),l?.kind===`deadline`||l?.kind===`cancellation`){let t=l.error;c.then(n=>E(e,n,t),()=>{}).catch(()=>{})}else c.catch(()=>{})}}async function E(e,t,n){try{t.reattached.status===`active`&&await O(e,t.reattached.handle,`late_handle_cleanup_failed`,n)}finally{await O(e,t.control,`late_control_cleanup_failed`,n)}}async function D(e,t){let n,r;try{return n=await e.acquireControl(e.envelope,t),t.signal.throwIfAborted(),r=await n.reattach(e.envelope),t.signal.throwIfAborted(),{control:n,reattached:r}}catch(t){try{r?.status===`active`&&await O(e,r.handle,`late_handle_cleanup_failed`,t)}finally{n&&await O(e,n,`late_control_cleanup_failed`,t)}throw t}}async function O(e,t,n,r){try{await t[Symbol.asyncDispose]()}catch(t){e.onLateCleanupFailure(n,t,r)}}var k=class extends Error{deadlineMs;constructor(e,t){super(`${h(e)} recovery exceeded its ${t}ms deadline`),this.name=`DurableCaptureRecoveryDeadlineError`,this.deadlineMs=t}};const A=new Map;async function j(e){return await oe(e.resourcePath,async()=>{let t=e.store.read(e.resourcePath);if(t.status!==`decoded`)throw M(e.store,t.status===`missing`?`${e.store.displayName} resource record is missing`:`${e.store.displayName} resource record is unreattachable: ${t.message}`);if(!ae(t.envelope.fence,e.expected))throw M(e.store,`${e.store.displayName} resource ownership fence was lost`);let n=t.envelope;return await e.run({get envelope(){return n},transition(t,r={}){return n=Object.freeze({...n,lifecycle:t,...r.descriptor===void 0?{}:{descriptor:r.descriptor},...r.metadata===void 0?{}:{metadata:r.metadata}}),e.store.write(e.resourcePath,n),n}})})}function ae(e,t){return e.token===t.token&&e.generation===t.generation}async function oe(e,t){let n=A.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);A.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),A.get(e)===a&&A.delete(e)}}function M(t,n){return new e(`COMMAND_FAILED`,n,{reason:`ownership-fence-lost`,retriable:!1,hint:`Use the current ${t.displayName.toLowerCase()} resource owner or retain the recovery record for manual recovery.`})}async function se(t,n,r){let i=n.binding.read();if(!i)throw new e(`INVALID_ARGS`,t.messages.noActive);try{let e=await N(t,{handle:i.handle,fence:i.envelope.fence,resourcePath:r,intent:n.intent});return n.binding.clear(i),e}catch(e){let a=t.store.read(r);throw a.status===`decoded`&&a.envelope.lifecycle===`completed`&&n.binding.clear(i),e}}async function N(e,t){return await j({store:e.store,resourcePath:t.resourcePath,expected:t.fence,run:async n=>{W(n);let r=U(n),i;try{i=await t.handle.finish(r)}catch(r){throw await P(e,n,t,r,t.intent),r}if(i.status===`completed`)return H(e,n,i),i.result;H(e,n,i);let a=V(e,i);throw await P(e,n,t,a,t.intent),a}})}async function P(e,t,n,r,i){if(i===`capture`&&e.failedFinishPolicy===`preserve-retry-material`){I(e,n,r);return}let a;try{a=await n.handle.forceCleanup()}catch(i){L(e,n,r,i,F(t,i));return}try{z(t,a)}catch(t){L(e,n,r,a.status===`cleanup-pending`?a.message??a.reason:`cleanup returned ${a.status}`,t);return}f(a)||L(e,n,r,a.message)}function F(e,n){try{z(e,{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:t(n)});return}catch(e){return e}}function I(e,n,i){r({level:`error`,phase:`${g(e.resourceKind)}_finish_evidence_preserved`,data:{resourcePath:n.resourcePath,finishError:t(i),failedFinishPolicy:e.failedFinishPolicy}})}function L(e,n,i,a,o){r({level:`error`,phase:`${g(e.resourceKind)}_finish_cleanup_failed`,data:{resourcePath:n.resourcePath,finishError:t(i),cleanupError:a===void 0?`cleanup could not be confirmed`:t(a),...o===void 0?{}:{transitionError:t(o)}}})}async function R(e,t){let n=t.binding.read();n&&(B(e,await j({store:e.store,resourcePath:t.resourcePath,expected:n.envelope.fence,run:async e=>{W(e);let t=await n.handle.forceCleanup();return z(e,t),t}})),t.binding.clear(n))}function z(e,t){e.transition(f(t)?`completed`:`open`,{metadata:{...e.envelope.metadata??{},phase:f(t)?`completed`:`cleanup-pending`,cleanupStatus:t.status,...t.status===`cleanup-pending`?{cleanupPendingReason:t.reason,...t.message?{cleanupPendingMessage:t.message}:{}}:{}}})}function B(e,t){if(!f(t))throw V(e,t)}function V(t,n){return new e(`COMMAND_FAILED`,n.message??`${h(t.displayName)} cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:t.messages.cleanupPendingHint})}function H(e,t,n){if(n.status===`completed`){t.transition(`completed`,{metadata:{...t.envelope.metadata??{},...e.completionMetadata(n.result),phase:`completed`}});return}z(t,n)}function U(e){return Object.freeze({learned:e.envelope.metadata,record:t=>{e.transition(`open`,{metadata:{...e.envelope.metadata??{},...t}})}})}function W(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}async function G(e){let t=e.definition.store.list(e.sessionsDir),n=[];for(let r of t)n.push(await K(e,r));return{scanned:t.length,recovered:n.filter(e=>e===`recovered`).length,retained:n.filter(e=>e===`retained`).length}}async function K(e,t){let n=ce(e,t);if(n.status!==`recoverable`)return n.status;try{return await le(e,t,n.envelope,e.perRecordDeadlineMs??5e3)?`recovered`:`retained`}catch(n){return Y(e,n instanceof k?`timed_out`:`failed`,t,{error:n instanceof Error?n.message:String(n),...n instanceof k?{deadlineMs:n.deadlineMs}:{}}),`retained`}}function ce(e,t){let n=e.definition.store.read(t);if(n.status===`unreattachable`)return Y(e,`record_unreattachable`,t,{reason:n.reason,message:n.message,version:n.version}),{status:`retained`};if(n.status===`missing`||n.envelope.lifecycle===`completed`)return{status:`ignored`};let r=e.definition.store.resolvePath(e.resolveSessionDir(n.envelope.sessionId));return m.resolve(t)===m.resolve(r)?{status:`recoverable`,envelope:n.envelope}:(Y(e,`session_path_mismatch`,t,{envelopeSessionId:n.envelope.sessionId,canonicalPath:r}),{status:`retained`})}async function le(e,t,n,r){return await ue(e,t,n,await T({displayName:e.definition.displayName,envelope:n,scope:e.scope,deadlineMs:r,acquireControl:e.acquireControl,onLateCleanupFailure:(n,r,i)=>Y(e,n,t,{error:r instanceof Error?r.message:String(r),primaryError:i instanceof Error?i.message:String(i)})}))}async function ue(e,t,n,r){try{switch(r.reattached.status){case`active`:{let i=r.reattached.handle,a=await j({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{de(e);let t=await i.forceCleanup();return z(e,t),t}});return f(a)}case`completed`:return await q(e,t,n,{...e.definition.completionMetadata(r.reattached.result)}),!0;case`missing`:return await q(e,t,n,{recoveryStatus:`already-missing`}),!0;case`unreattachable`:{if(!J(r.reattached.reason))return Y(e,`retained`,t,{reason:r.reattached.reason,message:r.reattached.message}),!1;let i=await r.control.cleanup(n);return await j({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>z(e,i)}),f(i)}}}finally{await r.control[Symbol.asyncDispose]()}}async function q(e,t,n,r){await j({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{e.transition(`completed`,{metadata:{...e.envelope.metadata??{},phase:`completed`,...r}})}})}function de(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}function J(e){switch(e){case`descriptor-invalid`:case`descriptor-version-unsupported`:case`ownership-fence-lost`:return!1;case`owner-unavailable`:case`transport-not-reattachable`:return!0}}function Y(e,t,n,i){let a={phase:`${g(e.definition.resourceKind)}_recovery_${t}`,resourcePath:n,data:i};e.onDiagnostic?e.onDiagnostic(a):r({level:`warn`,phase:a.phase,data:{resourcePath:n,...i}})}async function fe(n,r){let i=n.store.read(r.resourcePath);if(i.status!==`decoded`||i.envelope.lifecycle!==`open`)throw pe(n,i.status);let a=i.envelope,o=await T({displayName:n.displayName,envelope:a,scope:r.scope,deadlineMs:r.deadlineMs??5e3,acquireControl:r.acquireControl,onLateCleanupFailure:(e,i,a)=>r.scope.diagnostics.emit({level:`error`,phase:`${g(n.resourceKind)}_recovery_${e}`,data:{resourcePath:r.resourcePath,error:t(i),primaryError:t(a)}})});try{switch(o.reattached.status){case`active`:return await N(n,{handle:o.reattached.handle,fence:a.fence,resourcePath:r.resourcePath,intent:`capture`});case`completed`:{let e=o.reattached.result;return await j({store:n.store,resourcePath:r.resourcePath,expected:a.fence,run:async t=>{H(n,t,{status:`completed`,result:e,alreadyCompleted:!0})}}),e}case`missing`:throw new e(`COMMAND_FAILED`,`${h(n.displayName)} is missing`,{reason:`resource-missing`,hint:n.messages.cleanupPendingHint});case`unreattachable`:if(J(o.reattached.reason)){let e=await o.control.cleanup(a);await j({store:n.store,resourcePath:r.resourcePath,expected:a.fence,run:async t=>z(t,e)}),B(n,e)}throw new e(`COMMAND_FAILED`,o.reattached.message??`${h(n.displayName)} cannot be reattached`,{reason:o.reattached.reason,hint:n.messages.cleanupPendingHint})}}finally{await o.control[Symbol.asyncDispose]()}}function pe(t,n){return new e(`INVALID_ARGS`,n===`missing`?t.messages.noActive:`${h(t.displayName)} recovery record is not open`)}function me(e){ge(e.fileName);let t=t=>m.join(t,e.fileName);return Object.freeze({resourceKind:e.resourceKind,displayName:e.displayName,resolvePath:t,read(t){let n,r;try{if(n=c(t),n===void 0)return{status:`missing`};r=JSON.parse(p.readFileSync(n,`utf8`))}catch(t){return Q(t)?{status:`missing`}:Z(_e(t,e.displayName))}finally{n!==void 0&&p.closeSync(n)}return he(d(r),e.resourceKind)},write(e,t){let r=m.dirname(e);p.mkdirSync(r,{recursive:!0}),n({destination:e,contents:`${JSON.stringify(t)}\n`})},list(e){let n;try{n=p.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(n=>t(m.join(e,n.name))).filter(X).sort()}})}function he(e,t){return e.status===`decoded`?e.envelope.resourceKind===t?{status:`decoded`,envelope:e.envelope}:Z(`Expected ${t} resource record, received ${e.envelope.resourceKind}`):e}function ge(e){if(e.length===0||m.basename(e)!==e)throw TypeError(`Durable capture resource fileName must be one file name`)}function X(e){try{return p.lstatSync(e),!0}catch(e){return!Q(e)}}function Z(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function Q(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function _e(e,t){return e instanceof Error?e.message:`${t} resource record is invalid`}function ve(e,t){t.admissionLedger.assertStartAllowed(t.device),ye(e,t.resourcePath,t.device);let n=e.store.read(t.resourcePath);return Object.freeze({token:ee.randomUUID(),generation:n.status===`decoded`?n.envelope.fence.generation+1:1})}function ye(t,n,r){let o=a(i(r));for(let r of t.store.list(m.dirname(m.dirname(n)))){let i=t.store.read(r);if(i.status===`unreattachable`)throw new e(`COMMAND_FAILED`,`${h($(t.displayName))} ${t.displayName} recovery record is unreattachable: ${i.message}`,{reason:i.reason,retriable:!1,hint:`Retain the corrupt or future-version ${t.displayName} manifest for manual recovery; no replacement capture is safe.`});if(i.status===`decoded`&&i.envelope.lifecycle!==`completed`&&(r===n||a(i.envelope.device)===o))throw new e(`COMMAND_FAILED`,`${h($(t.displayName))} ${t.displayName} resource for this device has not reached a confirmed terminal state`,{reason:`cleanup-unconfirmed`,hint:`Retry exact-owner cleanup using the existing ${t.displayName} manifest before starting a replacement.`})}}function $(e){return/^[aeiou]/i.test(e)?`an`:`a`}function be(e){let t=(t,n)=>e.store.resolvePath(t.resolveSessionDir(n)),n=t=>({definition:e,resolveSessionDir:e=>m.join(t.sessionsDir,l(e)),...t});return Object.freeze({store:e.store,resourcePath:t,createNextFence(t){return ve(e,t)},adoptStarted(t){return te(e,{...t,reportUndurableCleanup:(e,n)=>{n.confirmed?t.admissionLedger.clearUndurableCleanup(e):t.admissionLedger.blockUndurableCleanup(e,n.reason)}},e.store.resolvePath(t.binding.sessionDir))},finishLive(t){return se(e,t,e.store.resolvePath(t.binding.sessionDir))},finishRecovered(t){return fe(e,t)},forceCleanupLive(t){return R(e,{...t,resourcePath:e.store.resolvePath(t.binding.sessionDir)})},recoverAll(e){return G(n(e))},recoverOne(e,t){return K(n(e),t)}})}export{me as n,be as t};
|
|
1
|
+
import{R as e,q as t}from"./sdk-contracts.js";import{ct as n,ht as r}from"./sdk-io.js";import"./diagnostics.js";import{F as i,I as a,R as o}from"./sdk-device.js";import{rn as s}from"./sdk-batch.js";import{i as c}from"./verified-file.js";import"./file.js";import{r as l}from"./session-paths.js";import{n as u,r as d,t as f}from"./durable-resource.js";import ee from"node:crypto";import p from"node:fs";import m from"node:path";function h(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function g(e){return e.replaceAll(`-`,`_`)}async function te(e,t,n){let r={kind:`pending`};try{t.binding.assertAdoptable();let i=w(S(e,t),`active`);e.store.write(n,i),r={kind:`persisted`},t.throwIfCanceled();let a=t.pendingHandle.transfer();r={kind:`transferred`,handle:a},t.binding.adopt({handle:a,envelope:i})}catch(i){throw await _(e,t,n,r,i),i}}async function _(e,t,n,r,i){let a=t.binding.canPersist(),o=r.kind!==`pending`||a&&b(e,t,n),s=v(e,t,n,await y(t,r));t.reportUndurableCleanup(t.device,!o&&s.cleanupError===void 0||s.confirmed?{confirmed:!0}:{confirmed:!1,reason:s.cleanupError instanceof Error?s.cleanupError.message:`The durable cleanup transition could not be confirmed`}),s.cleanupError!==void 0&&C(e,t,i,s.cleanupError)}function v(e,t,n,i){try{return{confirmed:ie(e,n,t.fence,i),cleanupError:i}}catch(n){return r({level:`error`,phase:`${g(e.resourceKind)}_pending_adoption_transition_failed`,data:{session:t.binding.address,transitionError:n instanceof Error?n.message:String(n)}}),{confirmed:!1,cleanupError:i??n}}}async function y(e,t){try{t.kind===`transferred`?await t.handle[Symbol.asyncDispose]():await e.pendingHandle[Symbol.asyncDispose]();return}catch(e){return e}}function b(e,t,n){try{return e.store.write(n,ne(e,t)),!0}catch(i){try{return e.store.write(n,x(e,t,{version:0,body:{reason:`runtime-contract-invalid`}})),!0}catch(n){return r({level:`error`,phase:`${g(e.resourceKind)}_runtime_contract_tombstone_failed`,data:{session:t.binding.address,descriptorError:i instanceof Error?i.message:String(i),persistenceError:n instanceof Error?n.message:String(n)}}),!1}}}function ne(e,t){try{return w(S(e,t),`active`)}catch{return x(e,t,t.envelope.descriptor)}}function x(e,t,n){return u({resourceKind:e.resourceKind,sessionId:t.binding.address,device:i(t.device),owner:t.owner,fence:t.fence,lifecycle:`open`,descriptor:n,metadata:{phase:`runtime-contract-invalid`,runtimeContractInvalid:!0}})}function S(t,n){let r=d(n.envelope);if(r.status===`decoded`&&re(r.envelope,n,t.resourceKind))return r.envelope;throw new e(`COMMAND_FAILED`,`${h(t.displayName)} runtime returned an incoherent durable envelope`,{reason:`runtime-contract-invalid`,hint:`Retain the runtime diagnostics and report the selected device and owner.`})}function re(e,t,n){return e.resourceKind===n&&e.sessionId===t.binding.address&&o(e.device,i(t.device))&&s(e.owner)===s(t.owner)&&e.fence.token===t.fence.token&&e.fence.generation===t.fence.generation&&e.lifecycle===`open`}function ie(e,t,n,r){let i=e.store.read(t);return i.status!==`decoded`||i.envelope.fence.token!==n.token||i.envelope.fence.generation!==n.generation?!1:(e.store.write(t,{...i.envelope,lifecycle:r===void 0?`completed`:`open`,metadata:{...i.envelope.metadata??{},phase:r===void 0?`completed`:`cleanup-pending`,cleanupStatus:r===void 0?`cleaned`:`cleanup-pending`}}),!0)}function C(e,t,n,i){r({level:`error`,phase:`${g(e.resourceKind)}_pending_adoption_cleanup_failed`,data:{session:t.binding.address,primaryError:n instanceof Error?n.message:String(n),cleanupError:i instanceof Error?i.message:String(i)}})}function w(e,t){return Object.freeze({...e,lifecycle:`open`,metadata:{...e.metadata??{},phase:t}})}async function T(e){e.scope.signal.throwIfAborted();let t=new AbortController,n={...e.scope,signal:AbortSignal.any([e.scope.signal,t.signal])},r=()=>{},i=new Promise((e,t)=>{r=t}),a=()=>{},o=new Promise((t,n)=>{let r=()=>{try{e.scope.signal.throwIfAborted()}catch(e){n(e)}};if(e.scope.signal.aborted){r();return}e.scope.signal.addEventListener(`abort`,r,{once:!0}),a=()=>e.scope.signal.removeEventListener(`abort`,r)}),s=setTimeout(()=>{let n=new k(e.displayName,e.deadlineMs);t.abort(n),r(n)},e.deadlineMs);s.unref?.();let c=D(e,n),l,u=c.then(e=>(l??={kind:`acquisition`},e),e=>{throw l??={kind:`acquisition-error`},e}),d=i.catch(e=>{throw l??={kind:`deadline`,error:e},e}),f=o.catch(e=>{throw l??={kind:`cancellation`,error:e},e});try{return await Promise.race([u,d,f])}finally{if(clearTimeout(s),a(),l?.kind===`deadline`||l?.kind===`cancellation`){let t=l.error;c.then(n=>E(e,n,t),()=>{}).catch(()=>{})}else c.catch(()=>{})}}async function E(e,t,n){try{t.reattached.status===`active`&&await O(e,t.reattached.handle,`late_handle_cleanup_failed`,n)}finally{await O(e,t.control,`late_control_cleanup_failed`,n)}}async function D(e,t){let n,r;try{return n=await e.acquireControl(e.envelope,t),t.signal.throwIfAborted(),r=await n.reattach(e.envelope),t.signal.throwIfAborted(),{control:n,reattached:r}}catch(t){try{r?.status===`active`&&await O(e,r.handle,`late_handle_cleanup_failed`,t)}finally{n&&await O(e,n,`late_control_cleanup_failed`,t)}throw t}}async function O(e,t,n,r){try{await t[Symbol.asyncDispose]()}catch(t){e.onLateCleanupFailure(n,t,r)}}var k=class extends Error{deadlineMs;constructor(e,t){super(`${h(e)} recovery exceeded its ${t}ms deadline`),this.name=`DurableCaptureRecoveryDeadlineError`,this.deadlineMs=t}};const A=new Map;async function j(e){return await oe(e.resourcePath,async()=>{let t=e.store.read(e.resourcePath);if(t.status!==`decoded`)throw M(e.store,t.status===`missing`?`${e.store.displayName} resource record is missing`:`${e.store.displayName} resource record is unreattachable: ${t.message}`);if(!ae(t.envelope.fence,e.expected))throw M(e.store,`${e.store.displayName} resource ownership fence was lost`);let n=t.envelope;return await e.run({get envelope(){return n},transition(t,r={}){return n=Object.freeze({...n,lifecycle:t,...r.descriptor===void 0?{}:{descriptor:r.descriptor},...r.metadata===void 0?{}:{metadata:r.metadata}}),e.store.write(e.resourcePath,n),n}})})}function ae(e,t){return e.token===t.token&&e.generation===t.generation}async function oe(e,t){let n=A.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);A.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),A.get(e)===a&&A.delete(e)}}function M(t,n){return new e(`COMMAND_FAILED`,n,{reason:`ownership-fence-lost`,retriable:!1,hint:`Use the current ${t.displayName.toLowerCase()} resource owner or retain the recovery record for manual recovery.`})}async function se(t,n,r){let i=n.binding.read();if(!i)throw new e(`INVALID_ARGS`,t.messages.noActive);try{let e=await N(t,{handle:i.handle,fence:i.envelope.fence,resourcePath:r,intent:n.intent});return n.binding.clear(i),e}catch(e){let a=t.store.read(r);throw a.status===`decoded`&&a.envelope.lifecycle===`completed`&&n.binding.clear(i),e}}async function N(e,t){return await j({store:e.store,resourcePath:t.resourcePath,expected:t.fence,run:async n=>{W(n);let r=U(n),i;try{i=await t.handle.finish(r)}catch(r){throw await P(e,n,t,r,t.intent),r}if(i.status===`completed`)return H(e,n,i),i.result;H(e,n,i);let a=V(e,i);throw await P(e,n,t,a,t.intent),a}})}async function P(e,t,n,r,i){if(i===`capture`&&e.failedFinishPolicy===`preserve-retry-material`){I(e,n,r);return}let a;try{a=await n.handle.forceCleanup()}catch(i){L(e,n,r,i,F(t,i));return}try{z(t,a)}catch(t){L(e,n,r,a.status===`cleanup-pending`?a.message??a.reason:`cleanup returned ${a.status}`,t);return}f(a)||L(e,n,r,a.message)}function F(e,n){try{z(e,{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:t(n)});return}catch(e){return e}}function I(e,n,i){r({level:`error`,phase:`${g(e.resourceKind)}_finish_evidence_preserved`,data:{resourcePath:n.resourcePath,finishError:t(i),failedFinishPolicy:e.failedFinishPolicy}})}function L(e,n,i,a,o){r({level:`error`,phase:`${g(e.resourceKind)}_finish_cleanup_failed`,data:{resourcePath:n.resourcePath,finishError:t(i),cleanupError:a===void 0?`cleanup could not be confirmed`:t(a),...o===void 0?{}:{transitionError:t(o)}}})}async function R(e,t){let n=t.binding.read();n&&(B(e,await j({store:e.store,resourcePath:t.resourcePath,expected:n.envelope.fence,run:async e=>{W(e);let t=await n.handle.forceCleanup();return z(e,t),t}})),t.binding.clear(n))}function z(e,t){e.transition(f(t)?`completed`:`open`,{metadata:{...e.envelope.metadata??{},phase:f(t)?`completed`:`cleanup-pending`,cleanupStatus:t.status,...t.status===`cleanup-pending`?{cleanupPendingReason:t.reason,...t.message?{cleanupPendingMessage:t.message}:{}}:{}}})}function B(e,t){if(!f(t))throw V(e,t)}function V(t,n){return new e(`COMMAND_FAILED`,n.message??`${h(t.displayName)} cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:t.messages.cleanupPendingHint})}function H(e,t,n){if(n.status===`completed`){t.transition(`completed`,{metadata:{...t.envelope.metadata??{},...e.completionMetadata(n.result),phase:`completed`}});return}z(t,n)}function U(e){return Object.freeze({learned:e.envelope.metadata,record:t=>{e.transition(`open`,{metadata:{...e.envelope.metadata??{},...t}})}})}function W(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}async function G(e){let t=e.definition.store.list(e.sessionsDir),n=[];for(let r of t)n.push(await K(e,r));return{scanned:t.length,recovered:n.filter(e=>e===`recovered`).length,retained:n.filter(e=>e===`retained`).length}}async function K(e,t){let n=ce(e,t);if(n.status!==`recoverable`)return n.status;try{return await le(e,t,n.envelope,e.perRecordDeadlineMs??5e3)?`recovered`:`retained`}catch(n){return Y(e,n instanceof k?`timed_out`:`failed`,t,{error:n instanceof Error?n.message:String(n),...n instanceof k?{deadlineMs:n.deadlineMs}:{}}),`retained`}}function ce(e,t){let n=e.definition.store.read(t);if(n.status===`unreattachable`)return Y(e,`record_unreattachable`,t,{reason:n.reason,message:n.message,version:n.version}),{status:`retained`};if(n.status===`missing`||n.envelope.lifecycle===`completed`)return{status:`ignored`};let r=e.definition.store.resolvePath(e.resolveSessionDir(n.envelope.sessionId));return m.resolve(t)===m.resolve(r)?{status:`recoverable`,envelope:n.envelope}:(Y(e,`session_path_mismatch`,t,{envelopeSessionId:n.envelope.sessionId,canonicalPath:r}),{status:`retained`})}async function le(e,t,n,r){return await ue(e,t,n,await T({displayName:e.definition.displayName,envelope:n,scope:e.scope,deadlineMs:r,acquireControl:e.acquireControl,onLateCleanupFailure:(n,r,i)=>Y(e,n,t,{error:r instanceof Error?r.message:String(r),primaryError:i instanceof Error?i.message:String(i)})}))}async function ue(e,t,n,r){try{switch(r.reattached.status){case`active`:{let i=r.reattached.handle,a=await j({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{de(e);let t=await i.forceCleanup();return z(e,t),t}});return f(a)}case`completed`:return await q(e,t,n,{...e.definition.completionMetadata(r.reattached.result)}),!0;case`missing`:return await q(e,t,n,{recoveryStatus:`already-missing`}),!0;case`unreattachable`:{if(!J(r.reattached.reason))return Y(e,`retained`,t,{reason:r.reattached.reason,message:r.reattached.message}),!1;let i=await r.control.cleanup(n);return await j({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>z(e,i)}),f(i)}}}finally{await r.control[Symbol.asyncDispose]()}}async function q(e,t,n,r){await j({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{e.transition(`completed`,{metadata:{...e.envelope.metadata??{},phase:`completed`,...r}})}})}function de(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}function J(e){switch(e){case`descriptor-invalid`:case`descriptor-version-unsupported`:case`ownership-fence-lost`:return!1;case`owner-unavailable`:case`transport-not-reattachable`:return!0}}function Y(e,t,n,i){let a={phase:`${g(e.definition.resourceKind)}_recovery_${t}`,resourcePath:n,data:i};e.onDiagnostic?e.onDiagnostic(a):r({level:`warn`,phase:a.phase,data:{resourcePath:n,...i}})}async function fe(n,r){let i=n.store.read(r.resourcePath);if(i.status!==`decoded`||i.envelope.lifecycle!==`open`)throw pe(n,i.status);let a=i.envelope,o=await T({displayName:n.displayName,envelope:a,scope:r.scope,deadlineMs:r.deadlineMs??5e3,acquireControl:r.acquireControl,onLateCleanupFailure:(e,i,a)=>r.scope.diagnostics.emit({level:`error`,phase:`${g(n.resourceKind)}_recovery_${e}`,data:{resourcePath:r.resourcePath,error:t(i),primaryError:t(a)}})});try{switch(o.reattached.status){case`active`:return await N(n,{handle:o.reattached.handle,fence:a.fence,resourcePath:r.resourcePath,intent:`capture`});case`completed`:{let e=o.reattached.result;return await j({store:n.store,resourcePath:r.resourcePath,expected:a.fence,run:async t=>{H(n,t,{status:`completed`,result:e,alreadyCompleted:!0})}}),e}case`missing`:throw new e(`COMMAND_FAILED`,`${h(n.displayName)} is missing`,{reason:`resource-missing`,hint:n.messages.cleanupPendingHint});case`unreattachable`:if(J(o.reattached.reason)){let e=await o.control.cleanup(a);await j({store:n.store,resourcePath:r.resourcePath,expected:a.fence,run:async t=>z(t,e)}),B(n,e)}throw new e(`COMMAND_FAILED`,o.reattached.message??`${h(n.displayName)} cannot be reattached`,{reason:o.reattached.reason,hint:n.messages.cleanupPendingHint})}}finally{await o.control[Symbol.asyncDispose]()}}function pe(t,n){return new e(`INVALID_ARGS`,n===`missing`?t.messages.noActive:`${h(t.displayName)} recovery record is not open`)}function me(e){ge(e.fileName);let t=t=>m.join(t,e.fileName);return Object.freeze({resourceKind:e.resourceKind,displayName:e.displayName,resolvePath:t,read(t){let n,r;try{if(n=c(t),n===void 0)return{status:`missing`};r=JSON.parse(p.readFileSync(n,`utf8`))}catch(t){return Q(t)?{status:`missing`}:Z(_e(t,e.displayName))}finally{n!==void 0&&p.closeSync(n)}return he(d(r),e.resourceKind)},write(e,t){let r=m.dirname(e);p.mkdirSync(r,{recursive:!0}),n({destination:e,contents:`${JSON.stringify(t)}\n`})},list(e){let n;try{n=p.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(n=>t(m.join(e,n.name))).filter(X).sort()}})}function he(e,t){return e.status===`decoded`?e.envelope.resourceKind===t?{status:`decoded`,envelope:e.envelope}:Z(`Expected ${t} resource record, received ${e.envelope.resourceKind}`):e}function ge(e){if(e.length===0||m.basename(e)!==e)throw TypeError(`Durable capture resource fileName must be one file name`)}function X(e){try{return p.lstatSync(e),!0}catch(e){return!Q(e)}}function Z(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function Q(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function _e(e,t){return e instanceof Error?e.message:`${t} resource record is invalid`}function ve(e,t){t.admissionLedger.assertStartAllowed(t.device),ye(e,t.resourcePath,t.device);let n=e.store.read(t.resourcePath);return Object.freeze({token:ee.randomUUID(),generation:n.status===`decoded`?n.envelope.fence.generation+1:1})}function ye(t,n,r){let o=a(i(r));for(let r of t.store.list(m.dirname(m.dirname(n)))){let i=t.store.read(r);if(i.status===`unreattachable`)throw new e(`COMMAND_FAILED`,`${h($(t.displayName))} ${t.displayName} recovery record is unreattachable: ${i.message}`,{reason:i.reason,retriable:!1,hint:`Retain the corrupt or future-version ${t.displayName} manifest for manual recovery; no replacement capture is safe.`});if(i.status===`decoded`&&i.envelope.lifecycle!==`completed`&&(r===n||a(i.envelope.device)===o))throw new e(`COMMAND_FAILED`,`${h($(t.displayName))} ${t.displayName} resource for this device has not reached a confirmed terminal state`,{reason:`cleanup-unconfirmed`,hint:`Retry exact-owner cleanup using the existing ${t.displayName} manifest before starting a replacement.`})}}function $(e){return/^[aeiou]/i.test(e)?`an`:`a`}function be(e){let t=(t,n)=>e.store.resolvePath(t.resolveSessionDir(n)),n=t=>({definition:e,resolveSessionDir:e=>m.join(t.sessionsDir,l(e)),...t});return Object.freeze({store:e.store,resourcePath:t,createNextFence(t){return ve(e,t)},adoptStarted(t){return te(e,{...t,reportUndurableCleanup:(e,n)=>{n.confirmed?t.admissionLedger.clearUndurableCleanup(e):t.admissionLedger.blockUndurableCleanup(e,n.reason)}},e.store.resolvePath(t.binding.sessionDir))},finishLive(t){return se(e,t,e.store.resolvePath(t.binding.sessionDir))},finishRecovered(t){return fe(e,t)},forceCleanupLive(t){return R(e,{...t,resourcePath:e.store.resolvePath(t.binding.sessionDir)})},recoverAll(e){return G(n(e))},recoverOne(e,t){return K(n(e),t)}})}export{me as n,be as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as e,o as t}from"./sdk-device.js";import{
|
|
1
|
+
import{b as e,o as t}from"./sdk-device.js";import{en as n,nn as r}from"./sdk-batch.js";const i=4096;function a(e){return s(e,{seen:new WeakSet,nodes:0},0)}function o(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,f(t)])))}function s(e,t,n){if(!u(e)||n>32||t.seen.has(e))return!1;t.seen.add(e),t.nodes+=1;let r=t.nodes<=i&&Object.values(e).every(e=>c(e,t,n+1));return t.seen.delete(e),r}function c(e,t,n){return d(e)?!0:n>32?!1:Array.isArray(e)?l(e,t,n):s(e,t,n)}function l(e,t,n){if(t.seen.has(e))return!1;t.seen.add(e),t.nodes+=1;let r=t.nodes<=i&&e.every(e=>c(e,t,n+1));return t.seen.delete(e),r}function u(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function d(e){return e===null?!0:typeof e==`number`?Number.isFinite(e):typeof e==`string`||typeof e==`boolean`}function f(e){return Array.isArray(e)?Object.freeze(e.map(f)):typeof e==`object`&&e?o(e):e}function p(e){if(!C(e))return g(`Durable resource envelope must be an object`);let n=e.envelopeVersion;if(!S(n))return g(`Durable resource envelopeVersion must be a non-negative integer`);if(n!==1)return{status:`unreattachable`,reason:`descriptor-version-unsupported`,message:`Unsupported durable resource envelope version: ${n}`,version:n};if(!x(e.resourceKind))return g(`Durable resource resourceKind must be a non-empty string`);if(!x(e.sessionId))return g(`Durable resource sessionId must be a non-empty string`);let r=t(e.device);if(!r)return g(`Durable resource device identity is invalid`);let i=_(e.owner);if(!i)return g(`Durable resource owner reference is invalid`);if(i.kind===`local-family`&&i.family!==r.family)return g(`Durable resource local owner does not match the device family`);let s=v(e.fence);if(!s)return g(`Durable resource ownership fence is invalid`);if(!b(e.lifecycle))return g(`Durable resource lifecycle state is invalid`);let c=y(e.descriptor);return c?e.metadata!==void 0&&!a(e.metadata)?g(`Durable resource metadata must be a JSON object`):{status:`decoded`,envelope:Object.freeze({envelopeVersion:1,resourceKind:e.resourceKind,sessionId:e.sessionId,device:r,owner:i,fence:s,lifecycle:e.lifecycle,descriptor:c,...e.metadata===void 0?{}:{metadata:o(e.metadata)}})}:g(`Durable resource descriptor is invalid`)}function m(e,t){return Object.freeze({version:e.version,body:o(e.encode(t))})}function h(e){let t=p({envelopeVersion:1,...e});if(t.status!==`decoded`)throw TypeError(t.message);return t.envelope}function g(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function _(t){return C(t)?t.kind===`local-family`&&e(t.family)?n(t.family):t.kind===`provider-runtime`&&x(t.provider)&&x(t.instance)?r(t.provider,t.instance):null:null}function v(e){return!C(e)||!x(e.token)||!S(e.generation)?null:Object.freeze({token:e.token,generation:e.generation})}function y(e){return!C(e)||!S(e.version)||!a(e.body)?null:Object.freeze({version:e.version,body:o(e.body)})}function b(e){return e===`open`||e===`completed`}function x(e){return typeof e==`string`&&e.trim().length>0}function S(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}function C(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function w(e){return e.status===`cleaned`||e.status===`already-missing`}export{m as i,h as n,p as r,w as t};
|
package/dist/src/ended-lease.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Tt as e}from"./back-mode.js";import{m as t}from"./daemon-resolution.js";import{_ as n,x as r}from"./cli.js";import{isHostAllocatedLease as i,r as a}from"./connection-runtime.js";function o(o,s,c){if(!o.remoteConfig)return;let l=e(s).map(e=>e.leaseId);if(l.length===0)return;let u=t(o.stateDir,{cwd:c.cwd,env:c.env}).baseDir,d=n({stateDir:u,session:o.session??`default`});!d?.leaseId||!l.includes(d.leaseId)||i(d)||a(d.leaseProvider).leaseKind===`proxy`&&r({stateDir:u,state:{...d,leaseId:void 0,updatedAt:new Date().toISOString()}})}export{o as forgetEndedProxyLease};
|
package/dist/src/find.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{et as e,p as t,s as n,x as r}from"./sdk-contracts.js";import{h as i}from"./back-mode.js";import{Bn as a,
|
|
1
|
+
import{et as e,p as t,s as n,x as r}from"./sdk-contracts.js";import{h as i}from"./back-mode.js";import{Bn as a,Bt as o,Rn as s,Un as c,_t as l,zn as u}from"./sdk-batch.js";import{o as d}from"./session-store.js";import{u as f}from"./src.js";import{r as p,t as m}from"./success-text.js";import{n as h}from"./interaction-error.js";import{b as g,o as _,r as v}from"./snapshot-runtime-capture-input.js";import{a as y,c as b,n as x,s as S,t as C}from"./selector-pipeline-policy.js";import{t as w}from"./snapshot-baseline.js";import{t as T}from"./snapshot-quality-verdict.js";import{n as E}from"./capture-disclosure.js";import{t as D}from"./snapshot-runtime-binding.js";import{r as O,t as k}from"./keyboard-occlusion.js";import{t as A}from"./type-text-runtime.js";import{n as j,u as M}from"./selector-runtime.js";function N(e,t){let n=t[0]?.rect;if(!n)return e;let i=e.filter(e=>{if(!e.rect)return!1;let t=r(e.rect);return t.x>=n.x&&t.x<=n.x+n.width&&t.y>=n.y&&t.y<=n.y+n.height}),a=i.length>0?i:e;return a.length<2?a:P(a,t,S(t))}function P(e,t,n){return e.map((e,r)=>({node:e,index:r,score:F(e,t,n)})).sort((e,t)=>t.score===e.score?L(e.node)-L(t.node)||e.index-t.index:t.score-e.score).map(e=>e.node)}function F(e,t,n){let r=n(e);if(r.reason===`covered`)return 0;let i=I(r,t[0]);return i>0?i:e.hittable&&e.rect&&!b(e,t[0])?3:+!!e.rect}function I(e,t){return e.node.rect?e.reason===`semantic-target`||e.reason===`same-rect-descendant`?4:e.reason===`hittable-ancestor`&&!b(e.node,t)?2:0:0}function L(e){return e.rect?e.rect.width*e.rect.height:1/0}function R(e,t,r){return n(`AMBIGUOUS_MATCH`,`find matched ${e.length} elements for ${t} "${r}". Use a more specific locator or selector.`,{locator:t,query:r,...i(e)})}function z(e){if(e.ambiguity!==`reject-candidates`)throw Error(`find's resolution policy must reject candidates, got "${e.ambiguity}"`)}function B(e){let{nodes:t,locator:r,query:i,selectorExpression:a,flags:o,platform:s}=e,c=C.findAct,l=t.filter(e=>!b(e,t[0])),d=c.resolution,f;if(f=a?x(c,l,a,{platform:s}).list?.matchedNodes??[]:u(l,r,i,{requireRect:d.requireRect}).matches,f=N(f,t),f.length>1){z(d);let e=V(f,o);if(!e)return{ok:!1,response:R(f,r,i)};f=e}let p=f[0]??null;return p?{ok:!0,node:p}:{ok:!1,response:n(`COMMAND_FAILED`,`find did not match any element`)}}function V(e,t){return t?.findFirst?[e[0]]:t?.findLast?[e.at(-1)]:null}function H(e){let{device:t,req:n,logPath:r,locator:i,query:a,sessionStore:o,sessionName:s}=e,c=M({ref:e.ref,device:t,sessionStore:o,sessionName:s,req:n,logPath:r,capture:e.capture,captureProof:e.captureProof});return async()=>{let{snapshot:e}=await c.capture({flags:{...n.flags,snapshotInteractiveOnly:!0},recovery:{legacyIosSparse:{query:a,shouldScope:W(i)},sparseVerdictQueryScope:{query:a,shouldScope:W(i)}}});return e}}function U(e){return n(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}function W(e){return e!==`role`}async function G(e){let{req:r,sessionName:i,logPath:u,sessionStore:d,invoke:f}=e,p=d.lookup(i),m=r.command;if(m!==`find`)return null;let h=r.positionals??[],g=s(h,r.flags);if(!g.ok)return n(g.code,g.message);let{locator:_,query:v,action:b,value:x}=g.parsed;if(r.flags?.record&&!a(b))return n(`INVALID_ARGS`,`find ${b} is a mutating action and is always recorded; --record only applies to a read-only find (exists, wait, list, get text, get attrs).`);let S=await j({createCommandSurface:e.createCommandSurface,req:r,sessionName:i,logPath:u,sessionStore:d,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(S)return S;let O=p?d.requireCurrent(p):void 0;if(!O||!p)return t();let k=O.device,A=await D({command:`find`,device:k,session:O,plan:o({hasActiveApp:O.appBundleId!==void 0,intent:l(b)}),inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(!A.ok)return A.response;let M=c(_,v),N={},P=H({ref:p,device:k,req:r,logPath:u,locator:_,query:v,sessionStore:d,sessionName:i,capture:A.capture,captureProof:N}),F={sessionRef:p,req:r,sessionName:i,logPath:u,sessionStore:d,invoke:f,device:k,command:m,locator:_,query:v,publicFlags:te(r.flags),boundFocusPoint:A.focusPoint,boundTypeText:A.typeText},I=await P();if(T(I.snapshotQuality))return E({response:U(I.snapshotQuality),consumedTree:I,captureProof:N});let{nodes:L}=I,R=B({nodes:L,locator:_,query:v,selectorExpression:M,flags:r.flags,platform:k.platform});if(!R.ok)return E({response:R.response,consumedTree:I,captureProof:N});let z=R.node,V=await y(C.findAct,L,z),W=V.node,G=`@${W.ref}`,q={...r.flags??{},noRecord:!0},J=await K(F,{node:z,resolvedNode:W,ref:G,tree:w(I),...I.keyboard?{keyboard:I.keyboard}:{},actionFlags:q,...V.kind===`occluded`?{occludedNode:V.node}:{}},b,x);return J&&E({response:J,consumedTree:I,captureProof:N})}async function K(e,t,n,r){let i={click:()=>J(e,t),fill:()=>Y(e,t,r),focus:()=>X(e,t),type:()=>Z(e,t,r)}[n];return i?await i():null}function q(e){return{ref:e.ref,node:e.resolvedNode,tree:e.tree,...e.keyboard?{keyboard:e.keyboard}:{}}}async function J(e,t){let{req:n,sessionName:i,sessionStore:a,sessionRef:o,invoke:s,command:c,locator:l,query:u,publicFlags:f}=e,h=await s({token:n.token,session:i,command:`click`,positionals:[t.ref],flags:t.actionFlags,internal:{findResolvedTarget:q(t)}});if(!h.ok)return h;let g=t.resolvedNode.rect?r(t.resolvedNode.rect):t.node.rect?r(t.node.rect):null,_={ref:t.ref,locator:l,query:u};g&&(_.x=g.x,_.y=g.y);let v=m(h.data)??`Tapped ${t.ref}${g?` (${g.x}, ${g.y})`:``}`;return Object.assign(_,p(v)),d(a,o,n,c,{ref:t.ref,action:`click`,locator:l,query:u},{flags:f}),{ok:!0,data:_}}async function Y(e,t,r){let{req:i,sessionName:a,sessionStore:o,sessionRef:s,invoke:c,command:l,publicFlags:u}=e;if(r===void 0)return n(`INVALID_ARGS`,`find fill requires text (use "" to clear the field)`);let f=await c({token:i.token,session:a,command:`fill`,positionals:[t.ref,r],flags:t.actionFlags,internal:{findResolvedTarget:q(t)}});return f.ok&&d(o,s,i,l,{ref:t.ref,action:`fill`},{flags:u}),f}async function X(e,t){let n=await Q(e,t);return n.ok&&$(e,t,`focus`),n}async function Z(e,t,r){let{req:i,logPath:a}=e;if(!r)return n(`INVALID_ARGS`,`find type requires text`);let o=await Q(e,t);if(!o.ok)return o;let s=e.sessionStore.requireCurrent(e.sessionRef);_(s);let c=e.boundTypeText;if(!c)return n(`COMMAND_FAILED`,`find type was admitted without a text-entry operation`);let l=await A({operations:{typeText:c}},[r],v(a,i.flags,s.appBundleId,s.trace?.outPath));return $(e,t,`type`),{ok:!0,data:l}}async function Q(t,i){let{req:a,logPath:o}=t,s=ee(i,`focus`);if(s)return s;let c=i.resolvedNode.rect?r(i.resolvedNode.rect):null;if(!c)return n(`COMMAND_FAILED`,`matched element has no bounds`);try{k({nodes:i.tree.nodes,node:i.resolvedNode,action:`focus`,label:`Ref ${i.ref}`,...i.keyboard?{keyboard:i.keyboard}:{},tapPoint:c})}catch(t){return{ok:!1,error:e(t)}}let l=t.sessionStore.requireCurrent(t.sessionRef);_(l);let u=t.boundFocusPoint;return u?{ok:!0,data:await f({operations:{focusPoint:u}},c,v(o,a.flags,l.appBundleId,l.trace?.outPath))}:n(`COMMAND_FAILED`,`find focus was admitted without a focus operation`)}function ee(e,t){let r=e.occludedNode;return r?n(`COMMAND_FAILED`,`Matched element ${e.ref} is covered by another visible element and cannot ${O(t)} safely`,h(r)):null}function $(e,t,n){let{req:r,sessionStore:i,sessionRef:a,command:o,publicFlags:s}=e;d(i,a,r,o,{ref:t.ref,action:n},{flags:s})}function te(e){return{...g(e)??{}}}export{G as handleFindCommands};
|
package/dist/src/finders.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Hn as e}from"./sdk-batch.js";import{t}from"./sdk-finders.js";export{t as findBestMatchesByLocator,e as parseFindArgs};
|
|
@@ -7,8 +7,9 @@ type PointerTrajectorySample = {
|
|
|
7
7
|
offsetMs: number;
|
|
8
8
|
point: Point;
|
|
9
9
|
};
|
|
10
|
-
type
|
|
11
|
-
|
|
10
|
+
type TapPointerId = 0 | 1 | 2 | 3 | 4;
|
|
11
|
+
type PointerTrajectory<PointerId extends number = 0 | 1> = {
|
|
12
|
+
pointerId: PointerId;
|
|
12
13
|
samples: readonly PointerTrajectorySample[];
|
|
13
14
|
};
|
|
14
15
|
type SinglePointerTrajectory = {
|
|
@@ -23,13 +24,22 @@ type SinglePointerGesturePlan = {
|
|
|
23
24
|
viewport: Rect;
|
|
24
25
|
pointers: readonly [SinglePointerTrajectory];
|
|
25
26
|
};
|
|
26
|
-
type
|
|
27
|
-
topology: '
|
|
27
|
+
type TwoContactGesturePlan = {
|
|
28
|
+
topology: 'multi';
|
|
28
29
|
intent: 'pan' | 'pinch' | 'rotate' | 'transform';
|
|
29
30
|
durationMs: number;
|
|
30
31
|
viewport: Rect;
|
|
31
32
|
pointers: readonly [PointerTrajectory, PointerTrajectory];
|
|
32
33
|
};
|
|
34
|
+
/** Stationary contacts that touch down together and lift together after `durationMs`. */
|
|
35
|
+
type TapGesturePlan = {
|
|
36
|
+
topology: 'multi';
|
|
37
|
+
intent: 'tap';
|
|
38
|
+
durationMs: number;
|
|
39
|
+
viewport: Rect;
|
|
40
|
+
pointers: readonly [PointerTrajectory<TapPointerId>, PointerTrajectory<TapPointerId>, ...PointerTrajectory<TapPointerId>[]];
|
|
41
|
+
};
|
|
42
|
+
type MultiTouchGesturePlan = TwoContactGesturePlan | TapGesturePlan;
|
|
33
43
|
type GesturePlan = SinglePointerGesturePlan | MultiTouchGesturePlan;
|
|
34
44
|
//#endregion
|
|
35
45
|
export { PointerTrajectorySample as a, PointerTrajectory as i, GesturePointerCount as n, SinglePointerGesturePlan as o, MultiTouchGesturePlan as r, GesturePlan as t };
|
package/dist/src/gesture-plan.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{R as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{R as e}from"./sdk-contracts.js";import{Z as t,dt as n,lt as r}from"./tv-remote.js";const i={pinchAxisDegrees:-90,samplingProfile:`default`},a={ios:i,macos:i,android:{pinchAxisDegrees:0,samplingProfile:`android`},harmonyos:i,vega:i,linux:i,web:i};function o(e,t,n){let r=S(t),i=F(n);switch(e.intent){case`fling`:return u(e,r);case`pan`:return d(e,r,i);case`pinch`:return p({intent:`pinch`,origin:e.origin??j(r),delta:{x:0,y:0},scale:k(e.scale,`gesture pinch scale`),rotationDegrees:0,durationMs:300},r,i);case`rotate`:{let t=O(e.degrees,`gesture rotate degrees`);return p({intent:`rotate`,origin:e.origin??j(r),delta:{x:0,y:0},scale:1,rotationDegrees:t,durationMs:E(t)},r,i)}case`transform`:{let t=O(e.degrees,`gesture transform degrees`);return p({intent:`transform`,origin:e.origin,delta:e.delta,scale:k(e.scale,`gesture transform scale`),rotationDegrees:t,durationMs:C(e.durationMs,E(t),`gesture transform durationMs`)},r,i)}case`tap`:return _(e,r)}}function s(e){let[{samples:t}]=e.pointers,n=t[0],r=t.at(-1);return{start:n.point,end:r.point}}function c(n,r){let i=S(r),a=w(n.sourceHoldMs,800,`gesture drag sourceHoldMs`),o=C(n.moveMs,500,`gesture drag moveMs`),s=T(n.destinationHoldMs,0,`gesture drag destinationHoldMs`);if(a+o+s>1e4)throw new e(`INVALID_ARGS`,`gesture drag total duration must be at most ${t}`);return l(f(`pan`,n.from,n.to,o,i,`timed-pan`),a,s)}function l(e,t,n){let r=e.pointers[0],[i,a]=r.samples,o=t+e.durationMs+n,s=[{offsetMs:0,point:i.point},{...i,offsetMs:i.offsetMs+t},{...a,offsetMs:a.offsetMs+t},...n>0?[{offsetMs:o,point:a.point}]:[]];return{...e,durationMs:o,pointers:[{...r,samples:s}]}}function u(e,t){if(`preset`in e){let{from:n,to:r}=P(e.preset,t);return f(`fling`,n,r,100,t,`endpoint-hold`)}if(`from`in e)return f(`fling`,e.from,e.to,100,t,`endpoint-hold`);let r=D(e.origin,`gesture fling origin`),i=A(e.distance??180,`gesture fling distance`);return f(`fling`,r,M(r,n(e.direction,i)),100,t,`endpoint-hold`)}function d(t,n,r){let i=C(t.durationMs,500,`gesture pan durationMs`);if((t.pointerCount??1)===1){let e=D(t.origin,`gesture pan origin`);return f(`pan`,e,M(e,D(t.delta,`gesture pan delta`)),i,n,t.executionProfile??`timed-pan`)}if(t.pointerCount!==2)throw new e(`INVALID_ARGS`,`gesture pan pointerCount must be 1 or 2`);return p({intent:`pan`,origin:t.origin,delta:t.delta,scale:1,rotationDegrees:0,durationMs:i},n,r)}function f(e,t,n,r,i,a){let o=D(t,`gesture ${e} start`),s=D(n,`gesture ${e} end`),c=[{offsetMs:0,point:o},{offsetMs:r,point:s}];return b(c,i,{intent:e,pointerId:0}),{topology:`single`,intent:e,executionProfile:a,durationMs:r,viewport:i,pointers:[{pointerId:0,samples:c}]}}function p(e,t,n){let r=D(e.origin,`gesture ${e.intent} origin`),i=M(r,D(e.delta,`gesture ${e.intent} delta`)),a=Math.min(t.width,t.height)*g(e.intent),o=e.scale>1?a/e.scale:a,s=o*e.scale;if(Math.min(o,s)<48)throw x({intent:e.intent,viewport:t,initialSpan:o,finalSpan:s,minimumReliableSpan:48});let c=o/2,l=y(e.durationMs,n.samplingProfile),u=(a,o)=>{let s=l.map(t=>({offsetMs:t,point:m({...e,start:r,end:i,initialRadius:c,offsetMs:t,side:o,profile:n})}));return b(s,t,{intent:e.intent,pointerId:a}),{pointerId:a,samples:s}};return{topology:`multi`,intent:e.intent,durationMs:e.durationMs,viewport:t,pointers:[u(0,1),u(1,-1)]}}function m(e){let t=e.offsetMs/e.durationMs,n=N(e.start,e.end,t),r=e.initialRadius*(1+(e.scale-1)*t),i=I(h(e.intent,e.profile)+e.rotationDegrees*t);return{x:n.x+Math.cos(i)*r*e.side,y:n.y+Math.sin(i)*r*e.side}}function h(e,t){return e===`pinch`?t.pinchAxisDegrees:-90}function g(e){return e===`pinch`?.4:.25}function _(e,t){let n=C(e.holdMs,50,`gesture tap holdMs`);return{topology:`multi`,intent:`tap`,durationMs:n,viewport:t,pointers:v(e.points).map((e,r)=>{let i=[{offsetMs:0,point:e},{offsetMs:n,point:e}];return b(i,t,{intent:`tap`,pointerId:r}),{pointerId:r,samples:i}})}}function v(t){if(t.length<2||t.length>5)throw new e(`INVALID_ARGS`,`gesture tap requires 2 to 5 points`,{pointCount:t.length,hint:`Use press for a single contact.`});let n=t.map((e,t)=>D(e,`gesture tap point ${t+1}`));return n.forEach((t,r)=>{if(n.findIndex(e=>e.x===t.x&&e.y===t.y)!==r)throw new e(`INVALID_ARGS`,`gesture tap points must be distinct`,{reason:`GESTURE_TAP_DUPLICATE_POINT`,point:t,hint:`Give each contact its own coordinates.`})}),n}function y(t,n){if(!Number.isFinite(t)||t<=0)throw new e(`INVALID_ARGS`,`gesture sample duration must be a positive finite number`);let r=t/16,i=Math.max(3,n===`android`?Math.round(r):Math.floor(r));return Array.from({length:i+1},(e,n)=>Math.round(t*n/i))}function b(t,n,r){let i=n.x+n.width-1,a=n.y+n.height-1;for(let o of t){let{x:t,y:s}=o.point;if(!Number.isFinite(t)||!Number.isFinite(s))throw new e(`INVALID_ARGS`,`Gesture motion produces non-finite pointer coordinates`,{...r,reason:`GESTURE_TRAJECTORY_NON_FINITE`,hint:`Reduce the requested rotation, translation, or scale.`});if(t<n.x+1||t>i||s<n.y+1||s>a)throw x({...r,viewport:n,sample:o})}}function x(t){return new e(`INVALID_ARGS`,`Gesture trajectory does not fit inside the viewport`,{...t,reason:`GESTURE_TRAJECTORY_OUT_OF_BOUNDS`,hint:`Move the gesture away from the edge or reduce its translation, scale, or rotation.`})}function S(t){let n={x:O(t.x,`gesture viewport x`),y:O(t.y,`gesture viewport y`),width:O(t.width,`gesture viewport width`),height:O(t.height,`gesture viewport height`)};if(n.width<=0||n.height<=0)throw new e(`INVALID_ARGS`,`gesture viewport width and height must be positive`);return n}function C(n,r,i){let a=n??r;if(!Number.isInteger(a)||a<16||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 16 and ${t}`);return a}function w(n,r,i){let a=n??r;if(!Number.isInteger(a)||a<1||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 1 and ${t}`);return a}function T(n,r,i){let a=n??r;if(!Number.isInteger(a)||a<0||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 0 and ${t}`);return a}function E(e){let t=Math.ceil(Math.abs(e)/3)*16;return Math.min(Math.max(300,t),2400)}function D(e,t){return{x:O(e.x,`${t} x`),y:O(e.y,`${t} y`)}}function O(t,n){if(!Number.isFinite(t))throw new e(`INVALID_ARGS`,`${n} must be a finite number`);return t}function k(t,n){let r=O(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be greater than 0`);return r}function A(t,n){let r=O(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be a positive number`);return r}function j(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function M(e,t){return{x:e.x+t.x,y:e.y+t.y}}function N(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function P(e,t){let n=r(e,{referenceWidth:t.width,referenceHeight:t.height});return{from:{x:t.x+n.x1,y:t.y+n.y1},to:{x:t.x+n.x2,y:t.y+n.y2}}}function F(e){return e===void 0?i:a[e]}function I(e){return e*Math.PI/180}export{s as a,y as i,o as n,N as r,c as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{R as e,et as t}from"./sdk-contracts.js";import{
|
|
1
|
+
import{R as e,et as t}from"./sdk-contracts.js";import{Lt as n,bt as r}from"./sdk-batch.js";import{n as i}from"./snapshot-runtime-capture-input.js";import{n as a,t as o}from"./runtime-admission.js";import{i as s}from"./gesture-admission.js";async function c(e){let t=await a({command:`runtime gesture-viewport`,device:e.device,use:r,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});return t.type===`response`?{ok:!1,response:t.response}:{ok:!0,read:d(t.runtime).gestureViewport}}async function l(r){let i=n(r.input),a=await o({command:`gesture`,device:r.device,required:i.use.required,inspectFacts:r.inspectFacts,platformServices:r.platformServices,bindDevice:r.bindDevice,unavailableResponse:n=>({ok:!1,error:t(new e(`UNSUPPORTED_OPERATION`,s(r.device,i.tier,r.input.intent),{gesture:r.input.intent,...n.hint===void 0?{}:{hint:n.hint}}))})});return a.type===`response`?{ok:!1,response:a.response}:{ok:!0,gestures:await u(a.bind,r.device,i)}}async function u(e,t,n){switch(n.tier){case`plan`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performGesturePlan(f(e,t)),...d(r),...r.operations.querySelector?{querySelector:r.operations.querySelector}:{}}}case`directional-fling`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performDirectionalFlingPlan(f(e,t)),...d(r),...r.operations.querySelector?{querySelector:r.operations.querySelector}:{}}}case`multi-touch`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performMultiTouchGesturePlan(f(e,t)),...d(r),...r.operations.querySelector?{querySelector:r.operations.querySelector}:{}}}case`target-authored-drag`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performTargetAuthoredDrag(f(e,t)),...d(r),...r.operations.querySelector?{querySelector:r.operations.querySelector}:{}}}}}function d(e){let{gestureViewport:t}=e.operations,n=e.operations.captureSnapshot?{operations:{captureSnapshot:e.operations.captureSnapshot}}:void 0,r=t?{operations:{gestureViewport:t}}:void 0;return Object.freeze({...n?{captureSnapshot:async e=>await n.operations.captureSnapshot(e)}:{},...r?{gestureViewport:async e=>await r.operations.gestureViewport(p(e))}:{}})}function f(e,t){return{plan:e,...t.appBundleId===void 0?{}:{options:{appBundleId:t.appBundleId}},execution:i(t)}}function p(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:i(e)}}export{c as n,l as t};
|
package/dist/src/host4.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{R as e}from"./sdk-contracts.js";import{f as t}from"./sdk-io.js";import{n}from"./agent-device-client.js";import{
|
|
1
|
+
import{R as e}from"./sdk-contracts.js";import{f as t}from"./sdk-io.js";import{n}from"./agent-device-client.js";import{m as r}from"./daemon-resolution.js";async function i(i){let a=i.host??t(process),o={env:{...a.env},cwd:a.cwd};if(typeof i.stateDir!=`string`||i.stateDir.trim().length===0)throw new e(`INVALID_ARGS`,`startAgentDevice requires a stateDir.`,{hint:`Pass an explicit stateDir to startAgentDevice({ stateDir }).`});let s=(i.plugins??[]).map(e=>({source:`embedder`,load:()=>e})),c={env:{...o.env,AGENT_DEVICE_STATE_DIR:i.stateDir,AGENT_DEVICE_DAEMON_SERVER_MODE:`socket`},cwd:o.cwd},l=r(i.stateDir,{env:c.env,cwd:c.cwd}).baseDir,[{startDaemonRuntime:u},{composeDaemonRuntimeDeps:d},{resolveLocalDaemonCodeIdentity:f}]=await Promise.all([import(`./src.js`).then(e=>e.t),import(`./daemon-composition.js`),import(`./daemon-launch-spec.js`).then(e=>e.t)]),p=await f(),m={write:()=>{}},h=await u({host:c,stdout:m,stderr:m,ownership:`embedded`,codeIdentity:p,composeDeps:async e=>await d(e,s)});try{let t=h.identity;if(t.startTime===null)throw new e(`COMMAND_FAILED`,`This host cannot pin its runtime identity.`,{reason:`host_instance_unreadable`,pid:t.pid,hint:`Use a detached daemon on this platform.`});let r=Object.freeze({stateDir:l,daemonLifecycle:`attach`,daemonTransport:`socket`,cwd:o.cwd,daemonBaseUrl:``,daemonBinding:Object.freeze({token:h.token,pid:t.pid,processStartTime:t.startTime})});return Object.freeze({client:n(r,{host:o}),clientConfig:r,close:()=>h.close()})}catch(e){throw await h.close({cause:e}).catch(()=>{}),e}}export{i as startAgentDevice};
|
package/dist/src/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as KnownAppErrorCode, A as Point, E as HostEnvironment, J as AppError, L as SnapshotNode, M as RawSnapshotNode, N as Rect, Q as ErrorCause, U as SnapshotState, X as AppErrorDetails, Y as AppErrorCode, et as NormalizedError, nt as isAgentDeviceError, q as centerOfRect, rt as normalizeAgentDeviceError, y as AppleOS } from "./sdk-contracts.js";
|
|
2
2
|
import { t as AppsFilter } from "./app-inventory.js";
|
|
3
|
-
import { $ as
|
|
3
|
+
import { $ as NetworkOptions, $t as AppOpenResult, A as WaitCommandOptions, An as JsonValue, At as TransformGestureOptions, B as GetOptions, Bt as CaptureSnapshotOptions, C as KeyboardCommandOptions, Cn as DaemonIdentity, Ct as RepeatedPressOptions, D as TelephonyCommandOptions, Dn as TargetShutdownResult, Dt as SwipeGestureOptions, E as ReactNativeCommandOptions, En as EnsureDaemonOptions, Et as SettleCommandOptions, F as SessionCloseResult, Ft as RefTarget, G as CommandRequestResult, Gt as AppCloseResult, H as IsStatePredicateOptions, Ht as FindSnapshotCommandOptions, I as SessionSaveScriptOptions, It as SelectorTarget, J as ReplayRunOptions, Jt as AppInstallFromSourceOptions, K as BatchRunOptions, Kt as AppDeployOptions, L as SessionSaveScriptResult, Lt as CaptureDiffOptions, M as AlertAction, Mt as ElementTarget, N as PermissionTarget, Nt as InteractionTarget, O as TvRemoteCommandOptions, On as JsonObject, Ot as SwipeOptions, P as SettingsUpdateOptions, Pt as PointTarget, Q as LogsOptions, Qt as AppOpenOptions, R as FindBaseOptions, Rt as CaptureScreenshotOptions, S as HomeCommandOptions, Sn as DaemonConnection, St as PressOptions, T as PrepareCommandOptions, Tn as DeviceCommandBaseOptions, Tt as ScrollOptions, U as IsTextPredicateOptions, Ut as SelectorSnapshotCommandOptions, V as IsOptions, Vt as CaptureSnapshotResult, W as RecordControlOptions, Wt as AppCloseOptions, X as AudioOptions, Xt as AppInstallOptions, Y as ReplayTestOptions, Yt as AppInstallFromSourceResult, Z as EventsOptions, Zt as AppListOptions, _ as BackCommandOptions, _n as AgentDeviceDaemonTransportContext, _t as GestureOptions, a as WaitCommandResult, an as DeviceSelectionSource, at as HumanControlHold, b as FoldCommandOptions, bn as AgentDeviceSelectionOptions, bt as PanOptions, c as DebugSymbolsOptions, cn as AgentDeviceCapabilitiesResult, ct as Lease, d as PrepareCommandResult, dn as AgentDeviceSessionDevice, dt as LeaseScopedOptions, en as AppPushOptions, et as PerfOptions, f as TriggerAppEventCommandResult, fn as DeviceBootOptions, ft as ClickOptions, g as AppSwitcherCommandOptions, gn as AgentDeviceDaemonTransport, gt as FocusOptions, h as AppStateCommandOptions, hn as AgentDeviceClientConfig, ht as FlingOptions, i as TraceCommandResult, in as DeviceSelectionReason, it as EndedLease, j as WaitCommandTarget, jn as isRecord, jt as TypeTextOptions, k as ViewportCommandOptions, kn as JsonPrimitive, kt as TapGestureOptions, l as DebugSymbolsResult, ln as AgentDeviceDevice, lt as LeaseAllocateOptions, m as AlertCommandOptions, mn as StartupPerfSample, mt as FillOptions, n as AgentDeviceCommandClient, nn as AppUninstallOptions, nt as TraceOptions, o as DiffSnapshotCommandResult, on as MaterializationReleaseOptions, ot as HumanControlHoldOptions, p as ActionButtonCommandOptions, pn as DeviceShutdownOptions, pt as DragOptions, q as BatchStep, qt as AppDeployResult, r as RecordingCommandResult, rn as DeviceSelectionMetadata, rt as CloudArtifactsOptions, s as DoctorCommandResult, sn as MaterializationReleaseResult, st as HumanControlHoldScope, t as AgentDeviceClient, tn as AppTriggerEventOptions, tt as RecordOptions, u as PushCommandResult, un as AgentDeviceSession, ut as LeaseOptions, v as ClipboardCommandOptions, vn as AgentDeviceIdentifiers, vt as HoverOptions, w as OrientationCommandOptions, wn as DaemonLifecycle, wt as RotateGestureOptions, x as HardwareButtonCommandOptions, xn as DaemonBinding, xt as PinchOptions, y as DoctorCommandOptions, yn as AgentDeviceRequestOverrides, yt as LongPressOptions, z as FindOptions, zt as CaptureScreenshotResult } from "./client-types.js";
|
|
4
4
|
import { i as CloudProviderSessionResult, t as AgentArtifactsResult } from "./cloud-artifacts.js";
|
|
5
5
|
import { c as MetroPrepareOptions, d as MetroReloadResult, l as MetroPrepareResult, m as MetroBridgeScope, u as MetroReloadOptions } from "./sdk-remote-config.js";
|
|
6
6
|
import { r as ReplaySuiteResult, t as ReplayCommandResult } from "./replay.js";
|
|
@@ -119,4 +119,4 @@ declare function ensureDaemon(options?: EnsureDaemonOptions): Promise<DaemonConn
|
|
|
119
119
|
/** Starts an in-process daemon, loading its runtime only when called. */
|
|
120
120
|
declare function startAgentDevice(options: StartAgentDeviceOptions): Promise<AgentDeviceHost>;
|
|
121
121
|
//#endregion
|
|
122
|
-
export { type ActionButtonCommandOptions, type AgentArtifactsResult, type AgentDeviceCapabilitiesResult, type AgentDeviceClient, type AgentDeviceClientConfig, type AgentDeviceCommandClient, type AgentDeviceDaemonTransport, type AgentDeviceDaemonTransportContext, type AgentDeviceDevice, type AgentDeviceHost, type AgentDeviceIdentifiers, type AgentDeviceRequestOverrides, type AgentDeviceSelectionOptions, type AgentDeviceSession, type AgentDeviceSessionDevice, type AlertAction, type AlertCommandOptions, type AppCloseOptions, type AppCloseResult, type AppDeployOptions, type AppDeployResult, AppError, type AppErrorCode, type AppErrorDetails, type AppInstallFromSourceOptions, type AppInstallFromSourceResult, type AppInstallOptions, type AppListOptions, type AppOpenOptions, type AppOpenResult, type AppPushOptions, type AppStateCommandOptions, type AppSwitcherCommandOptions, type AppTriggerEventOptions, type AppUninstallOptions, type AppleOS, type AppsFilter, type AudioOptions, type BackCommandOptions, type BatchRunOptions, type BatchRunResult, type BatchStep, type CaptureDiffOptions, type CaptureScreenshotOptions, type CaptureScreenshotResult, type CaptureSnapshotOptions, type CaptureSnapshotResult, type ClickOptions, type ClipboardCommandOptions, type CloudArtifactsOptions, type CloudProviderSessionResult, type CommandRequestResult, type DaemonBinding, type DaemonConnection, type DaemonIdentity, type DaemonLifecycle, type DebugSymbolsOptions, type DebugSymbolsResult, type DeviceBootOptions, type DeviceCommandBaseOptions, type DeviceSelectionMetadata, type DeviceSelectionReason, type DeviceSelectionSource, type DeviceShutdownOptions, type DiffSnapshotCommandResult, type DoctorCommandOptions, type DoctorCommandResult, type DragOptions, type ElementTarget, type EndedLease, type EnsureDaemonOptions, type ErrorCause, type EventsOptions, type FillOptions, type FindBaseOptions, type FindOptions, type FindSnapshotCommandOptions, type FlingOptions, type FocusOptions, type FoldCommandOptions, type GetOptions, type HomeCommandOptions, type HoverOptions, type HumanControlHold, type HumanControlHoldOptions, type HumanControlHoldScope, type InteractionTarget, type IsOptions, type IsStatePredicateOptions, type IsTextPredicateOptions, type JsonObject, type JsonPrimitive, type JsonValue, type KeyboardCommandOptions, type KnownAppErrorCode, type Lease, type LeaseAllocateOptions, type LeaseOptions, type LeaseScopedOptions, type LogsOptions, type LongPressOptions, type MaterializationReleaseOptions, type MaterializationReleaseResult, type MetroBridgeScope, type MetroPrepareOptions, type MetroPrepareResult, type MetroReloadOptions, type MetroReloadResult, type NetworkOptions, type NormalizedError, type OrientationCommandOptions, type PanOptions, type PerfOptions, type PermissionTarget, type PinchOptions, type Point, type PointTarget, type PrepareCommandOptions, type PrepareCommandResult, type PressOptions, type PushCommandResult, type RawSnapshotNode, type ReactNativeCommandOptions, type RecordControlOptions, type RecordOptions, type RecordingCommandResult, type Rect, type RefTarget, type RepeatedPressOptions, type ReplayCommandResult, type ReplayRunOptions, type ReplaySuiteResult, type ReplayTestOptions, type RotateGestureOptions, type ScrollOptions, type SelectorSnapshotCommandOptions, type SelectorTarget, type SessionCloseResult, type SessionSaveScriptOptions, type SessionSaveScriptResult, type SettingsUpdateOptions, type SettleCommandOptions, type SnapshotNode, type SnapshotState, type StartAgentDeviceOptions, type StartupPerfSample, type SwipeGestureOptions, type SwipeOptions, type TargetShutdownResult, type TelephonyCommandOptions, type TraceCommandResult, type TraceOptions, type TransformGestureOptions, type TriggerAppEventCommandResult, type TvRemoteCommandOptions, type TypeTextOptions, type ViewportCommandOptions, type WaitCommandOptions, type WaitCommandResult, type WaitCommandTarget, centerOfRect, createAgentDeviceClient, createLocalArtifactAdapter, ensureDaemon, isAgentDeviceError, type isRecord, isUnreadableCaptureContentError, normalizeAgentDeviceError, startAgentDevice };
|
|
122
|
+
export { type ActionButtonCommandOptions, type AgentArtifactsResult, type AgentDeviceCapabilitiesResult, type AgentDeviceClient, type AgentDeviceClientConfig, type AgentDeviceCommandClient, type AgentDeviceDaemonTransport, type AgentDeviceDaemonTransportContext, type AgentDeviceDevice, type AgentDeviceHost, type AgentDeviceIdentifiers, type AgentDeviceRequestOverrides, type AgentDeviceSelectionOptions, type AgentDeviceSession, type AgentDeviceSessionDevice, type AlertAction, type AlertCommandOptions, type AppCloseOptions, type AppCloseResult, type AppDeployOptions, type AppDeployResult, AppError, type AppErrorCode, type AppErrorDetails, type AppInstallFromSourceOptions, type AppInstallFromSourceResult, type AppInstallOptions, type AppListOptions, type AppOpenOptions, type AppOpenResult, type AppPushOptions, type AppStateCommandOptions, type AppSwitcherCommandOptions, type AppTriggerEventOptions, type AppUninstallOptions, type AppleOS, type AppsFilter, type AudioOptions, type BackCommandOptions, type BatchRunOptions, type BatchRunResult, type BatchStep, type CaptureDiffOptions, type CaptureScreenshotOptions, type CaptureScreenshotResult, type CaptureSnapshotOptions, type CaptureSnapshotResult, type ClickOptions, type ClipboardCommandOptions, type CloudArtifactsOptions, type CloudProviderSessionResult, type CommandRequestResult, type DaemonBinding, type DaemonConnection, type DaemonIdentity, type DaemonLifecycle, type DebugSymbolsOptions, type DebugSymbolsResult, type DeviceBootOptions, type DeviceCommandBaseOptions, type DeviceSelectionMetadata, type DeviceSelectionReason, type DeviceSelectionSource, type DeviceShutdownOptions, type DiffSnapshotCommandResult, type DoctorCommandOptions, type DoctorCommandResult, type DragOptions, type ElementTarget, type EndedLease, type EnsureDaemonOptions, type ErrorCause, type EventsOptions, type FillOptions, type FindBaseOptions, type FindOptions, type FindSnapshotCommandOptions, type FlingOptions, type FocusOptions, type FoldCommandOptions, type GestureOptions, type GetOptions, type HardwareButtonCommandOptions, type HomeCommandOptions, type HoverOptions, type HumanControlHold, type HumanControlHoldOptions, type HumanControlHoldScope, type InteractionTarget, type IsOptions, type IsStatePredicateOptions, type IsTextPredicateOptions, type JsonObject, type JsonPrimitive, type JsonValue, type KeyboardCommandOptions, type KnownAppErrorCode, type Lease, type LeaseAllocateOptions, type LeaseOptions, type LeaseScopedOptions, type LogsOptions, type LongPressOptions, type MaterializationReleaseOptions, type MaterializationReleaseResult, type MetroBridgeScope, type MetroPrepareOptions, type MetroPrepareResult, type MetroReloadOptions, type MetroReloadResult, type NetworkOptions, type NormalizedError, type OrientationCommandOptions, type PanOptions, type PerfOptions, type PermissionTarget, type PinchOptions, type Point, type PointTarget, type PrepareCommandOptions, type PrepareCommandResult, type PressOptions, type PushCommandResult, type RawSnapshotNode, type ReactNativeCommandOptions, type RecordControlOptions, type RecordOptions, type RecordingCommandResult, type Rect, type RefTarget, type RepeatedPressOptions, type ReplayCommandResult, type ReplayRunOptions, type ReplaySuiteResult, type ReplayTestOptions, type RotateGestureOptions, type ScrollOptions, type SelectorSnapshotCommandOptions, type SelectorTarget, type SessionCloseResult, type SessionSaveScriptOptions, type SessionSaveScriptResult, type SettingsUpdateOptions, type SettleCommandOptions, type SnapshotNode, type SnapshotState, type StartAgentDeviceOptions, type StartupPerfSample, type SwipeGestureOptions, type SwipeOptions, type TapGestureOptions, type TargetShutdownResult, type TelephonyCommandOptions, type TraceCommandResult, type TraceOptions, type TransformGestureOptions, type TriggerAppEventCommandResult, type TvRemoteCommandOptions, type TypeTextOptions, type ViewportCommandOptions, type WaitCommandOptions, type WaitCommandResult, type WaitCommandTarget, centerOfRect, createAgentDeviceClient, createLocalArtifactAdapter, ensureDaemon, isAgentDeviceError, type isRecord, isUnreadableCaptureContentError, normalizeAgentDeviceError, startAgentDevice };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{R as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{R as e}from"./sdk-contracts.js";import{ct as t}from"./tv-remote.js";import{V as n}from"./sdk-io.js";import"./retry.js";import{runHarmonyShell as r}from"./hdc.js";import{invalidateHarmonyGestureViewport as i,readHarmonyGestureViewport as a}from"./snapshot2.js";async function o(e,t,n){await r(e,[`uitest`,`uiInput`,`click`,t,n])}async function s(e,t,n){await r(e,[`uitest`,`uiInput`,`doubleClick`,t,n])}async function c(e,t,n,i=800){await r(e,[`uitest`,`uiInput`,`longClick`,t,n])}async function l(e,t,i=0){await r(e,[`uitest`,`uiInput`,`text`,t]),i>0&&await n(i)}async function u(e,t,i,a,o=0){await r(e,[`uitest`,`uiInput`,`inputText`,t,i,a]),o>0&&await n(o)}async function d(e,n,i){let o=await a(e),s=t({direction:n,amount:i?.amount,pixels:i?.pixels,referenceWidth:o.width,referenceHeight:o.height});return await r(e,[`uitest`,`uiInput`,`swipe`,s.x1,s.y1,s.x2,s.y2,i?.durationMs??300]),s}async function f(t,n){if(n.topology!==`single`)throw new e(`UNSUPPORTED_OPERATION`,`HarmonyOS HDC does not support multi-touch gestures`);let i=n.pointers[0].samples,a=i[0],o=i.at(-1);if(!a||!o)throw new e(`COMMAND_FAILED`,`HarmonyOS gesture plan has no pointer endpoints`);let s=Math.hypot(o.point.x-a.point.x,o.point.y-a.point.y),c=Math.max(200,Math.min(4e4,Math.round(s/n.durationMs*1e3))),l=n.intent===`fling`?`fling`:`swipe`;return await r(t,[`uitest`,`uiInput`,l,Math.round(a.point.x),Math.round(a.point.y),Math.round(o.point.x),Math.round(o.point.y),c]),{backend:`harmonyos-hdc-uiinput`,command:l,velocity:c,viewport:n.viewport}}async function p(e){await r(e,[`uitest`,`uiInput`,`keyEvent`,`Back`]),i(e)}async function m(e){await r(e,[`uitest`,`uiInput`,`keyEvent`,`Home`]),i(e)}async function h(e){await r(e,[`uitest`,`uiInput`,`keyEvent`,`Recent`]),i(e)}async function g(e,t){if(t===`Back`){await p(e);return}await r(e,[`uitest`,`uiInput`,`keyEvent`,t])}async function _(t,n){throw new e(`UNSUPPORTED_OPERATION`,`HarmonyOS orientation control is not available through the public HDC API.`)}export{h as appSwitcherHarmony,p as backHarmony,s as doubleClickHarmony,u as fillHarmony,m as homeHarmony,c as longPressHarmony,f as performHarmonyGesture,o as pressHarmony,g as pressHarmonyKeyboardKey,d as scrollHarmony,_ as setHarmonyOrientation,l as typeHarmony};
|