UNPKG

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.

11 lines (7 loc) • 9.45 kB
import{_ as e,at as t}from"./sdk-batch.js";import{u as n,v as r}from"./sdk-contracts.js";import{g as i}from"./sdk-batch-runner.js";import{i as a}from"./catalog.js";import{n as o,t as s}from"./command-tools.js";import{a as c}from"./version.js";import{i as l,r as u,t as d}from"./cli-help.js";const f=`agent-device drives iOS, Android, tvOS, Android TV, macOS, Linux, and web apps. Tools mirror CLI commands of the same name; CLI flags are camelCase properties (--settle -> settle: true). If your client defers tool schemas, load a tool's schema before its first call. Start: known app -> call open {app, foreground: true} at once; do not probe with devices, apps, appstate, snapshot, or screenshot first. open returns the initial interactive snapshot with @refs. Unknown app id: devices, then apps, then open the discovered id; never invent ids. Existing session: continue from its state, do not reopen. Loop: ${p().join(`/`)} with settle: true; the response is the settled UI diff, continue from it. A known multi-step walk is one batch call: steps [{command, input}]. To reach an off-screen target, scroll {direction, until: "<selector>"} scrolls until it is on screen in one call, and direction "bottom" runs to the end of the content; repeated bare scrolls are the slow way to find something. snapshot {interactiveOnly: true} only when the diff lacks the next target or did not settle. Verify with wait {kind: "text", text}, wait {selector}, wait {absent: selector}, is, or get; a bare screenshot is not verification. find acts and clicks by default; to check only, pass action: "exists". End with close. Targets are top-level arguments: press {ref: "@e12"}, click {selector: "id=submit"}, press {x, y}. Copy refs byte-for-byte (@e12, @e12~s4; keep @ and any ~sN). Refs go stale after mutations. Prefer refs, then id/label/role selectors; coordinates last. On a sparse/AX-unavailable warning its refs and selectors are invalid: screenshot, read the image, press {x, y}, then snapshot the changed screen. Errors carry hints; follow them instead of re-planning. Call help only for specialized work (gestures, scripting, TV, macOS, web, remote, debugging) or an unclear command shape, never at startup.`;function p(){return e().filter(e=>t(e)!==void 0)}function m(){let t=new Set(e());return a().filter(e=>!t.has(e))}const h={name:`help`,title:`Read usage guides`,annotations:{readOnlyHint:!0,destructiveHint:!1},description:`Return usage guides and command references. With no topic, returns the root decision card. The topic can be ${u().join(`, `)}, or a tool name for its complete flag reference.`,inputSchema:{type:`object`,properties:{topic:{type:`string`,description:`Guide topic or tool name; omit for the card.`}},additionalProperties:!1}},g=`CLI syntax over MCP: the guide below is written for the terminal. Call the tool named after the command and pass every argument as a named property, for example press {ref: "@e12", settle: true} or snapshot {interactiveOnly: true}. Positionals become properties such as ref, label, selector, x, y, text, and direction; options become camelCase properties. Terminal-only (no MCP tool; run in a shell): ${m().join(`, `)}.\n\n`;function _(e){let t=e.topic;if(t!==void 0&&typeof t!=`string`)return v(`Expected topic to be a string.`,!0);let n=t?l(t):d();return n===null?v(`Unknown help topic: ${t}. ${h.description}`,!0):v(g+n)}function v(e,t=!1){return{isError:t,content:[{type:`text`,text:e}]}}const y=`2026-07-28`,b=[y],x=[`2025-11-25`,`2025-06-18`],S=[...b,...x],C=`server/discover`,w=new Set([`initialize`,`ping`]),T=`io.modelcontextprotocol/protocolVersion`,E=`io.modelcontextprotocol/clientCapabilities`,D=`io.modelcontextprotocol/clientInfo`,O=36e5;var k=class extends Error{requested;constructor(e){super(`Unsupported MCP protocol version: ${e}. Supported: ${S.join(`, `)}.`),this.requested=e}get data(){return{supported:S,requested:this.requested}}};function A(e,t){let n=L(L(t)._meta),a=R(n,T);if(a===void 0){if(e===C)throw new r(`INVALID_ARGS`,`Expected _meta["${T}"] on ${C}.`);return`legacy`}if(!S.includes(a))throw new k(a);if(!i(n[E]))throw new r(`INVALID_ARGS`,`Expected _meta["${E}"] to be an object.`);let o=n[D];if(o!==void 0&&!ne(o))throw new r(`INVALID_ARGS`,`Expected _meta["${D}"] to be a valid Implementation.`);if(!b.includes(a)){if(e===C)throw new k(a);return`legacy`}return`modern`}function j(e){let t=R(L(e),`protocolVersion`);return t!==void 0&&x.includes(t)?t:`2025-11-25`}function M(e,t){return t===`modern`&&w.has(e)}function N(){return{name:`agent-device`,version:c()}}function ee(e,t){return t===`legacy`||typeof e!=`object`||!e?e:{resultType:`complete`,...e,_meta:{...e._meta,"io.modelcontextprotocol/serverInfo":N()}}}function te(e,t){return e===`modern`?{ttlMs:t,cacheScope:`public`}:void 0}function ne(e){return!i(e)||!F(e.name)||!F(e.version)?!1:P(e.title,F)&&P(e.description,F)&&P(e.websiteUrl,F)&&P(e.icons,e=>Array.isArray(e)&&e.every(re))}function re(e){return!i(e)||!F(e.src)?!1:P(e.mimeType,F)&&P(e.sizes,I)&&P(e.theme,e=>e===`light`||e===`dark`)}function P(e,t){return e===void 0||t(e)}function F(e){return typeof e==`string`}function I(e){return Array.isArray(e)&&e.every(F)}function L(e){return i(e)?e:{}}function R(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function z(e){let t={structured:e.structured,executor:s(e.structured?{structuredContent:`declared`}:{})};return async(e,n={})=>await B(t,e,n)}async function B(e,t,n){if(t.jsonrpc!==`2.0`||typeof t.method!=`string`)return W(t.id??null,-32600,`Invalid JSON-RPC request.`);if(t.id===void 0)return null;try{let r=A(t.method,t.params),i=await V(e,t.method,t.params,r,n.signal);return U(t.id,ee(i,r))}catch(e){return e instanceof k?W(t.id,-32022,e.message,e.data):e instanceof J?W(t.id,-32601,e.message):W(t.id,-32602,e instanceof Error?e.message:String(e))}}async function V(e,t,n,r,i){if(M(t,r))throw new J(`${t} was removed in MCP ${y}.`);switch(t){case`server/discover`:return{supportedVersions:S,capabilities:{tools:{}},instructions:f,ttlMs:O,cacheScope:`public`};case`initialize`:return{protocolVersion:j(n),capabilities:{tools:{}},serverInfo:N(),instructions:f};case`ping`:return{};case`tools/list`:return{tools:[...o({outputSchemas:e.structured}),h],...te(r,O)};case`tools/call`:return await H(e.executor,n,i);default:throw new J(`Unsupported MCP method: ${t}`)}}async function H(e,t,n){let r=G(t),i=q(r,`name`);try{return i===`help`?_(K(r.arguments)):await e.execute(i,K(r.arguments),{signal:n})}catch(t){return await e.errorResult(t)}}function U(e,t){return{jsonrpc:`2.0`,id:e,result:t}}function W(e,t,n,r){return{jsonrpc:`2.0`,id:e,error:{code:t,message:n,...r?{data:r}:{}}}}function G(e){if(!e||typeof e!=`object`||Array.isArray(e))throw new r(`INVALID_ARGS`,`Expected object parameters.`);return e}function K(e){return e===void 0?{}:G(e)}function q(e,t){let n=e[t];if(typeof n!=`string`||n.length===0)throw new r(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return n}var J=class extends Error{};async function Y(e){let t=ie({handlePayload:ae(e)});process.stdin.setEncoding(`utf8`),process.stdin.on(`data`,e=>{t.receive(e)}),await new Promise(e=>{process.stdin.on(`end`,e),process.stdin.on(`close`,e),process.stdin.resume()}),await t.end()}function ie(e){let t=e.handlePayload,n=e.write??de,r=new Set,i=new Map,a=Promise.resolve(),o=``,s=e=>{r.add(e),e.finally(()=>r.delete(e))},c=async(e,r)=>{try{let i=await t(e,{signal:r});i&&!r?.aborted&&n(i)}catch(t){if(r?.aborted)return;n({jsonrpc:`2.0`,id:Z(e),error:{code:-32603,message:t instanceof Error?t.message:String(t)}})}},l=(e,t)=>{let n=new AbortController;t!==void 0&&i.set(t,n),a=a.then(async()=>{n.signal.aborted||await c(e,n.signal),t!==void 0&&i.get(t)===n&&i.delete(t)}),s(a)},u=e=>{let t=Q(e);if(t?.method===`notifications/cancelled`&&t.id===void 0){let e=le(t.params);e!==void 0&&i.get(e)?.abort();return}if(t?.method===`tools/call`){l(e,t?.id);return}s(c(e))},d=e=>{let t=e.trim();if(t.length===0)return;let r;try{r=JSON.parse(t)}catch(e){n({jsonrpc:`2.0`,id:null,error:{code:-32700,message:e instanceof Error?e.message:String(e)}});return}u(r)};return{receive:e=>{o+=e;for(let e=o.indexOf(` `);e!==-1;e=o.indexOf(` `)){let t=o.slice(0,e);o=o.slice(e+1),d(t)}},end:async()=>{let e=o;for(o=``,d(e);r.size>0;)await Promise.all(r)}}}function ae(e){let t=z(e);return async(e,n={})=>Array.isArray(e)?await oe(t,e):await X(t,e,n)}async function oe(e,t){let n=[];for(let r of t){let t=Q(r),i=t?.jsonrpc===`2.0`&&t.method===`tools/call`?se(t.id):await X(e,r);n.push(...ue(i))}return n.length>0?n:null}function se(e){return e===void 0?null:{jsonrpc:`2.0`,id:e,error:{code:-32600,message:`tools/call is not accepted in a JSON-RPC batch. Send it as its own message.`}}}async function X(e,t,r={}){let i;try{i=n.parse(t)}catch{return ce($(t))}return e(i,r)}function ce(e){return{jsonrpc:`2.0`,id:e,error:{code:-32600,message:`Invalid JSON-RPC request.`}}}function Z(e){return Array.isArray(e)?e.length===1?$(e[0]):null:$(e)}function Q(e){if(!Array.isArray(e))try{return n.parse(e)}catch{return}}function le(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.requestId;return typeof t==`string`||typeof t==`number`?t:void 0}function $(e){if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e.id;if(typeof t==`string`||typeof t==`number`||t===null)return t}return null}function ue(e){return e?[e]:[]}function de(e){process.stdout.write(`${JSON.stringify(e)}\n`)}export{Y as runAgentDeviceMcpServer};