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.
4 lines • 31.1 kB
JavaScript
import{C as e,Er as t,N as n,Nn as r,Tr as i,dr as a}from"./sdk-batch.js";import{B as o,Z as s,v as c}from"./sdk-contracts.js";import{g as l}from"./sdk-batch-runner.js";import{St as u,gt as ee,wt as d}from"./sdk-io.js";import"./diagnostics.js";import{R as te,p as f}from"./sdk-device.js";import{r as ne}from"./success-text.js";import{s as re}from"./script.js";import{a as ie,c as p,d as m,f as ae,i as oe,l as se,m as h,o as ce,p as g,s as le,t as ue,v as _}from"./open-script.js";import{i as de}from"./vars.js";import{A as v,D as fe,E as pe,F as me,G as he,H as y,L as ge,M as _e,N as ve,O as ye,P as be,T as xe,U as Se,W as Ce,a as we,b as Te,c as Ee,f as De,j as Oe,k as ke,n as Ae,q as je,r as Me,t as Ne,u as Pe,w as b}from"./parameterized-recorded-fill.js";import{n as Fe}from"./catalog.js";import{a as Ie}from"./flag-registry.js";import{l as Le,u as Re}from"./file.js";import{a as ze}from"./daemon-resolution.js";import{n as Be,r as x}from"./session-paths.js";import{a as Ve,i as He,r as Ue}from"./session-artifact-paths.js";import{i as We,r as Ge,t as Ke}from"./session-repair-tombstone.js";import{a as qe,n as Je,t as Ye}from"./session-event-action.js";import Xe,{createHash as Ze,randomUUID as Qe}from"node:crypto";import S from"node:fs";import C from"node:path";import{StringDecoder as $e}from"node:string_decoder";function et(e,t={}){let n=[e.command];return e.command===`snapshot`?se(n,e):e.command===`open`?ue(n,e):e.command===`runtime`?ce(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?ie(n,e):e.command===`screenshot`?le(n,e):oe(n,e),n.join(` `)}function tt(e){return e.targetEvidences?[i(e.targetEvidences)]:e.targetEvidence?[t(e.targetEvidence)]:[]}function w(e){return e?.scriptPublication??b}function nt(e,t,n){let r=w(e),i=typeof t.saveScript==`string`?Re(t.saveScript,{cwd:n}):r.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=pe(r,{requested:{path:i,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function rt(e){e.scriptPublication=ye(w(e))}function it(e){e.scriptPublication=_e(w(e))}function at(e,t){e.scriptPublication=ve(w(e),t)}function ot(e){e.scriptPublication=xe(w(e))}function st(e,t){let n=w(e);return n.kind===`repair`&&n.closeReceipt===t}function T(e){return w(e).kind===`repair`}function E(e){return Oe(w(e))}function D(e){return be(w(e))}function O(e){return me(w(e))}function ct(e,t,n){if(t.flags?.noRecord||Se(t.flags)&&t.flags.recordAs===void 0||yt(e,t))return;t.flags&&Pe(e,t.flags,n);let r=ft(t),{entry:i,echoedNames:a}=ht(e,pt(t,r)),o=[...new Set([...r?[r.variableName]:[],...a])];r&&mt(e,r);let s=lt(i,o);return e.actions.push(s),u({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),s}function lt(e,t){let n=ut(e);return{ts:Date.now(),command:e.command,positionals:e.positionals,runtime:e.runtime,flags:xt(e.flags),result:e.result,...n?{publicationIntent:n}:{},...e.targetEvidence?{targetEvidence:e.targetEvidence}:{},...e.targetEvidences?{targetEvidences:e.targetEvidences}:{},...t.length>0?{livePlaceholders:t}:{}}}function ut(e){if(A.has(e.command))return e.interactiveObservation===!1?`authored`:e.flags.record===!0?`explicit-record`:void 0}function dt(e,t,n,r,i,a){!t||!e.resolveCurrent(t)||e.recordAction(t,{command:r,positionals:a?.positionals??n.positionals??[],flags:a?.flags??n.flags??{},result:i??{}})}function ft(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=je(e.flags.recordAs),n=he(t);return{literal:y({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n,variableName:t}}function pt(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:_t(e.positionals,r),result:Ne(e.result,n,r),targetEvidence:Ae(e.targetEvidence,n,r)}}function mt(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function ht(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return{entry:t,echoedNames:[]};let{payload:r,insertedPlaceholders:i}=Me(t.result,n),a=(t.targetEvidenceMode??`action`)===`landmark`?gt(t.targetEvidence,n):k(t.targetEvidence,n),o=t.targetEvidences?{source:k(t.targetEvidences.source,n),destination:k(t.targetEvidences.destination,n)}:t.targetEvidences;return{entry:{...t,result:r,targetEvidence:a,targetEvidences:o},echoedNames:[...i].flatMap(e=>Ce(e)??[])}}function gt(e,t){return e&&(Ee(e,t)?void 0:e)}function k(e,t){return!e||!Ee(e,t)?e:{...we(e,t),verification:`unverifiable`}}function _t(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const A=new Set([`snapshot`,`get`,`is`,`find`]);function vt(e){return e.internal?.replayPlanStep!==!0&&A.has(e.command)}function yt(e,t){return!t.interactiveObservation||D(e)===void 0?!1:t.flags.record!==!0}const bt=Ie();function xt(e){if(!e)return{};let t={};for(let n of bt){let r=e[n];r!==void 0&&(t[n]=r)}return t}function j(e){return C.join(e,`idle-expiry.json`)}function St(e){let t;try{t=S.readFileSync(e,`utf8`)}catch{return}let n;try{n=JSON.parse(t)}catch{return}if(!(typeof n?.expiresAt!=`number`||!Number.isFinite(n.expiresAt))&&!(n.expiresAt<=Date.now())&&typeof n.owner==`string`&&!(!M(n.expiredAtMs)||!M(n.idleExpiryMs))&&(n.deviceKey===void 0||typeof n.deviceKey==`string`))return n}function M(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}function Ct(t){let n=t.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new c(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(t.some(e=>e.command===`close`))throw new c(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[n,i]of t.entries())e({command:i.command,positionals:i.positionals,flags:i.flags})===`mutates-app`&&(r=n);if(!t.slice(r+1).some(Ot))throw new c(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function wt(t){for(let n of t){if(Tt(n)){Et(n);continue}let t=kt(n),i=t??(n.command===`wait`?n.positionals[0]:void 0);if(i?.startsWith(`@`))throw new c(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&e(n)===`mutates-app`)throw new c(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let a=t;if(!(!a||!r(a)||n.targetEvidence))throw new c(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${a}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function Tt(e){return N(e)!==void 0}function Et(e){let t=N(e);if(!t)return;let n=[t.source,t.destination];for(let t of n){if(t?.startsWith(`@`))throw new c(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${t}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!t||!r(t))&&!e.targetEvidences)throw new c(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${t}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function N(e){return e.command===`gesture`?re(e.positionals):void 0}function Dt(e,t){if(e instanceof c){if(e.details?.reason===`script_target_exists`)return new c(e.code,`A file already exists at ${String(e.details.path)}.`,{...e.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let t=e.details?.retriable===!0;return new c(e.code,e.message,{...e.details,retriable:t,hint:e.details?.hint??(t?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let n=e instanceof Error?e.message:String(e);return new c(`COMMAND_FAILED`,`Failed to publish the active session script${t?` to ${t}`:``}: ${n}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Ot(e){if(e.command!==`wait`)return!1;let t=n(e.positionals);return t?.kind!==`selector`||!r(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function kt(e){if(e.command===`get`)return e.positionals[1];if(h(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&P(t)&&P(n)?void 0:t}}function P(e){return e.trim().length>0&&Number.isFinite(Number(e))}function At(e){let t=e.scriptPublication??b;return t.kind===`repair`?t.status===`committed`||!v(t):!1}function jt(e){return!ke(e.scriptPublication??b)||At(e)}var Mt=class{sessionsDir;hostCwd;constructor(e,t){this.sessionsDir=e,this.hostCwd=t}write(e,t){let n=T(e),r=t?.publication===`active`,i;try{if(jt(e))return{written:!1};let a=Nt(e,{appendCompleteSentinel:n,activePublication:r}),o=e.scriptPublication?.kind===`authoring`&&e.scriptPublication.remoteDelivery;i=o?this.remoteScriptPath():this.resolveScriptPath(e);let s=!o&&ge(e.scriptPublication??b)!==void 0;if(!s){let e=C.dirname(i);S.existsSync(e)||S.mkdirSync(e,{recursive:!0})}let c=Lt({scriptPath:i,script:a.script,force:t?.force,callerOwnsDestination:s,...o?{mode:384}:{}});return n&&(e.scriptPublication=fe(e.scriptPublication??b)),{written:!0,path:c,actionCount:a.actionCount}}catch(t){return Pt({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}remoteScriptPath(){let e=C.join(this.sessionsDir,`remote-scripts`);return S.mkdirSync(e,{recursive:!0,mode:448}),S.chmodSync(e,448),C.join(e,`${Xe.randomUUID()}.ad`)}resolveScriptPath(e){let t=ge(e.scriptPublication??b);if(t)return Re(t,{cwd:this.hostCwd});let n=x(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return C.join(this.sessionsDir,`${n}-${r}.ad`)}};function Nt(e,t){let n=Rt(e,{strictPortableRefs:t.activePublication});return t.activePublication&&Ct(n),{script:Jt(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Pt(e){let{session:t,error:n,scriptPath:r,repairArmed:i,activePublication:a}=e;return u({level:`warn`,phase:`session_script_write_failed`,data:{session:t.name,path:r,error:n instanceof Error?n.message:String(n)}}),i?{written:!1,error:It(n,r)}:a?{written:!1,error:Dt(n,r)}:{written:!1,error:Ft(n,r)}}function Ft(e,t){if(e instanceof c)return e;let n=e instanceof Error?e.message:String(e);return new c(`COMMAND_FAILED`,`Failed to write the session script${t?` to ${t}`:``}: ${n}`,{reason:`script_write_failed`,...t?{path:t}:{},hint:`Check the target path and its permissions, then re-record with open --save-script.`},e)}function It(e,t){if(e instanceof c)return e;let n=e instanceof Error?e.message:String(e);return new c(`COMMAND_FAILED`,`Failed to write the healed script${t?` to ${t}`:``}: ${n}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function Lt(e){let{scriptPath:t,script:n,force:r,mode:i,callerOwnsDestination:a}=e;try{return a?Le({destination:t,contents:n,publish:r?`replace`:`link-exclusive`}):(ee({destination:t,contents:n,publish:r?`replace`:`link-exclusive`,...i===void 0?{}:{mode:i}}),t)}catch(e){throw e.code===`EEXIST`?new c(`COMMAND_FAILED`,`A file already exists at ${t}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:t}):e}}function Rt(e,t={}){let n=D(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`&&n.publicationIntent!==`authored`&&!(r&&n.publicationIntent===`explicit-record`))continue;let i=Vt(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&zt(n);let o=qt(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&wt(a),a}function zt(e){let t=e.command===`gesture`?re(e.positionals??[]):void 0;if(t){Bt(t);return}if(!F(e.command))return;let n=e.command===`get`?e.positionals?.[1]:e.positionals?.[0];if(n?.startsWith(`@`))throw new c(`COMMAND_FAILED`,`Cannot write recorded step "${e.command} ${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Bt(e){let t=[e.source,e.destination].find(e=>e.startsWith(`@`));if(t)throw new c(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${t}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Vt(e){let t=Ht(e);if(!(!t||!F(e.command)))return g(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Wt(e,t):e.command===`fill`?Ut(e,t):Gt(e,t)}function Ht(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return a(t)}function F(e){return h(e)||e===`fill`||e===`get`}function Ut(e,t){return typeof e.result?.text==`string`||(e.positionals?.length??0)>1?{...e,positionals:[t,y(e)]}:void 0}function Wt(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):Kt(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Gt(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function Kt(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function qt(e,t){if(!F(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r},...t.livePlaceholders?{livePlaceholders:t.livePlaceholders}:{}}}function Jt(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${te(e.device)} device=${ae(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...tt(e)),r.push(Yt(de(e,new Set(e.livePlaceholders)))));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
`)}\n`}function Yt(e){return Xt([e.command],e)||et(e)}function Xt(e,t){if(g(t.command))return Zt(e,t);if(t.command===`fill`)return Qt(e,t);if(t.command===`get`)return $t(e,t)}function Zt(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(m(_(n))),I(e,t),p(e,t),e.join(` `);if(t.positionals.length===1)return e.push(m(n)),p(e,t),e.join(` `)}}function Qt(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(m(_(n))),I(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(m(r)),p(e,t),e.join(` `)}function $t(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(m(n)),e.push(m(_(r))),r.startsWith(`@`)&&I(e,t),e.join(` `)}function I(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(m(n))}const L=65536;function R(e){return Ze(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function z(e,t){let n=tn(e);if(n===void 0)return!1;try{let e=V(t),r=Buffer.allocUnsafe(L),i=0;do if(i=S.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{S.closeSync(n)}}async function en(e){let t=await nn(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=V(e=>{n.lineCount===0&&(n.firstLineDigest=R(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(L);for(;;){let{bytesRead:n}=await t.read(r,0,r.length,null);if(e.push(r.subarray(0,n)),n===0)break}return e.end(),n}finally{await t.close()}}function B(e){let t;return z(e,e=>(t=R(e),!1)),t}function V(e){let t=new $e(`utf8`),n=``,r=!1;return{push(i){if(r)return!1;let a=`${n}${t.write(i)}`,o=0;for(let t=a.indexOf(`
`);t!==-1;t=a.indexOf(`
`,o)){if(H(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||H(`${n}${t.end()}`,e)}}}function H(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function tn(e){try{return S.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function nn(e){try{return await S.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const U=5242880,rn=Qe();function an(e){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return U;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:U}function W(e){return`${e}.1`}function G(e){return`${e}.window.json`}function K(e){let t;for(let n=0;n<3;n+=1){let n=Y(e);try{let t=on(e);for(let n of t.files)hn(e,n.path);if(Y(e)===n)return t}catch(r){if(t=r,Y(e)===n)throw r}}throw t??J(e,`the window did not settle while reading`)}function on(e){let t=W(e),n=fn(e);if(n===`unverifiable`)throw J(e,`window file is invalid`);if(n===void 0)return sn(e,t);let r=n.at(-1);if(!r)throw J(e,`window file records no generation`);let i=gn(e),a=q(B(e),r),o=[],s=cn({eventLogPath:e,rotatedPath:t,sidecar:n,activeStart:a,activeExists:i});return s!==void 0&&o.push({path:t,firstLineIndex:s}),i&&o.push({path:e,firstLineIndex:a}),{files:o,earliestCursor:o[0]?.firstLineIndex??a}}function sn(e,t){if(B(t)!==void 0)throw J(e,`a rotated event log exists with no window record`);return{files:gn(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function q(e,t){return e!==void 0&&e===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function cn(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=B(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw J(t,`the rotated event log matches no window record`);let c=dn(n);if(c!==s.lineCount)throw J(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw J(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function ln(e,t,n){let r=_n(e);if(r&&hn(e,e),!r||r.size+n<=t)return!1;K(e);let i=fn(e);if(i===`unverifiable`)throw J(e,`window file is invalid`);let a=await en(e);if(a.firstLineDigest!==void 0){let t=i??[],n=t.at(-1),r=n?.firstLineDigest===a.firstLineDigest;if(r&&n.lineCount>a.lineCount)throw J(e,`active generation differs from its window record`);let o={firstLineIndex:n?q(a.firstLineDigest,n):0,lineCount:a.lineCount,firstLineDigest:a.firstLineDigest};await mn(e,[...r?t.slice(0,-1):t,o].slice(-2))}return await S.promises.rename(e,W(e)),!0}function un(e,t){if(!(e>=t))throw new c(`COMMAND_FAILED`,`events cursor ${e} precedes the retained event log window; events before cursor ${t} were rotated out.`,{reason:`EVENT_LOG_CURSOR_EXPIRED`,cursor:e,earliestCursor:t,hint:`Resume with cursor ${t}, the oldest retained event; earlier events are no longer available.`})}function J(e,t){return new c(`COMMAND_FAILED`,`Session event log window cannot be verified: ${t}.`,{reason:`EVENT_LOG_WINDOW_UNVERIFIED`,path:e,hint:`Cursor positions for this session cannot be resolved. Delete ${e}, ${W(e)}, and ${G(e)} to restart the timeline, or read the files directly.`})}function dn(e){let t=0;return z(e,()=>{t+=1}),t}function Y(e){return[X(G(e)),X(e),X(W(e))].join(`|`)}function X(e){try{let t=S.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function fn(e){let t;try{t=S.readFileSync(G(e),`utf8`)}catch(e){return e.code===`ENOENT`?void 0:`unverifiable`}try{let e=JSON.parse(t);if(!l(e)||e.version!==2)return`unverifiable`;let{generations:n}=e;if(!Array.isArray(n)||n.length===0)return`unverifiable`;let r=n.map(pn);return r.every(e=>e!==void 0)?r:`unverifiable`}catch{return`unverifiable`}}function pn(e){if(!l(e))return;let{firstLineIndex:t,lineCount:n,firstLineDigest:r}=e;if(!(!Number.isSafeInteger(t)||t<0)&&!(!Number.isSafeInteger(n)||n<0)&&typeof r==`string`&&r.length!==0)return{firstLineIndex:t,lineCount:n,firstLineDigest:r}}async function mn(e,t){let n=G(e),r=`${n}.${process.pid}.${rn}.tmp`,i=await S.promises.open(r,`wx`);try{try{await i.writeFile(JSON.stringify({version:2,generations:t}),`utf8`)}finally{await i.close()}await S.promises.rename(r,n)}catch(e){throw await S.promises.unlink(r).catch(()=>void 0),e}}function hn(e,t){try{let n=S.openSync(t,`r`);try{let{size:t}=S.fstatSync(n);if(t===0)return;let r=Buffer.alloc(1);if(S.readSync(n,r,0,1,t-1)!==1||r[0]!==10)throw J(e,`retained event log has an incomplete line`)}finally{S.closeSync(n)}}catch(t){throw t instanceof c?t:J(e,`retained event log completeness cannot be verified`)}}function gn(e){return _n(e)!==void 0}function _n(e){try{let t=S.lstatSync(e);if(t.isSymbolicLink())throw new c(`COMMAND_FAILED`,`Session event log must not be a symbolic link: ${e}`);return t}catch(e){if(e.code===`ENOENT`)return;throw e}}const Z=16777216,Q=new Map,vn=new Set;function yn(e){return C.join(e,`events.ndjson`)}function bn(e){return e.command!==Fe.events}function xn(e,t,n,r){let i=s({version:1,ts:n.ts??new Date().toISOString(),session:t,...n});Cn(e,`${JSON.stringify(i)}\n`,r)}async function Sn(e){await(e?Q.get(e)?.pending:Promise.all([...Q.values()].map(e=>e.pending)))}function $(e,t,n,r){u({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,reason:t,operation:n,errno:r instanceof c?void 0:r?.code,error:r===void 0?void 0:o(r)}})}function Cn(e,t,n){let r=an(n),i=Buffer.byteLength(t,`utf8`);if(i>Math.min(r,Z)){$(e,`entry-too-large`,`admission`);return}let a=Q.get(e);if(a&&(a.entries>=128||a.bytes+i>Z)){$(e,`queue-full`,`admission`);return}a||(a={pending:Promise.resolve(),entries:0,bytes:0},Q.set(e,a));let o=a;o.entries+=1,o.bytes+=i,o.pending=o.pending.then(async()=>{try{await wn(e)}catch(t){$(e,`maintenance-failed`,`mkdir`,t);return}try{await ln(e,r,i)}catch(t){$(e,`maintenance-failed`,`rotation`,t);return}try{await S.promises.appendFile(e,t,`utf8`)}catch(t){$(e,`append-failed`,`append`,t)}}).finally(()=>{--o.entries,o.bytes-=i,o.entries===0&&Q.delete(e)})}async function wn(e){let t=C.dirname(e);vn.has(t)||(await S.promises.mkdir(t,{recursive:!0}),vn.add(t))}function Tn(e,t,n,r){xn(e,t,{kind:`action.recorded`,requestId:d().requestId,command:n.command,summary:Je(n),details:Ye(n)},r)}function En(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??d().requestId,command:t.command,summary:`Started ${t.command}`}}function Dn(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=qe(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??d().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??d().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function On(e,t={}){let n=An(t.cursor),r=jn(t.limit),i=K(e);un(n,i.earliestCursor);let a=kn(i.files,n,r),o=a.lines.flatMap(e=>{let t=Mn(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)},endCursor:String(a.endCursor)}}function kn(e,t,n){let r=[],i,a=0;for(let o of e){let e=o.firstLineIndex;if(z(o.path,a=>{if(e>=t+n)return i=t+n,!1;e>=t&&r.push(a),e+=1}),a=e,i!==void 0)break}let o=Math.max(t,Math.min(t+n,a));return{lines:r,...i===void 0?{}:{nextCursor:i},endCursor:o}}function An(e){if(e===void 0||e.trim()===``)return 0;let t=Number(e);if(Number.isInteger(t)&&t>=0)return t;throw new c(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function jn(e){if(e===void 0||typeof e==`string`&&e.trim()===``)return 100;let t=typeof e==`string`?Number(e):e;if(Number.isInteger(t)&&t>=1&&t<=500)return t;throw new c(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function Mn(e){try{let t=Nn(JSON.parse(e));return t?Pn(t):void 0}catch{return}}function Nn(e){if(l(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&Fn(e.kind))return e}function Pn(e){let t=l(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...In(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function Fn(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function In(e){return e===`ok`||e===`error`}const Ln=36e5;var Rn=class{sessions=new Map;retainedExecutionHosts=new Map;acceptingSessions=!0;runtimeHints=new Map;sessionsDir;scriptWriter;host;constructor(e,t){this.sessionsDir=e,this.host=t,this.scriptWriter=new Mt(e,t.cwd)}get(e){return this.sessions.get(e)?.current}closeAdmission(){this.acceptingSessions=!1}assertAdmissionOpen(e){if(!this.acceptingSessions)throw new c(`COMMAND_FAILED`,`Daemon is shutting down`,{reason:ze,session:e})}assertPublishable(e){if(this.assertAdmissionOpen(e),this.sessions.has(e))throw new c(`COMMAND_FAILED`,`Session address is already occupied`,{reason:`session_address_occupied`,session:e})}publish(e,t){this.assertPublishable(e);let n={current:t};this.sessions.set(e,n);for(let e of this.retainedExecutionHosts.values())f(e.device.id,t.device.id)&&this.releaseRetainedExecutionHost(e);return this.clearIdleExpiryTombstone(e),this.captureRef(e,n)}resolveCurrent(e){let t=this.sessions.get(e.address);return t===e.lifetime?t.current:void 0}refresh(e){let t=this.sessions.get(e.address);return t===e.lifetime?this.captureRef(e.address,t):e}requireCurrent(e){let t=this.resolveCurrent(e);if(!t)throw new c(`COMMAND_FAILED`,`Session lifetime has ended`,{reason:`session_lifetime_ended`,session:e.address,hint:`Open a new session before retrying the command.`});return t}update(e,t){let n=this.requireCurrent(e),r=this.sessions.get(e.address),i=typeof t==`function`?t(n):t,a={...n,...i};return r.current=a,a}retire(e,t={}){let n=this.resolveCurrent(e);return n?(t.retainExecutionHost&&n.lease&&this.retainedExecutionHosts.set(n.device.id,{address:e.address,device:n.device,lease:{...n.lease}}),this.runtimeHints.delete(e.address),this.sessions.delete(e.address)):!1}listRetainedExecutionHosts(e){return Array.from(this.retainedExecutionHosts.values()).filter(t=>t.lease.leaseId===e)}ownsRetainedExecutionHost(e){return this.retainedExecutionHosts.get(e.device.id)===e}releaseRetainedExecutionHost(e){return this.ownsRetainedExecutionHost(e)?this.retainedExecutionHosts.delete(e.device.id):!1}captureRef(e,t){return Object.freeze({address:e,session:t.current,lifetime:t})}*values(){for(let e of this.sessions.values())yield e.current}toArray(){return Array.from(this.values())}lookup(e){let t=this.sessions.get(e);return t?this.captureRef(e,t):void 0}findByDevice(e){for(let[t,n]of this.sessions)if(f(n.current.device.id,e))return this.captureRef(t,n)}listRefs(){return Array.from(this.sessions,([e,t])=>this.captureRef(e,t))}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){t?this.runtimeHints.set(e,t):this.runtimeHints.delete(e)}clearRuntimeHints(e){return this.requireCurrent(e),this.runtimeHints.delete(e.address)}recordAction(e,t){let n=ct(this.requireCurrent(e),t,this.host.cwd);n&&Tn(this.resolveEventLogPath(e.address),e.address,n,this.host.env)}recordEvent(e,t){xn(this.resolveEventLogPath(e),e,t,this.host.env)}readEvents(e,t={}){return On(this.resolveEventLogPath(e),t)}async flushEvents(e){await Sn(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.requireCurrent(e),r=this.scriptWriter.write(n,t);return r.written&&u({level:`info`,phase:`session_script_written`,data:{session:n.name,path:r.path}}),r}writeRemoteScriptVersion(e){return this.scriptWriter.write(this.requireCurrent(e))}finalizeRepairTeardown(e){let t=this.resolveCurrent(e);if(!t||Te(t))return;this.recordRepairFinalizeCloseIfCommitting(e);let n=this.writeSessionLog(e,{force:De(t,void 0)});E(t)&&(!n.written&&n.error?this.writeRepairTombstone(e,Ln,{code:String(n.error.code),message:n.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=this.requireCurrent(e),n=t.scriptPublication??b;v(n)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:t.name,...ne(`Closed: ${t.name}`)}})}writeRepairTombstone(e,t=Ln,n){let r=this.resolveCurrent(e);if(r)try{let i=this.resolveSessionDir(e.address);S.mkdirSync(i,{recursive:!0});let a={owner:e.address,reapedAt:Date.now(),expiresAt:Date.now()+t,...O(r)?{sourcePath:O(r)}:{},...n?{commitFailure:n}:{}};S.writeFileSync(this.repairTombstonePath(e.address),`${JSON.stringify(a)}\n`)}catch(t){u({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.address,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return Ge(this.repairTombstonePath(e),e)}clearRepairTombstone(e){Ke(this.repairTombstonePath(e),e)}noteSessionActivity(e,t=Date.now()){let n=this.get(e);n&&(n.lastActivityAtMs=t)}markCloseEffectsUnconfirmed(e){this.update(e,{closeEffectsUnconfirmed:!0})}clearCloseEffectsUnconfirmed(e){delete this.requireCurrent(e).closeEffectsUnconfirmed}writeIdleExpiryTombstone(e,t){try{S.mkdirSync(this.resolveSessionDir(e),{recursive:!0}),S.writeFileSync(j(this.resolveSessionDir(e)),`${JSON.stringify(t)}\n`)}catch(t){u({level:`warn`,phase:`idle_expiry_tombstone_write_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}readIdleExpiryTombstone(e){if(!Be(e))return;let t=St(j(this.resolveSessionDir(e)));return t?.owner===e?t:void 0}clearIdleExpiryTombstone(e){try{S.rmSync(j(this.resolveSessionDir(e)),{force:!0})}catch(t){u({level:`warn`,phase:`idle_expiry_tombstone_clear_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}repairTombstonePath(e){return We(this.resolveSessionDir(e))}defaultTracePath(e){let t=x(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return C.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){return Ve(this.sessionsDir,e)}resolveDaemonStateDir(){return C.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return S.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return Ue(this.sessionsDir,e)}resolveAppLogPidPath(e){return He(this.sessionsDir,e)}resolveEventLogPath(e){return yn(this.resolveSessionDir(e))}};export{vt as a,nt as c,E as d,it as f,rt as h,bn as i,st as l,D as m,Dn as n,dt as o,at as p,En as r,ot as s,Rn as t,T as u};