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.
2 lines • 11.6 kB
JavaScript
import{C as e,F as t,j as n,v as r}from"./sdk-contracts.js";import{gt as i}from"./sdk-io.js";import"./file.js";import{i as a}from"./png-worker-client.js";import{r as o}from"./png.js";import{t as s}from"./png-encode.js";import{n as c}from"./png-resize.js";import{c as l,r as u,s as ee}from"./video.js";import{a as d,i as f,n as p,o as m,r as h,s as g,t as _}from"./runtime-factory.js";import{t as v}from"./png-size.js";import{r as y}from"./artifact-paths.js";import{i as b,n as x,r as te}from"./screenshot-overlay-draw.js";import{t as ne}from"./mp4-duration.js";import S from"node:fs";import re from"node:os";import C from"node:path";const w=`contact_sheet_frame_extraction_failed`,T=`contact_sheet_no_frames`;function E(e=process.platform){if(e!==`darwin`)throw new r(`UNSUPPORTED_OPERATION`,`Contact sheets can only be built on macOS hosts, which is where the frame decoder runs`,{reason:`contact_sheet_unsupported_host`,hostPlatform:e,hint:`Run this command on the macOS host that recorded the clip, or read the video artifact itself.`})}async function D(e){if(E(e.hostPlatform??process.platform),e.timesMs.length===0)throw new r(`COMMAND_FAILED`,`Contact sheet sampling requested no frames`,{reason:T,videoPath:e.videoPath});L(e.signal);let t=await I(e);L(e.signal);let n;try{n=await l(e.host,t,[`--input`,e.videoPath,`--output-dir`,e.scratchDir,`--times`,e.timesMs.join(`,`),`--max-width`,String(e.maxWidth)],{timeoutMs:9e4,allowFailure:!0,...e.signal===void 0?{}:{signal:e.signal}})}catch(t){j(t,e.videoPath,`Failed to run the frame decoder`)}if(n.exitCode!==0)throw new r(`COMMAND_FAILED`,`Failed to extract frames from the recording: ${F(n.stderr)||`exit ${n.exitCode}`}`,{reason:w,videoPath:e.videoPath,exitCode:n.exitCode});let i=O(n.stdout,e.videoPath,e.scratchDir,e.timesMs.length);if(i.frames.length===0)throw new r(`COMMAND_FAILED`,`The recording returned no decodable frames for a contact sheet`,{reason:T,videoPath:e.videoPath,skippedSampleCount:i.skippedSampleCount});return i}function O(e,t,n,r){let i;try{i=JSON.parse(e)}catch(e){throw A(t,`invalid manifest: ${String(e)}`)}let a=M(i).frames;if(!Array.isArray(a))throw A(t,`manifest has no frames array`);let o=M(i).skipped;if(a.length>r)throw A(t,`returned ${a.length} frames for ${r} requested samples`);let s=a.flatMap(e=>{let r=M(e),i=N(r.path),a=P(r.actualTimeMs);if(i===void 0||a===void 0||a<0)throw A(t,`frame entry is missing a path or presentation time`);let o=C.resolve(n,C.basename(i));return S.existsSync(o)?[{requestedTimeMs:P(r.requestedTimeMs)??a,actualTimeMs:a,path:o}]:[]});return{frames:s.sort((e,t)=>e.actualTimeMs-t.actualTimeMs),skippedSampleCount:Math.max(Array.isArray(o)?o.length:0,r-s.length)}}function k(e,t,n){return new r(`COMMAND_FAILED`,e,{reason:w,videoPath:t},n)}function A(e,t){return k(`Frame extraction returned an unreadable manifest: ${t}`,e)}function j(e,i,a){throw t(e)||e instanceof r&&e.code===`COMMAND_FAILED`&&e.details?.reason?e:k(`${a} for ${i}: ${n(e)}`,i,e)}function M(e){return typeof e==`object`&&e?e:{}}function N(e){return typeof e==`string`&&e!==``?e:void 0}function P(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function F(e){return(e.trim().split(`
`).pop()??``).trim()}async function I(e){try{let{RECORDING_FRAMES_SOURCES:t}=await import(`./recording-swift-sources.js`);return await ee({host:e.host,sources:t,cacheName:`recording-frames`,timeoutMs:12e4})}catch(t){j(t,e.videoPath,`Could not build the frame decoder`)}}function L(t){if(t?.aborted)throw e()}function R(e,t){if(e===void 0||!Number.isFinite(e)||e<0)throw new r(`COMMAND_FAILED`,`Cannot plan a contact sheet: the video timeline of ${t} could not be read`,{reason:`contact_sheet_duration_unknown`,videoPath:t,hint:`Retry once the recording finished finalizing; a clip whose container is still being written has no readable duration.`});if(e<=250)return{durationMs:e,timesMs:e>0?[0,Math.round(e)]:[0]};let n=Math.min(48,Math.floor(e/250)+1),i=e/(n-1);return{durationMs:e,timesMs:Array.from({length:n},(e,t)=>Math.round(t*i))}}const z=[360,320,280,240,200,160],B=[255,255,255,255],V=[17,24,39,255],H=te(2)+8;function U(e){let{cells:t}=e;if(t.length===0)throw new r(`COMMAND_FAILED`,`Contact sheet has no cells to render`);let n=G(t[0].image.height/Math.max(1,t[0].image.width),t.length,e),i=J(n.width,n.height,V);return t.forEach((e,t)=>{let r=t%n.columns,a=Math.floor(t/n.columns);W(i,8+r*(n.cellWidth+8),8+a*(H+n.cellHeight+8),e,n.cellWidth,n.cellHeight)}),{bytes:s(i.data,n.width,n.height,4),width:n.width,height:n.height,cellWidth:n.cellWidth}}function W(e,t,n,r,i,a){x(e,{x:t+4,y:n+4,text:ie(r.timeMs),color:B,scale:2}),Y(e,c(X(r.image),i,a),t,n+H)}function G(e,t,n){let i=K(e,t,n.maxPixels);if(i)return i;let a=q(e,t,160);throw new r(`COMMAND_FAILED`,`Contact sheet would be ${a.width*a.height} pixels, above the configured maxImagePixels limit of ${n.maxPixels}`,{reason:`contact_sheet_pixel_budget_exceeded`,cellCount:n.cells.length,maxPixels:n.maxPixels,hint:`Shorten the recording or raise the command policy maxImagePixels limit.`})}function K(e,t,n){for(let r of z){let i=q(e,t,r);if(i.width*i.height<=n)return i}}function q(e,t,n){let r=Math.min(4,t),i=Math.ceil(t/r),a=Math.max(1,Math.round(n*e));return{columns:r,cellWidth:n,cellHeight:a,width:16+r*n+(r-1)*8,height:16+i*(H+a)+(i-1)*8}}function J(e,t,n){let r=new o.PNG({width:e,height:t});for(let i=0;i<t;i+=1)for(let t=0;t<e;t+=1)b(r,t,i,n);return r}function Y(e,t,n,r){for(let i=0;i<t.height;i+=1)for(let a=0;a<t.width;a+=1){let o=(i*t.width+a)*4;b(e,n+a,r+i,[t.data[o],t.data[o+1],t.data[o+2],t.data[o+3]])}}function X(e){let t=new o.PNG({width:e.width,height:e.height});return Buffer.from(e.data.buffer,e.data.byteOffset,e.data.byteLength).copy(t.data),t}function ie(e){let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60,a=Math.floor(e%1e3);return`${[n,r,i].map(e=>String(e).padStart(2,`0`)).join(`:`)}.${String(a).padStart(3,`0`)}`}function ae(e,t){if(e.width!==t.width||e.height!==t.height)return{status:`dimension_mismatch`};let n=e.width*e.height;if(n===0)return{status:`compared`,changedPixelRatio:0};if(e.data.length!==t.data.length)return{status:`dimension_mismatch`};let r=0;for(let n=0;n+3<e.data.length;n+=4)(e.data[n]!==t.data[n]||e.data[n+1]!==t.data[n+1]||e.data[n+2]!==t.data[n+2])&&(r+=1);return{status:`compared`,changedPixelRatio:r/n}}function oe(e,t=.02,n=24){let r=[],i;for(let n of e){let e=i?Z(i,n.image):1;e<t||(r.push({timeMs:n.timeMs,changedPixelRatio:e,image:n.image}),i=n.image)}se(r,e);let a=r.length>n?ce(r,n):r;return{cells:a,keptCellCount:r.length,thinned:a.length<r.length}}function se(e,t){let n=t.at(-1);if(!n)return;let r=e.at(-1);!r||r.timeMs===n.timeMs||e.push({timeMs:n.timeMs,changedPixelRatio:Z(r.image,n.image),image:n.image})}function Z(e,t){let n=ae(e,t);return n.status===`compared`?n.changedPixelRatio:1}function ce(e,t){if(t<=1)return[e.at(-1)];let n=(e.length-1)/(t-1);return Array.from({length:t},(t,r)=>e[Math.round(r*n)])}async function le(e){E(e.hostPlatform??process.platform);let t=C.resolve(e.videoPath),n=C.resolve(e.outputPath??y(t));fe(t,n);let i=await u(t);if(i!==`mp4`)throw new r(`INVALID_ARGS`,i===`webm`?`Contact sheets need an MP4 recording; ${t} is WebM, whose frames this decoder does not read`:`Contact sheets need an MP4 recording; ${t} is not a readable MP4`,{reason:`contact_sheet_container_unsupported`,videoPath:t,container:i??`unknown`,hint:`Re-record on a backend that exports MP4, or pass the MP4 artifact the recording produced.`});let a=R(ne(t),t),o=S.mkdtempSync(C.join(re.tmpdir(),`agent-device-contact-sheet-`));try{let r=await D({host:e.host,videoPath:t,scratchDir:o,timesMs:a.timesMs,maxWidth:360,hostPlatform:e.hostPlatform??process.platform,...e.signal===void 0?{}:{signal:e.signal}}),i=await ue(r.frames,e.maxPixels);de(e.signal);let s=oe(i,e.changedPixelThreshold??.02),c=U({cells:s.cells,maxPixels:e.maxPixels});return he(n,c.bytes),{path:n,videoPath:t,durationMs:a.durationMs,width:c.width,height:c.height,sampledFrameCount:a.timesMs.length,decodedFrameCount:r.frames.length,skippedSampleCount:r.skippedSampleCount,changedPixelThreshold:e.changedPixelThreshold??.02,cells:s.cells.map($),...me(s,r)}}finally{S.rmSync(o,{recursive:!0,force:!0})}}async function ue(e,t){let n=[];for(let i of e){let e=await v(i.path);if(e.width>360)throw new r(`COMMAND_FAILED`,`Frame extraction returned a ${e.width}px-wide frame when the sheet asked for 360px cells`,{reason:w,framePath:i.path,frameWidth:e.width,frameWidthLimit:360});if(e.width*e.height>t)throw new r(`COMMAND_FAILED`,`Frame extraction returned a ${e.width}x${e.height} frame, above the ${t}-pixel budget for the whole sheet`,{reason:w,framePath:i.path,framePixels:e.width*e.height,maxPixels:t});let o=await a(S.readFileSync(i.path),`recording frame`);n.push({timeMs:i.actualTimeMs,image:o})}return n}function de(t){if(t?.aborted)throw e()}function fe(e,t){if(pe(e,t)??t===e)throw new r(`INVALID_ARGS`,`A contact sheet cannot be written over the recording it describes: ${t}`,{reason:`contact_sheet_output_collides_with_input`,videoPath:e,outputPath:t,hint:`Choose a different --out path, or omit it to write beside the recording.`})}function pe(e,t){let n=Q(e),r=Q(t);if(n!==void 0&&r!==void 0)return n.dev===r.dev&&n.ino===r.ino}function Q(e){try{return S.statSync(e)}catch{return}}function $(e){return{timeMs:e.timeMs,changedPixelRatio:e.changedPixelRatio}}function me(e,t){let n=[];return t.skippedSampleCount>0&&n.push(`${t.skippedSampleCount} sample times returned no frame, so the sheet covers less of the recording than it asked for`),e.thinned&&n.push(`${e.keptCellCount} changes were found and 24 cells are printed, so the sheet thins evenly across the recording instead of showing every change`),n.length===0?{}:{warning:n.join(`; `)}}function he(e,t){try{S.mkdirSync(C.dirname(e),{recursive:!0}),i({destination:e,contents:t})}catch(t){throw new r(`COMMAND_FAILED`,`Failed to write the contact sheet to ${e}: ${t instanceof Error?t.message:String(t)}`,{reason:`contact_sheet_output_write_failed`,outputPath:e})}}const ge=async(e,t)=>{if(!t.video)throw new r(`INVALID_ARGS`,`record contact-sheet requires a recording to read`);ve(t.changedPixelThreshold);let n=await f(e,t.video,{usage:`record contact-sheet`,field:`video`}),i;try{let r=_e(t,t.video,n.path);i=await h(e,r,{field:`path`,ext:`.png`,artifactType:`screen-recording-contact-sheet`});let a=await le({host:t.host,videoPath:n.path,outputPath:i.path,maxPixels:e.policy.maxImagePixels,...t.changedPixelThreshold===void 0?{}:{changedPixelThreshold:t.changedPixelThreshold},signal:t.signal??e.signal}),o=await i.publish();return{...a,path:ye(a.path,o),...o?{artifact:o}:{}}}catch(e){throw await i?.cleanup?.(),e}finally{await n.cleanup?.()}};function _e(e,t,n){if(e.out)return e.out;if(t.kind===`path`)return{kind:`path`,path:C.resolve(y(t.path||n))};throw new r(`INVALID_ARGS`,`record contact-sheet needs an output path when the recording is an uploaded artifact`,{hint:"Pass --out <sheet.png> (CLI) or `out` (Node) to name where the sheet is written."})}function ve(e){if(e!==void 0&&(!Number.isFinite(e)||e<0||e>1))throw new r(`INVALID_ARGS`,`record contact-sheet needs a changedPixelThreshold between 0 and 1, got ${e}`,{reason:`contact_sheet_threshold_invalid`,changedPixelThreshold:e,hint:`Omit it to use the calibrated default, or pass a share of the frame between 0 and 1.`})}function ye(e,t){return t?t.kind===`localPath`?t.path:t.clientPath??e:e}const be={contactSheet:ge};function xe(e){return{capture:p(e),selectors:m(e),interactions:d(e),recording:g(be,e)}}function Se(e){let t=_(e);return{...t,...xe(t)}}export{Se as createAgentDevice};