agent-device
Version:
Open source device layer for AI coding agents: a CLI, MCP server, and typed Node.js API to control mobile, web, TV, and desktop apps on devices and simulators, locally or in the cloud.
1 lines • 16.5 kB
JavaScript
import{On as e}from"./sdk-batch.js";import{j as t,v as n}from"./sdk-contracts.js";import{St as r,ht as i}from"./sdk-io.js";import"./diagnostics.js";import{J as a,Z as o}from"./sdk-device.js";import"./file.js";import{a as s}from"./verified-file.js";import{i as c,n as l,r as u}from"./durable-resource.js";import d from"node:fs";import f from"node:path";function p(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function m(e){return e.replaceAll(`-`,`_`)}async function h(e,t,n){let r={kind:`pending`};try{t.binding.assertAdoptable();let i=C(b(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 g(e,t,n,r,i),i}}async function g(e,t,n,r,i){let a=t.binding.canPersist(),o=r.kind!==`pending`||a&&ee(e,t,n),s=_(e,t,n,await v(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&&ne(e,t,i,s.cleanupError)}function _(e,t,n,i){try{return{confirmed:S(e,n,t.fence,i),cleanupError:i}}catch(n){return r({level:`error`,phase:`${m(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 v(e,t){try{t.kind===`transferred`?await t.handle[Symbol.asyncDispose]():await e.pendingHandle[Symbol.asyncDispose]();return}catch(e){return e}}function ee(e,t,n){try{return e.store.write(n,te(e,t)),!0}catch(i){try{return e.store.write(n,y(e,t,{version:0,body:{reason:`runtime-contract-invalid`}})),!0}catch(n){return r({level:`error`,phase:`${m(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 te(e,t){try{return C(b(e,t),`active`)}catch{return y(e,t,t.envelope.descriptor)}}function y(e,t,n){return u({resourceKind:e.resourceKind,sessionId:t.binding.address,device:a(t.device),owner:t.owner,fence:t.fence,lifecycle:`open`,descriptor:n,metadata:{phase:`runtime-contract-invalid`,runtimeContractInvalid:!0}})}function b(e,t){let r=c(t.envelope);if(r.status===`decoded`&&x(r.envelope,t,e.resourceKind))return r.envelope;throw new n(`COMMAND_FAILED`,`${p(e.displayName)} runtime returned an incoherent durable envelope`,{reason:`runtime-contract-invalid`,hint:`Retain the runtime diagnostics and report the selected device and owner.`})}function x(t,n,r){return t.resourceKind===r&&t.sessionId===n.binding.address&&o(t.device,a(n.device))&&e(t.owner)===e(n.owner)&&t.fence.token===n.fence.token&&t.fence.generation===n.fence.generation&&t.lifecycle===`open`}function S(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 ne(e,t,n,i){r({level:`error`,phase:`${m(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 C(e,t){return Object.freeze({...e,lifecycle:`open`,metadata:{...e.metadata??{},phase:t}})}async function w(e){e.scope.signal.throwIfAborted(),e.scope.checkDeadline?.();let t=Date.now()+e.deadlineMs,n=new AbortController,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=()=>{if(c.signal.aborted)return;let t=new O(e.displayName,e.deadlineMs);n.abort(t),r(t)},c={...e.scope,signal:AbortSignal.any([e.scope.signal,n.signal]),checkDeadline:()=>{c.signal.throwIfAborted(),e.scope.checkDeadline?.(),Date.now()>=t&&s(),c.signal.throwIfAborted()}},l=setTimeout(s,Math.max(0,t-Date.now()));l.unref?.();let u=E(e,c),d,f=u.then(e=>(d??={kind:`acquisition`},e),e=>{throw d??={kind:`acquisition-error`},e}),p=i.catch(e=>{throw d??={kind:`deadline`,error:e},e}),m=o.catch(e=>{throw d??={kind:`cancellation`,error:e},e});try{return await Promise.race([f,p,m])}finally{if(clearTimeout(l),a(),d?.kind===`deadline`||d?.kind===`cancellation`){let t=d.error;u.then(n=>T(e,n,t),()=>{}).catch(()=>{})}else u.catch(()=>{})}}async function T(e,t,n){try{t.reattached.status===`active`&&await D(e,t.reattached.handle,`late_handle_cleanup_failed`,n)}finally{await D(e,t.control,`late_control_cleanup_failed`,n)}}async function E(e,t){let n,r;try{return n=await e.acquireControl(e.envelope,t),t.signal.throwIfAborted(),t.checkDeadline?.(),r=await n.reattach(e.envelope),t.signal.throwIfAborted(),t.checkDeadline?.(),{control:n,reattached:r}}catch(t){try{r?.status===`active`&&await D(e,r.handle,`late_handle_cleanup_failed`,t)}finally{n&&await D(e,n,`late_control_cleanup_failed`,t)}throw t}}async function D(e,t,n,r){try{await t[Symbol.asyncDispose]()}catch(t){e.onLateCleanupFailure(n,t,r)}}var O=class extends Error{deadlineMs;constructor(e,t){super(`${p(e)} recovery exceeded its ${t}ms deadline`),this.name=`DurableCaptureRecoveryDeadlineError`,this.deadlineMs=t}};const k=new Map;async function A(e){return await re(e.resourcePath,async()=>{let t=j(e.store,e.resourcePath,e.expected);if(t.envelope.lifecycle===`completed`)return await e.onCompleted({envelope:t.envelope});let n=t.envelope,r=!0;try{return await e.run({get envelope(){return n},transition(t,i={}){let a=j(e.store,e.resourcePath,e.expected);if(a.envelope.lifecycle===`completed`)throw P(e.store);if(!r)throw ie(e.store);return n=Object.freeze({...a.envelope,lifecycle:t,...i.descriptor===void 0?{}:{descriptor:i.descriptor},...i.metadata===void 0?{}:{metadata:i.metadata}}),e.store.write(e.resourcePath,n),n}})}finally{r=!1}})}function j(e,t,n){let r=e.read(t);if(r.status!==`decoded`)throw N(e,r.status===`missing`?`${e.displayName} resource record is missing`:`${e.displayName} resource record is unreattachable: ${r.message}`);if(!M(r.envelope.fence,n))throw N(e,`${e.displayName} resource ownership fence was lost`);return r}function M(e,t){return e.token===t.token&&e.generation===t.generation}async function re(e,t){let n=k.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);k.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),k.get(e)===a&&k.delete(e)}}function N(e,t){return new n(`COMMAND_FAILED`,t,{reason:`ownership-fence-lost`,retriable:!1,hint:`Use the current ${e.displayName.toLowerCase()} resource owner or retain the recovery record for manual recovery.`})}function ie(e){return N(e,`${e.displayName} resource fence was released with its run`)}function ae(e){return e instanceof n&&e.details?.reason===`resource-already-completed`}function P(e){return new n(`COMMAND_FAILED`,`${e.displayName} resource record is already completed`,{reason:`resource-already-completed`,retriable:!1,hint:`Read the completed ${e.displayName.toLowerCase()} record instead of finishing or cleaning it again.`})}async function oe(e,t,r){let i=t.binding.read();if(!i)throw new n(`INVALID_ARGS`,e.messages.noActive);let a=!1;try{let n=await F(e,{handle:i.handle,fence:i.envelope.fence,resourcePath:r,intent:t.intent,onCleanupPending:()=>{a=!0}});return a||t.binding.clear(i),n}catch(n){let o=e.store.read(r);throw!a&&o.status===`decoded`&&o.envelope.lifecycle===`completed`&&t.binding.clear(i),n}}async function F(e,n){return await A({store:e.store,resourcePath:n.resourcePath,expected:n.fence,onCompleted:async({envelope:i})=>{let a;try{a=await n.handle.forceCleanup()}catch(e){a={status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:t(e)}}if(!l(a)&&(n.onCleanupPending?.(a),r({level:`warn`,phase:`${m(e.resourceKind)}_terminal_cleanup_pending`,data:{resourcePath:n.resourcePath,cleanup:a}}),n.intent===`disposal`))throw W(e,a);let o=await e.completionFromMetadata?.(i.metadata);if(o!==void 0)return o;throw l(a)?P(e.store):W(e,a)},run:async t=>{q(t);let r=K(t),i;try{i=await n.handle.finish(r)}catch(r){throw await I(e,t,n,r,n.intent),r}if(i.status===`completed`)return G(e,t,i),i.result;G(e,t,i);let a=W(e,i);throw await I(e,t,n,a,n.intent),a}})}async function I(e,t,n,r,i){if(i===`capture`&&e.failedFinishPolicy===`preserve-retry-material`){R(e,n,r);return}let a;try{a=await n.handle.forceCleanup()}catch(i){z(e,n,r,i,L(t,i));return}try{H(t,a)}catch(t){z(e,n,r,a.status===`cleanup-pending`?a.message??a.reason:`cleanup returned ${a.status}`,t);return}l(a)||z(e,n,r,a.message)}function L(e,n){try{H(e,{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:t(n)});return}catch(e){return e}}function R(e,n,i){r({level:`error`,phase:`${m(e.resourceKind)}_finish_evidence_preserved`,data:{resourcePath:n.resourcePath,finishError:t(i),failedFinishPolicy:e.failedFinishPolicy}})}function z(e,n,i,a,o){r({level:`error`,phase:`${m(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 B(e,t){let n=t.binding.read();n&&(U(e,await A({store:e.store,resourcePath:t.resourcePath,expected:n.envelope.fence,onCompleted:async()=>await n.handle.forceCleanup(),run:async e=>{q(e);let t=await n.handle.forceCleanup();return H(e,t),t}})),t.binding.clear(n))}async function V(e,t){return await A({store:e.store,resourcePath:t.resourcePath,expected:t.envelope.fence,onCompleted:()=>({status:`already-missing`}),run:async e=>{let n=await t.cleanup();return H(e,n),n}})}function H(e,t){e.transition(l(t)?`completed`:`open`,{metadata:{...e.envelope.metadata??{},phase:l(t)?`completed`:`cleanup-pending`,cleanupStatus:t.status,...t.status===`cleanup-pending`?{cleanupPendingReason:t.reason,...t.message?{cleanupPendingMessage:t.message}:{}}:{}}})}function U(e,t){if(!l(t))throw W(e,t)}function W(e,t){return new n(`COMMAND_FAILED`,t.message??`${p(e.displayName)} cleanup could not be confirmed`,{reason:t.reason,cleanupStatus:t.status,retriable:t.reason!==`ownership-fence-lost`,hint:e.messages.cleanupPendingHint})}function G(e,t,n){if(n.status===`completed`){t.transition(`completed`,{metadata:{...t.envelope.metadata??{},...e.completionMetadata(n.result),phase:`completed`}});return}H(t,n)}function K(e){return Object.freeze({learned:e.envelope.metadata,record:t=>{e.transition(`open`,{metadata:{...e.envelope.metadata??{},...t}})}})}function q(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}async function se(e){let t=e.definition.store.list(e.sessionsDir),n=[];for(let r of t)n.push(e.scope.signal.aborted?`retained`:await J(e,r));return{scanned:t.length,recovered:n.filter(e=>e===`recovered`).length,retained:n.filter(e=>e===`retained`).length}}async function J(e,t){let n=ce(e,t);if(n.status!==`recoverable`)return n.status;try{return await le(e,t,n.envelope,e.acquisitionDeadlineMs??5e3)?`recovered`:`retained`}catch(n){return Z(e,n instanceof O?`timed_out`:`failed`,t,{error:n instanceof Error?n.message:String(n),...n instanceof O?{deadlineMs:n.deadlineMs}:{}}),`retained`}}function ce(e,t){let n=e.definition.store.read(t);if(n.status===`unreattachable`)return Z(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 f.resolve(t)===f.resolve(r)?{status:`recoverable`,envelope:n.envelope}:(Z(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 w({displayName:e.definition.displayName,envelope:n,scope:e.scope,deadlineMs:r,acquireControl:e.acquireControl,onLateCleanupFailure:(n,r,i)=>Z(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 A({store:e.definition.store,resourcePath:t,expected:n.fence,onCompleted:async()=>await i.forceCleanup(),run:async e=>{q(e);let t=await i.forceCleanup();return H(e,t),t}});return l(a)}case`completed`:return await Y(e,t,n,{...e.definition.completionMetadata(r.reattached.result)}),!0;case`missing`:return await Y(e,t,n,{recoveryStatus:`already-missing`}),!0;case`unreattachable`:{if(!X(r.reattached.reason))return Z(e,`retained`,t,{reason:r.reattached.reason,message:r.reattached.message}),!1;let i=await V(e.definition,{envelope:n,resourcePath:t,cleanup:()=>r.control.cleanup(n)});return l(i)}}}finally{await r.control[Symbol.asyncDispose]()}}async function Y(e,t,n,r){await A({store:e.definition.store,resourcePath:t,expected:n.fence,onCompleted:()=>void 0,run:async e=>{e.transition(`completed`,{metadata:{...e.envelope.metadata??{},phase:`completed`,...r}})}})}function X(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 Z(e,t,n,i){let a={phase:`${m(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 de(e,r){let i=e.store.read(r.resourcePath);if(i.status!==`decoded`||i.envelope.lifecycle!==`open`)throw fe(e,i.status);let a=i.envelope,o=await w({displayName:e.displayName,envelope:a,scope:r.scope,deadlineMs:r.deadlineMs??5e3,acquireControl:r.acquireControl,onLateCleanupFailure:(n,i,a)=>r.scope.diagnostics.emit({level:`error`,phase:`${m(e.resourceKind)}_recovery_${n}`,data:{resourcePath:r.resourcePath,error:t(i),primaryError:t(a)}})});try{switch(o.reattached.status){case`active`:return await F(e,{handle:o.reattached.handle,fence:a.fence,resourcePath:r.resourcePath,intent:`capture`});case`completed`:{let t=o.reattached.result;return await A({store:e.store,resourcePath:r.resourcePath,expected:a.fence,onCompleted:()=>void 0,run:async n=>{G(e,n,{status:`completed`,result:t,alreadyCompleted:!0})}}),t}case`missing`:throw new n(`COMMAND_FAILED`,`${p(e.displayName)} is missing`,{reason:`resource-missing`,hint:e.messages.cleanupPendingHint});case`unreattachable`:throw X(o.reattached.reason)&&U(e,await V(e,{envelope:a,resourcePath:r.resourcePath,cleanup:()=>o.control.cleanup(a)})),new n(`COMMAND_FAILED`,o.reattached.message??`${p(e.displayName)} cannot be reattached`,{reason:o.reattached.reason,hint:e.messages.cleanupPendingHint})}}finally{await o.control[Symbol.asyncDispose]()}}function fe(e,t){return new n(`INVALID_ARGS`,t===`missing`?e.messages.noActive:`${p(e.displayName)} recovery record is not open`)}function pe(e){he(e.fileName);let t=t=>f.join(t,e.fileName);return Object.freeze({resourceKind:e.resourceKind,displayName:e.displayName,resolvePath:t,read(t){let n,r;try{if(n=s(t),n===void 0)return{status:`missing`};r=JSON.parse(d.readFileSync(n,`utf8`))}catch(t){return $(t)?{status:`missing`}:Q(_e(t,e.displayName))}finally{n!==void 0&&d.closeSync(n)}return me(c(r),e.resourceKind)},write(e,t){let n=f.dirname(e);d.mkdirSync(n,{recursive:!0}),i({destination:e,contents:`${JSON.stringify(t)}\n`})},list(e){let n;try{n=d.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(n=>t(f.join(e,n.name))).filter(ge).sort()}})}function me(e,t){return e.status===`decoded`?e.envelope.resourceKind===t?{status:`decoded`,envelope:e.envelope}:Q(`Expected ${t} resource record, received ${e.envelope.resourceKind}`):e}function he(e){if(e.length===0||f.basename(e)!==e)throw TypeError(`Durable capture resource fileName must be one file name`)}function ge(e){try{return d.lstatSync(e),!0}catch(e){return!$(e)}}function Q(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function $(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`}export{oe as a,h as c,se as i,p as l,de as n,B as o,J as r,ae as s,pe as t};