@enhance-eng/enhance-dev 0.1.7-dev.sha-cec1f7daaffa → 0.1.7-dev.sha-3345ac7ecaec
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/dist/cli-output-identity.lib-C3dhDJfG.mjs +25 -0
- package/dist/main.mjs +10 -10
- package/dist/mcp-main.mjs +1 -1
- package/dist/mcp-server.adapter-BVeDABQv.mjs +4 -0
- package/dist/mcp.mjs +1 -1
- package/dist/mutation-key.adapter-HiEQIg6a.mjs +2 -0
- package/package.json +1 -1
- package/dist/cli-output-identity.lib-tfeJug7k.mjs +0 -25
- package/dist/mcp-server.adapter-TAb0Mc2v.mjs +0 -4
- package/dist/mutation-key.adapter-BjZGu9NT.mjs +0 -2
package/dist/main.mjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{A as e,C as t,D as n,E as r,G as i,J as a,K as o,O as s,S as c,T as l,U as u,W as d,X as f,Y as p,Z as ee,c as m,d as te,et as ne,i as
|
|
3
|
-
`),t=``,n=r?[n.at(-1)??0]:[],e};return{pending:()=>t.length,add:r=>{let o=[],s=Ge(r.event);for(n.push(r.atMs),i=!0;t.length+s.length>=e;){let n=e-t.length;t+=s.slice(0,n),s=s.slice(n),o.push(a())}return t+=s,o},drain:()=>!i||t.length>0?[a()]:[]}},qe=(e,t)=>{let n=Ke(t);return[...e.flatMap(e=>n.add(e)),...n.drain()]},O=[`recording.start`,`recording.appendChunk`,`recording.complete`],Je=t=>async n=>{let r=e.parse(await t.mutate(O[0],{sourceUrl:n.sourceUrl,viewport:n.viewport,pageTitle:n.pageTitle,audio:null})),i=r.upload;try{let e=qe(n.entries,8388608);for(let[n,a]of e.entries()){let e=new TextEncoder().encode(a.body),o=await t.upload({url:i.url,headers:i.headers,body:e});i=s.parse(await t.mutate(O[1],{recordingId:r.recordingId,index:n,firstEventMs:a.firstEventMs,lastEventMs:a.lastEventMs,eventCount:a.eventCount,continues:a.continues,bytes:e.byteLength,etag:o})).upload}let a=Math.max(0,...n.entries.map(e=>e.atMs));return re.parse(await t.mutate(O[2],{recordingId:r.recordingId,durationMs:a,viewport:n.viewport,sourceUrl:n.sourceUrl,interrupted:!1,...n.canvasId!==void 0&&{canvasId:n.canvasId},audioChunkCount:0,hasRecoverableBytes:!1}))}catch{throw new c(`Recording ${r.recordingId} began, but not every chunk was committed.`,`Run 'enhance recording discard --recording-id ${r.recordingId}' to remove the incomplete attempt before retrying the fixture.`)}},Ye=[`screen.create`,`screen.complete`],Xe=e=>async t=>{let i=n.parse(await e.mutate(Ye[0],{clientToken:t.clientToken,provenance:t.provenance,route:t.route,pageTitle:t.pageTitle,viewport:t.viewport,bytes:t.body.byteLength}));try{let n=await e.upload({url:i.upload.url,headers:i.upload.headers,body:t.body}),a=r.parse(await e.mutate(Ye[1],{screenId:i.screenId,etag:n}));return{screenId:a.screenId,route:t.route,title:t.pageTitle,viewport:t.viewport,atMs:t.provenance?.atMs??null,sourceRecordingId:t.provenance?.sourceRecordingId??null,assetBundle:null,download:null,storedBytes:a.storedBytes}}catch{throw new c(`Screen ${i.screenId} was reserved, but its upload did not complete.`,`Retry 'enhance fixture screen' with the same --client-token ${t.clientToken}.`)}},k=[`organisation.create`,`canvas.create`,`screen.create`,`screen.complete`,`canvas.document.get`,`canvas.document.save`],Ze=(e,t)=>async n=>{let r=u.parse(await e.mutate(k[0],{name:n.organisationName})).organisation,i=le.parse(await e.mutate(k[1],{title:n.canvasTitle,organisationId:r.id,sourceUrl:null}));try{let a=[];for(let e of n.screens)a.push(await t(e));let o=f.parse(await e.query(k[4],{canvasId:i.id})),s=He();for(let[e,t]of a.entries())s=We(s,{id:`fixture-screen-${String(e+1)}`,label:`Fixture screen ${String(e+1)}`,screenId:t.screenId,viewport:n.screens[e]?.viewport??{width:1440,height:900},at:{x:48+e*48,y:48+e*48}});let l=ee.parse(await e.mutate(k[5],{canvasId:i.id,baseVersion:o.version,document:s,screenIds:a.map(e=>e.screenId)}));if(l.outcome===`conflict`)throw new c(`World canvas ${i.id} was created, but another writer changed its document.`,`Read 'enhance canvas document get --canvas-id ${i.id}' before adding the screens.`);return{organisationId:r.id,canvasId:i.id,screenIds:a.map(e=>e.screenId),documentVersion:l.version}}catch(e){throw e instanceof c?e:new c(`Organisation ${r.id} and canvas ${i.id} exist, but the world is incomplete.`,`Inspect 'enhance canvas get --canvas-id ${i.id}' before retrying any missing steps.`)}},Qe=async(e,n)=>{if(e!==void 0&&e!==``)return e.trim();if(S.stdin.isTTY)throw new t(`BAD_REQUEST`,`A token is required and interactive prompting is disabled.`,`Pass '--token <token>' or pipe one line to '${n}'.`);let r=ke({input:S.stdin,crlfDelay:1/0});for await(let e of r){r.close();let t=e.trim();if(t!==``)return t;break}throw new t(`BAD_REQUEST`,`A token is required.`,`Pass '--token <token>' or pipe one line to '${n}'.`)},$e=async e=>{if(e!==void 0)return e.trim();if(S.stdin.isTTY)return null;let t=ke({input:S.stdin,crlfDelay:1/0});for await(let e of t){t.close();let n=e.trim();return n===``?null:n}return null},et=(e,t,n)=>{let r=e.command(`auth`).description(`Store and inspect the agent credential.`);r.command(`login`).description(`Authenticate in a browser, then store a revocable agent credential.`).option(`--token <token>`,`Use an existing agent token instead of browser authentication.`).option(`--no-open`,`Print the authorization URL without opening the browser.`).action(async e=>{let r=await $e(e.token);if(r!==null){n.result(await t.loginWithToken(r));return}n.result(await t.loginWithBrowser({label:`CLI on ${De()}`.slice(0,120),openBrowser:e.open,onReady:e=>{n.result({status:`waiting_for_browser`,url:e})}}))}),r.command(`status`).description(`Resolve the stored token to its person, label, and expiry.`).action(async()=>{n.result(await t.status())}),r.command(`logout`).description(`Delete the local credential file; this does not revoke the server token.`).action(async()=>{n.result(await t.logout())})},tt=x.array(a).min(1).max(o),nt=e=>{if(!e.startsWith(`@`))return e;let n=e.slice(1);if(n===``)throw new t(`BAD_REQUEST`,`--operations @ must name a JSON file.`,`Pass --operations @/absolute/path/layout.json or an inline JSON array.`);let r=T.resolve(n);try{let e=C(r);if(!e.isFile()||e.size>1048576)throw Error(`invalid size`);return Pe(r,`utf8`)}catch{throw new t(`BAD_REQUEST`,`Could not read a bounded operations file at ${r}.`,`Use a regular JSON file no larger than 1 MiB.`)}},rt=e=>{try{return JSON.parse(nt(e))}catch(e){throw e instanceof t?e:new t(`BAD_REQUEST`,`--operations must be one valid JSON array.`,`Pass inline JSON or @/absolute/path/layout.json; run 'enhance canvas apply --help' for examples.`)}},it=e=>{let n=rt(e),r=tt.safeParse(n);if(!r.success){let e=r.error.issues[0];throw new t(`BAD_REQUEST`,`The canvas operation batch is invalid${e===void 0||e.path.length===0?``:` at ${e.path.join(`.`)}`}.`,`Correct the named operation; run 'enhance canvas apply --help' for the supported vocabulary.`)}return r.data},A=x.uuid(),at=/^\/c\/([^/]+)\/?$/u,ot=e=>{try{let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`)return null;let n=at.exec(t.pathname.toLowerCase()),r=A.safeParse(n?.[1]);return r.success?r.data:null}catch{return null}},j=e=>{let n=e.trim(),r=A.safeParse(n);if(r.success)return r.data;let i=ot(n);if(i!==null)return i;throw new t(`BAD_REQUEST`,`The canvas reference is neither a canvas URL nor a UUID.`,`Paste an HTTP(S) URL shaped https://app.example/c/<UUID>, or pass the bare canvas UUID.`)},M=(e,t)=>{let n=e.find(e=>e.id===t);if(n===void 0)throw TypeError(`${t} is missing from the capability catalogue`);return n},st=x.coerce.number().int().positive(),ct=e=>{let n=st.safeParse(e);if(n.success)return n.data;throw new t(`BAD_REQUEST`,`--base-version is invalid.`,`Run 'enhance canvas apply --help'.`)},lt=(e,n)=>{let r=x.uuid().nullable().safeParse(n??null);if(!r.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact operation batch.`);return e.mutationKey.select(r.data,!1),e.mutationKey.current(`canvas.applyOperations`,{})},ut=(e,t)=>{e.command(`apply`).description(`Apply an atomic canvas edit batch and return its affected bounds.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact version returned by canvas inspect or tree.`).requiredOption(`--operations <json-or-@path>`,`JSON operation array inline, or @path to a JSON file.`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this exact batch.`).addHelpText(`after`,[``,`Supported operations: insertNode, insertText, insertPrototype, setText, setBox, setLabel, setVisibility, setLocked, setConstraints, setStyles, setAppearance, setLayout, setTypography, setAdditionalStyles, setProps, setParentage, move, remove.`,`Example:`,` enhance canvas apply --canvas <url-or-id> --base-version 3 --operations '[{"op":"insertText","nodeId":"txt_summary","parentId":"root","text":"Checkout needs an address.","box":{"x":120,"y":594,"width":720,"height":80},"styles":{"font-size":24}}]'`].join(`
|
|
4
|
-
`)).action(async e=>{lt(t,e.clientToken);let n=await t.invocation.invoke({capability:M(t.catalog(),`canvas.apply`),arguments:{canvasId:j(e.canvas),baseVersion:ct(e.baseVersion),operations:[...it(e.operations)]},clientToken:e.clientToken??null});t.output.result(n)})},N=1e3,dt=x.coerce.number().int().positive(),ft=x.coerce.number().min(.1).max(4),pt=x.uuid(),mt=x.union([x.string(),x.number(),x.null()]),ht=x.record(x.string(),mt),gt=x.array(x.object({nodeId:x.string().min(1).max(200),textContent:x.string().max(1e5)})).min(1).max(N),_t=x.array(x.object({nodeId:x.string().min(1).max(200),name:x.string().max(500)})).min(1).max(N),vt=x.array(x.object({nodeIds:x.array(x.string().min(1).max(200)).min(1).max(100),styles:ht})).min(1).max(100),yt=x.array(x.object({id:x.string().min(1).max(200),parentId:x.string().min(1).max(200).optional()})).min(1).max(100),bt=x.array(x.union([x.object({nodeId:x.string().min(1).max(200),before:x.string().min(1).max(200)}),x.object({nodeId:x.string().min(1).max(200),after:x.string().min(1).max(200)}),x.object({nodeId:x.string().min(1).max(200),parentId:x.string().min(1).max(200),index:x.number().int().nonnegative().optional()})])).min(1).max(100),xt=x.array(x.string().min(1).max(200)).min(1).max(N),St=x.coerce.number().int().min(0).max(20),Ct=e=>{try{return JSON.parse(e)}catch{return}},wt=e=>{if(e===void 0)return null;let n=de.safeParse(Ct(e));if(n.success)return n.data;throw new t(`BAD_REQUEST`,`--bounds must be a positive world rectangle.`,`Pass JSON with x, y, width and height.`)},Tt=e=>e===void 0?[]:e.split(`,`).map(e=>e.trim()).filter(e=>e!==``).slice(0,100),Et=(e,n)=>{e.command(`begin`).description(`Start visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--phase <phase>`,`reading, writing, creating, deleting, or rendering.`).option(`--node-ids <ids>`,`Comma-separated stable node ids.`).option(`--bounds <json>`,`Optional world rectangle for not-yet-created content.`).action(async e=>{let r=i.safeParse(e.phase);if(!r.success)throw new t(`BAD_REQUEST`,`--phase is invalid.`,`Use reading, writing, creating, deleting, or rendering.`);let a=j(e.canvas),o=d.parse(await n.remote.mutate(`canvas.realtime.activity.begin`,{canvasId:a,phase:r.data,nodeIds:Tt(e.nodeIds),bounds:wt(e.bounds)}));n.output.result({...o,next:[`enhance canvas work update --canvas ${a} --activity-id ${o.activityId} --phase ${r.data}`,`enhance canvas finish-working-on-nodes --canvas ${a} --activity-id ${o.activityId}`]})})},Dt=(e,t)=>{e.command(`update`).description(`Move visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by work begin.`).requiredOption(`--phase <phase>`,`Current agent phase.`).option(`--node-ids <ids>`,`Comma-separated current stable node ids.`).option(`--bounds <json>`,`Optional current world rectangle.`).action(async e=>{t.output.result(d.parse(await t.remote.mutate(`canvas.realtime.activity.renew`,{canvasId:j(e.canvas),activityId:pt.parse(e.activityId),phase:i.parse(e.phase),nodeIds:Tt(e.nodeIds),bounds:wt(e.bounds)})))})},Ot=(e,n)=>{e.command(`finish-working-on-nodes`).description(`End visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by canvas work begin.`).action(async e=>{if(!await Se(n.remote).finish(j(e.canvas),pt.parse(e.activityId)))throw new t(`NOT_FOUND`,`The activity could not be finished.`,`It may already have expired; run canvas work begin for new work.`);n.output.result({ended:!0,activityId:e.activityId})})},kt=(e,t)=>{let n=e.command(`work`).description(`Manage visible agent activity.`);Et(n,t),Dt(n,t),Ot(e,t)},At=/^(?:align|bottom|column-gap|display|flex|gap|height|justify|left|order|overflow|padding|position|right|row-gap|top|transform|width)/u,P=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e!=`string`)return null;let t=/^(-?\d+(?:\.\d+)?)(?:px)?$/u.exec(e.trim());return t===null?null:Number(t[1])},jt=(e,t)=>{let n=P(e);return n===null?[`100%`,`fill`].includes(String(e))?{mode:`fill`}:[`fit-content`,`auto`,`hug`].includes(String(e))?{mode:`hug`}:t:{mode:`fixed`,value:Math.max(0,n)}},Mt=(e,t,n)=>{let r=e[t],[i=n.top,a=i,o=i,s=a]=typeof r==`string`?r.split(/\s+/u).map(e=>P(e)??0):typeof r==`number`?[r]:[];return{top:Math.max(0,P(e[`${t}-top`])??i),right:Math.max(0,P(e[`${t}-right`])??a),bottom:Math.max(0,P(e[`${t}-bottom`])??o),left:Math.max(0,P(e[`${t}-left`])??s)}},Nt=(e,t)=>{switch(e){case`center`:case`start`:case`stretch`:return e;case`end`:case`flex-end`:return`end`;case`flex-start`:return`start`;default:return t}},Pt=(e,t)=>{switch(e){case`center`:case`space-around`:case`space-between`:case`space-evenly`:case`start`:return e;case`end`:case`flex-end`:return`end`;case`flex-start`:return`start`;default:return t}},Ft=()=>({direction:`column`,alignItems:`start`,alignContent:`start`,justifyContent:`start`,gap:0,rowGap:0,columnGap:0,wrap:`nowrap`,padding:{top:0,right:0,bottom:0,left:0}}),It=(e,t)=>{let n=t.display;if([`block`,`none`].includes(String(n)))return;let r=[`flex`,`inline-flex`].includes(String(n));if(e===void 0&&!r)return;let i={...e??Ft()},a=t[`flex-direction`];return i.direction=a===void 0?i.direction:String(a).startsWith(`row`)?`row`:`column`,i.alignItems=Nt(t[`align-items`],i.alignItems),i.justifyContent=Pt(t[`justify-content`],i.justifyContent),i.alignContent=Pt(t[`align-content`],i.alignContent===`stretch`?`start`:i.alignContent??`start`),i.gap=Math.max(0,P(t.gap)??i.gap),i.rowGap=Math.max(0,P(t[`row-gap`])??i.rowGap??i.gap),i.columnGap=Math.max(0,P(t[`column-gap`])??i.columnGap??i.gap),i.wrap=t[`flex-wrap`]===`wrap`?`wrap`:i.wrap??`nowrap`,i.padding=Mt(t,`padding`,i.padding),i},Lt=(e,t)=>{let n=P(t[`flex-grow`]),r=P(t[`flex-shrink`]),i=P(t.order);return{horizontal:jt(t.width,e.horizontal),vertical:jt(t.height,e.vertical),...t[`align-self`]!==void 0&&{alignSelf:Nt(t[`align-self`],`start`)},...n!==null&&{flexGrow:Math.max(0,n)},...r!==null&&{flexShrink:Math.max(0,r)},...t[`flex-basis`]!==void 0&&{flexBasis:P(t[`flex-basis`])??`auto`},...i!==null&&{order:Math.round(i)}}},Rt=(e,t)=>{if(Object.keys(t).every(e=>!At.test(e)))return null;let n=e.box??{x:0,y:0,width:1,height:1},r=e.layout??{...Be(),horizontal:{mode:`fixed`,value:n.width},vertical:{mode:`fixed`,value:n.height}},i=/rotate\(\s*(-?\d+(?:\.\d+)?)deg\s*\)/u.exec(String(t.transform??``))?.[1],a=`${String(t.overflow??``)} ${String(t[`overflow-x`]??``)} ${String(t[`overflow-y`]??``)}`,o=It(r.container,t),s=t.position;return{...r,...Lt(r,t),rotation:i===void 0?r.rotation:Number(i),position:s===`absolute`?`absolute`:[`relative`,`flow`].includes(String(s))?`flow`:r.position,clipContent:/\b(?:clip|hidden)\b/u.test(a)||r.clipContent,...o===void 0?{container:void 0}:{container:o}}},zt=(e,t)=>{if(e.box===void 0)return null;let n=P(t.left),r=P(t.top),i=P(t.width),a=P(t.height);return n===null&&r===null&&i===null&&a===null?null:{op:`setBox`,nodeId:e.id,box:{x:n??e.box.x,y:r??e.box.y,width:Math.max(1,i??e.box.width),height:Math.max(1,a??e.box.height)}}},Bt=/^(?:align|bottom|column-gap|display|flex|gap|height|justify|left|margin|order|overflow|padding|position|right|row-gap|top|transform|width)/u,Vt=e=>e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),Ht=e=>!/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu.test(e),Ut=(e,n)=>{let r=new Map((e.additionalStyles?.declarations??[]).map(e=>[e.property,e])),i=!1;for(let[e,a]of Object.entries(n)){if(p.safeParse({[e]:a}).success||Bt.test(e))continue;if(i=!0,a===null){r.delete(e);continue}let n=String(a);if(!Ht(n))throw new t(`BAD_REQUEST`,`Style ${e} contains executable CSS.`,`Remove imports, expressions, and executable URL schemes.`);r.set(e,{id:r.get(e)?.id??`css-${e}`.slice(0,200),property:e,value:n,enabled:!0})}let a=[];for(let e of r.values()){if(a.length>=128)break;a.push(e)}return i?{op:`setAdditionalStyles`,nodeId:e.id,additionalStyles:{declarations:a}}:null},Wt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[Vt(e),t])),Gt=(e,t)=>{let n=Wt(t),r=[],i=zt(e,n);i!==null&&r.push(i);let a=Object.fromEntries(Object.entries(n).filter(([e,t])=>p.safeParse({[e]:t}).success));Object.keys(a).length>0&&r.push({op:`setStyles`,nodeId:e.id,styles:p.parse(a)});let o=Rt(e,n);o!==null&&r.push({op:`setLayout`,nodeId:e.id,layout:o});let s=Ut(e,n);return s!==null&&r.push(s),n.display===`none`&&r.push({op:`setVisibility`,nodeId:e.id,visible:!1}),r},Kt=(e,n)=>{let r=e[n];if(r!==void 0)return r;throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use current stable node ids.`)},qt=(e,n)=>{let r=n.flatMap(t=>t.nodeIds.flatMap(n=>Gt(Kt(e,n),t.styles)));if(r.length===0)throw new t(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return r},Jt=x.uuid().nullable(),F=(e,n,r)=>{let i=e.safeParse(n);if(i.success)return i.data;throw new t(`BAD_REQUEST`,`${r} is invalid.`,`Run the command with --help.`)},I=e=>F(dt,e,`--base-version`),L=(e,n,r)=>{let i=Jt.safeParse(n??null);if(!i.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying the exact same command.`);e.mutationKey.select(i.data,r)},R=(e,t)=>e.mutationKey.current(`canvas.applyOperations`,{purpose:t}),z=async(e,n,r)=>{let i=f.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:n}));if(!i.success)throw new t(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(i.data.version!==r)throw new t(`CONFLICT`,`Canvas version ${String(i.data.version)} no longer matches --base-version ${String(r)}.`,`Run 'enhance canvas tree --canvas ${n}' and recompute against version ${String(i.data.version)}.`);let a=se.safeParse(i.data.document);if(a.success)return a.data;throw new t(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},B=async(e,t,n,r)=>(L(e,t.clientToken,!1),b(e.remote).execute({canvasId:j(t.canvas),mutationId:R(e,n),baseVersion:I(t.baseVersion),operations:[...r]})),Yt=(e,n,r)=>{if(!e.startsWith(`@`))return e;let i=e.slice(1);if(i===``)throw new t(`BAD_REQUEST`,`${r} @ must name a file.`,`Pass ${r} @/absolute/path/to/file or an inline value.`);let a=T.resolve(i);try{let e=C(a);if(!e.isFile()||e.size>n)throw Error(`invalid size`);return Pe(a,`utf8`)}catch{throw new t(`BAD_REQUEST`,`Could not read a bounded file at ${a}.`,`Use a regular UTF-8 file no larger than ${String(n)} bytes.`)}},V=(e,n,r)=>{let i=(()=>{try{return JSON.parse(Yt(e,1048576,r))}catch(e){throw e instanceof t?e:new t(`BAD_REQUEST`,`${r} must be valid JSON.`,`Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`)}})(),a=n.safeParse(i);if(a.success)return a.data;let o=a.error.issues[0];throw new t(`BAD_REQUEST`,`${r} is invalid${o===void 0||o.path.length===0?``:` at ${o.path.join(`.`)}`}.`,o?.message??`Correct the JSON shape and retry.`)},Xt=(e,t)=>{e.command(`set-text-content`).description(`Set Text node values.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,textContent} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.updates,gt,`--updates`).map(e=>({op:`setText`,nodeId:e.nodeId,text:e.textContent}));t.output.result(await B(t,e,`set-text-content`,n))})},Zt=(e,t)=>{e.command(`rename-nodes`).description(`Rename layers.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,name} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.updates,_t,`--updates`).map(e=>({op:`setLabel`,nodeId:e.nodeId,label:e.name,labelOrigin:`user`}));t.output.result(await B(t,e,`rename-nodes`,n))})},Qt=(e,t)=>{e.command(`delete-nodes`).description(`Delete node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.nodeIds,xt,`--node-ids`);t.output.result(await B(t,e,`delete-nodes`,n.map(e=>({op:`remove`,nodeId:e}))))})},$t=(e,t)=>{e.command(`update-styles`).description(`Update visual and layout styles.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeIds,styles} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=await z(t,j(e.canvas),I(e.baseVersion)),r=V(e.updates,vt,`--updates`);t.output.result(await B(t,e,`update-styles`,qt(n.nodes,r)))})},en=(e,t)=>{Xt(e,t),Zt(e,t),Qt(e,t),$t(e,t)},H=e=>e.space===`display-p3`?`color(display-p3 ${String(e.red)} ${String(e.green)} ${String(e.blue)} / ${String(e.alpha)})`:`rgba(${String(Math.round(e.red*255))}, ${String(Math.round(e.green*255))}, ${String(Math.round(e.blue*255))}, ${String(e.alpha)})`,U=e=>{if(!e.visible)return null;if(e.kind===`solid`)return H(e.color);if(e.kind===`image`)return`url(${JSON.stringify(e.assetId)})`;let t=e.stops.map(e=>`${H(e.color)} ${String(e.position*100)}%`).join(`, `);return e.kind===`linear-gradient`?`linear-gradient(${String(e.angle)}deg, ${t})`:`radial-gradient(at ${String(e.center.x*100)}% ${String(e.center.y*100)}%, ${t})`},tn=e=>{if(e.kind===`blur`)return`blur(${String(e.value)}px)`;if(e.kind===`hue-rotate`)return`hue-rotate(${String(e.value)}deg)`;let t=[`grayscale`,`invert`,`sepia`].includes(e.kind)?`${String(e.value*100)}%`:String(e.value);return`${e.kind}(${t})`},nn=e=>e?.flatMap(e=>{let t=U(e);return t===null?[]:[t]})??[],rn=e=>{if(e?.visible!==!0)return{};let t=U(e.paint);return{"border-width":[e.width.top,e.width.right,e.width.bottom,e.width.left].map(e=>`${String(e)}px`).join(` `),"border-style":e.style,...t!==null&&{"border-color":t}}},an=e=>{if(e?.visible!==!0)return{};let t=U(e.paint);return{"outline-width":`${String(e.width)}px`,"outline-offset":`${String(e.offset)}px`,"outline-style":e.style,...t!==null&&{"outline-color":t}}},on=e=>{let t=e.shadows?.filter(e=>e.visible).map(e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${H(e.color)}`),n=e.filters?.filter(e=>e.visible).map(tn),r=e.backdropFilters?.filter(e=>e.visible).map(tn);return{...t!==void 0&&t.length>0&&{"box-shadow":t.join(`, `)},...n!==void 0&&n.length>0&&{filter:n.join(` `)},...r!==void 0&&r.length>0&&{"backdrop-filter":r.join(` `)}}},sn=e=>{if(e===void 0)return{};let t=nn(e.fills),n=e.radius;return{...e.opacity!==void 0&&{opacity:e.opacity},...e.blendMode!==void 0&&{"mix-blend-mode":e.blendMode},...t.length>0&&{background:t.join(`, `)},...n!==void 0&&{"border-radius":[n.topLeft,n.topRight,n.bottomRight,n.bottomLeft].map(e=>`${String(e)}px`).join(` `)},...rn(e.border),...an(e.outline),...on(e)}},cn=e=>e===void 0?{}:{"font-family":[e.family,...e.fallbackFamilies].join(`, `),"font-size":`${String(e.size)}px`,"font-weight":e.weight,"font-style":e.style,"line-height":e.lineHeight.mode===`normal`?`normal`:`${String(e.lineHeight.value)}px`,"letter-spacing":`${String(e.letterSpacing)}px`,"text-align":e.align,"text-transform":e.transform,"text-decoration-line":e.decoration.line,"text-decoration-style":e.decoration.style,"white-space":e.wrapping},W=e=>e===`start`?`flex-start`:e===`end`?`flex-end`:e,ln=(e,t)=>e.mode===`fixed`?`${String(e.value)}px`:e.mode===`fill`?`100%`:`${String(t)}px`,un=(e,t)=>({position:e.position===`absolute`?`absolute`:`relative`,...e.position===`absolute`&&{left:`${String(t.x)}px`,top:`${String(t.y)}px`},width:ln(e.horizontal,t.width),height:ln(e.vertical,t.height),...e.clipContent===!0&&{overflow:`hidden`}}),dn=e=>{let t=[...e.rotation===0?[]:[`rotate(${String(e.rotation)}deg)`],...e.flipHorizontal===!0?[`scaleX(-1)`]:[],...e.flipVertical===!0?[`scaleY(-1)`]:[]];return t.length===0?{}:{transform:t.join(` `)}},fn=e=>{if(typeof e!=`object`)return e===`auto`?e:`${String(e)}px`;let t=`${String(e.ratio*100)}%`,n=e.offset??0;return n===0?t:`calc(${t} ${n<0?`-`:`+`} ${String(Math.abs(n))}px)`},pn=e=>({...e.alignSelf!==void 0&&{"align-self":W(e.alignSelf===`auto`?`start`:e.alignSelf)},...e.flexGrow!==void 0&&{"flex-grow":e.flexGrow},...e.flexShrink!==void 0&&{"flex-shrink":e.flexShrink},...e.flexBasis!==void 0&&{"flex-basis":fn(e.flexBasis)},...e.order!==void 0&&{order:e.order}}),mn=e=>{let t=e.container;return t===void 0?{}:{display:`flex`,"flex-direction":t.direction,"align-items":W(t.alignItems),"align-content":W(t.alignContent??`start`),"justify-content":W(t.justifyContent),gap:`${String(t.gap)}px`,"row-gap":`${String(t.rowGap??t.gap)}px`,"column-gap":`${String(t.columnGap??t.gap)}px`,"flex-wrap":t.wrap??`nowrap`,padding:[t.padding.top,t.padding.right,t.padding.bottom,t.padding.left].map(e=>`${String(e)}px`).join(` `)}},hn=e=>{let t=Object.fromEntries((e.additionalStyles?.declarations??[]).filter(e=>e.enabled).map(e=>[e.property,e.value])),n=e.layout===void 0||e.box===void 0?{}:{...un(e.layout,e.box),...dn(e.layout),...pn(e.layout),...mn(e.layout)};return{...e.styles,...t,...cn(e.typography),...sn(e.appearance),...n,...e.visible===!1&&{display:`none`}}},gn=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),_n=(e,n)=>{let r=e.nodes[n];if(r===void 0)throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use a current stable node id.`);return r},G=(e,t)=>{let n=e.props?.[t];return typeof n==`string`?n:``},vn=e=>`{${JSON.stringify(e)}}`,yn=(e,t,n,r)=>{let i=_n(e,t),a=` `.repeat(n),o=[`data-node-id=${JSON.stringify(i.id)}`,`data-name=${JSON.stringify(i.label)}`,`style={${JSON.stringify(hn(i))}}`];if(i.locked===!0&&o.push(`data-locked="true"`),i.component===`image`)return`${a}<img ${o.join(` `)} alt=${JSON.stringify(G(i,`alt`))} src=${JSON.stringify(G(i,`src`))} />`;if(i.component===`svg`)return`${a}<div ${o.join(` `)} data-component="svg" />`;let s=i.component===`text`?`span`:`div`,c=i.component===`text`?vn(G(i,`text`)):``,l=(n>=r?[]:gn(e,t)).map(t=>yn(e,t,n+1,r));return c===``&&l.length===0?`${a}<${s} ${o.join(` `)} />`:[`${a}<${s} ${o.join(` `)}>`,...c===``?[]:[`${a} ${c}`],...l,`${a}</${s}>`].join(`
|
|
5
|
-
`)},bn=(e,t,n)=>yn(e,t,0,n),xn=(e,t)=>t.map(t=>{let n=_n(e,t);return{nodeId:t,name:n.label,component:n.component,box:n.box,css:hn(n),layout:n.layout,appearance:n.appearance,typography:n.typography}}),Sn={topic:`canvas-agent-authoring`,workflow:[`Run canvas inspect, then canvas tree, before editing.`,`Render the target before changing it and inspect the PNG.`,`Write small visual groups incrementally with write-html.`,`Use duplicate-nodes, set-text-content, update-styles, and move-nodes instead of rewriting existing structure.`,`Use flex, padding, and gap as the primary layout tools. Avoid margin, grid, tables, and inline layout.`,`Every write requires the exact version returned by the latest read.`,`Inspect the review PNG returned by write-html and correct visual discrepancies.`,`Automatic commands show and clear their work indicator. Finish a manual work lease explicitly.`],html:{modes:[`insert-children`,`replace`],rules:[`Use inline styles and concrete CSS values.`,`Use layer-name for meaningful hierarchy names.`,`One call should add roughly one visual group.`,`Styled text controls become a frame plus an editable text child.`,`Scripts, event handlers, embedded documents, executable URLs, and CSS imports are rejected.`]},completion:[`The hierarchy is natural and uses the fewest useful editable primitives.`,`The affected version and node ids match the intended change.`,`The post-write PNG has been inspected.`,`Text, layout, paint, effects, and additional CSS remain editable in the ordinary inspector.`]},Cn=async(e,t)=>{let n=f.parse(await e.remote.query(`canvas.document.get`,{canvasId:t}));return{held:n,document:se.parse(n.document)}},wn=(e,t)=>{e.command(`guide`).description(`Agent design workflow.`).action(()=>{t.output.result(Sn)}),e.command(`get-jsx`).description(`Read concise subtree JSX.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-id <id>`,`Stable subtree root id.`).option(`--depth <integer>`,`Maximum descendant depth from 0 to 20.`,`8`).action(async e=>{let n=j(e.canvas),{held:r,document:i}=await Cn(t,n);t.output.result({canvasId:n,version:r.version,nodeId:e.nodeId,jsx:bn(i,e.nodeId,F(St,e.depth,`--depth`)),warning:`This is a structural reading projection. Use canvas render as the pixel authority.`})}),e.command(`get-computed-styles`).description(`Read effective node CSS.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).action(async e=>{let n=j(e.canvas),{held:r,document:i}=await Cn(t,n),a=V(e.nodeIds,xt,`--node-ids`);t.output.result({canvasId:n,version:r.version,nodes:xn(i,a)})})},K=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),Tn=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),q=(e,n)=>{let r=e.nodes[n];if(r!==void 0)return r;throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use a current stable node id.`)},En=(e,t)=>{let n=new Set,r=t=>{for(let i of K(e,t))n.add(i),r(i)};return r(t),n},Dn=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},On=e=>{let t=0;return n=>(t+=1,`${Dn(e)}_${Dn(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},kn=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of K(e,t))r(n)};return r(t),n},An=(e,t,n)=>Object.fromEntries(kn(e,t).map(t=>[t,n(q(e,t).label)])),jn=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=q(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let p=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??p}}},Mn=e=>{let{document:n,input:r,inputIndex:i,nextId:a}=e,o=q(n,r.id);if(r.id===`root`)throw new t(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let s=n.relationships[r.id];if(s===void 0)throw new t(`BAD_REQUEST`,`Canvas node ${r.id} is detached.`,`Choose a reachable node from canvas tree.`);let c=r.parentId??s.parentId;if(!Tn(n.nodes[c]))throw new t(`BAD_REQUEST`,`Canvas node ${c} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let l=An(n,r.id,a),u={document:n,rootId:r.id,parentId:c,inputIndex:i,sourceSortKey:s.sortKey,map:l},d=kn(n,r.id).map(e=>jn(u,e)),f=l[r.id];if(f===void 0)throw Error(`Missing duplicate root id for ${r.id}`);return{operations:d,summary:{sourceId:r.id,newId:f,name:o.label,component:o.component,descendantIdMap:Object.fromEntries(Object.entries(l).filter(([e])=>e!==r.id))}}},Nn=(e,n,r)=>{if(n.length===0)throw new t(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let i=On(r),a=n.map((t,n)=>Mn({document:e,input:t,inputIndex:n,nextId:i}));return{operations:a.flatMap(e=>e.operations),duplicatedNodes:a.map(e=>e.summary)}},Pn=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,K(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),Fn=(e,t)=>{let n=(t.children.get(e.parentId)??[]).filter(t=>t!==e.nodeId);return{parentId:e.parentId,index:Math.max(0,Math.min(e.index??n.length,n.length))}},In=(e,n)=>{let r=`before`in e?e.before:e.after;if(r===e.nodeId||n.document.nodes[r]===void 0)throw new t(`BAD_REQUEST`,`Sibling ${r} is not a valid move target.`,`Choose another current sibling node.`);let i=n.parentOf.get(r);if(i===void 0)throw new t(`BAD_REQUEST`,`Sibling ${r} is detached.`,`Choose a reachable sibling from canvas tree.`);let a=(n.children.get(i)??[]).filter(t=>t!==e.nodeId).indexOf(r);return{parentId:i,index:`before`in e?a:a+1}},Ln=(e,t)=>`parentId`in e?Fn(e,t):In(e,t),Rn=(e,n,r)=>{if(e.nodeId===`root`||r.document.nodes[e.nodeId]===void 0)throw new t(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(En(r.document,e.nodeId).has(n.parentId)||!Tn(r.document.nodes[n.parentId]))throw new t(`BAD_REQUEST`,`Canvas node ${n.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},zn=(e,t,n)=>{let r=n.parentOf.get(e.nodeId);r!==void 0&&(n.children.set(r,(n.children.get(r)??[]).filter(t=>t!==e.nodeId)),n.affected.add(r));let i=[...n.children.get(t.parentId)??[]];i.splice(t.index,0,e.nodeId),n.children.set(t.parentId,i),n.parentOf.set(e.nodeId,t.parentId),n.affected.add(t.parentId);let a=i[t.index-1];return{op:`move`,nodeId:e.nodeId,parentId:t.parentId,...a!==void 0&&{afterId:a}}},Bn=(e,n)=>{if(n.length===0)throw new t(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let r=Pn(e),i=[];return{operations:n.map(e=>{let t=Ln(e,r);return Rn(e,t,r),i.push({nodeId:e.nodeId,...t}),zn(e,t,r)}),moves:i,affectedParents:Array.from(r.affected,e=>({parentId:e,children:[...r.children.get(e)??[]]}))}},Vn=(e,t)=>{e.command(`duplicate-nodes`).description(`Deep-clone node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--nodes <json-or-@path>`,`Array of {id,parentId?} requests.`).option(`--id-prefix <prefix>`,`Stable namespace for cloned ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{L(t,e.clientToken,!1);let n=j(e.canvas),r=I(e.baseVersion),i=await z(t,n,r),a=R(t,`duplicate-nodes`),o=Nn(i,V(e.nodes,yt,`--nodes`),e.idPrefix??`copy_${a.replaceAll(`-`,``)}`),s=await b(t.remote).execute({canvasId:n,mutationId:a,baseVersion:r,operations:[...o.operations]});t.output.result({duplicatedNodes:o.duplicatedNodes,apply:s})})},Hn=(e,t)=>{e.command(`move-nodes`).description(`Reorder or reparent nodes.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--moves <json-or-@path>`,`Sequential before, after, or parent/index moves.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{L(t,e.clientToken,!1);let n=j(e.canvas),r=I(e.baseVersion),i=Bn(await z(t,n,r),V(e.moves,bt,`--moves`)),a=await b(t.remote).execute({canvasId:n,mutationId:R(t,`move-nodes`),baseVersion:r,operations:[...i.operations]});t.output.result({moves:i.moves,affectedParents:i.affectedParents,apply:a})})},Un=(e,t)=>{Vn(e,t),Hn(e,t)},Wn=262144,Gn=e=>{let n=Yt(e,Wn,`--html`);if(Buffer.byteLength(n,`utf8`)>Wn)throw new t(`BAD_REQUEST`,`--html exceeds 262144 bytes.`,`Write one visual group at a time, as taught by canvas guide.`);return n},Kn=new Set([`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`]),qn=(e,n)=>{e.command(`write-html`).description(`Compile HTML/CSS primitives.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--target-node-id <id>`,`Container receiving children, or node to replace.`).requiredOption(`--html <html-or-@path>`,`Inline HTML fragment or @path to a UTF-8 file.`).option(`--mode <mode>`,`insert-children or replace.`,`insert-children`).option(`--id-prefix <prefix>`,`Stable namespace for generated node ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact write and review.`).option(`--output <path>`,`Write the review PNG to this path.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--scale <number>`,`Review pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--timeout-ms <integer>`,`Review render polling deadline.`,`120000`).addHelpText(`after`,`
|
|
2
|
+
import{A as e,C as t,D as n,E as r,G as i,J as a,K as o,O as s,S as c,T as l,U as u,W as d,X as f,Y as p,Z as ee,c as m,d as te,et as ne,i as re,k as ie,l as ae,m as oe,n as h,o as se,ot as g,p as _,r as ce,s as le,st as ue,t as de,tt as fe,u as pe}from"./cli-output-identity.lib-C3dhDJfG.mjs";import{a as me,c as he,d as ge,f as _e,i as v,l as y,n as ve,o as ye,r as be,s as xe,t as Se,u as Ce}from"./mutation-key.adapter-HiEQIg6a.mjs";import{t as we}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{Command as Te}from"commander";import{createCli as Ee,parseRouter as De}from"trpc-cli";import{z as b}from"zod";import{hostname as Oe,tmpdir as ke}from"node:os";import x from"node:process";import{createInterface as Ae}from"node:readline";import{chmodSync as je,existsSync as Me,lstatSync as Ne,mkdirSync as Pe,readFileSync as Fe,readdirSync as Ie,statSync as Le,unlinkSync as Re,writeFileSync as S}from"node:fs";import C from"node:path";import{createHash as ze,randomUUID as w}from"node:crypto";import{readFile as Be}from"node:fs/promises";import{proxify as Ve}from"trpc-cli/dist/proxify.js";const He=()=>({rotation:0,flipHorizontal:!1,flipVertical:!1,horizontal:{mode:`fixed`,value:0},vertical:{mode:`fixed`,value:0},position:`absolute`,clipContent:!1}),T=`root`,Ue=e=>`a${String(e).padStart(4,`0`)}`,We=()=>({version:2,nodes:{[T]:{id:T,label:`Canvas`,component:`root`,styles:{}}},relationships:{}}),Ge=(e,t)=>({...e,nodes:{...e.nodes,[t.id]:t},relationships:{...e.relationships,[t.id]:{parentId:T,sortKey:Ue(Object.keys(e.relationships).length)}}}),Ke=(e,t)=>Ge(e,{id:t.id,label:t.label,component:`screen`,props:{capture:{viewport:t.viewport,atMs:0,screenId:t.screenId}},styles:{},box:{...t.at,...t.viewport}}),qe=e=>`${JSON.stringify(e)}\n`,Je=e=>{if(e<1)throw RangeError(`a chunk has to be able to hold at least one character`);let t=``,n=[],r=!1,i=!1,a=()=>{let e={body:t,continues:r,eventCount:n.length-+!!r,firstEventMs:n.length===0?0:Math.min(...n),lastEventMs:n.length===0?0:Math.max(...n)};return r=!t.endsWith(`
|
|
3
|
+
`),t=``,n=r?[n.at(-1)??0]:[],e};return{pending:()=>t.length,add:r=>{let o=[],s=qe(r.event);for(n.push(r.atMs),i=!0;t.length+s.length>=e;){let n=e-t.length;t+=s.slice(0,n),s=s.slice(n),o.push(a())}return t+=s,o},drain:()=>!i||t.length>0?[a()]:[]}},Ye=(e,t)=>{let n=Je(t);return[...e.flatMap(e=>n.add(e)),...n.drain()]},E=[`recording.start`,`recording.appendChunk`,`recording.complete`],Xe=t=>async n=>{let r=e.parse(await t.mutate(E[0],{sourceUrl:n.sourceUrl,viewport:n.viewport,pageTitle:n.pageTitle,audio:null})),i=r.upload;try{let e=Ye(n.entries,8388608);for(let[n,a]of e.entries()){let e=new TextEncoder().encode(a.body),o=await t.upload({url:i.url,headers:i.headers,body:e});i=s.parse(await t.mutate(E[1],{recordingId:r.recordingId,index:n,firstEventMs:a.firstEventMs,lastEventMs:a.lastEventMs,eventCount:a.eventCount,continues:a.continues,bytes:e.byteLength,etag:o})).upload}let a=Math.max(0,...n.entries.map(e=>e.atMs));return ie.parse(await t.mutate(E[2],{recordingId:r.recordingId,durationMs:a,viewport:n.viewport,sourceUrl:n.sourceUrl,interrupted:!1,...n.canvasId!==void 0&&{canvasId:n.canvasId},audioChunkCount:0,hasRecoverableBytes:!1}))}catch{throw new c(`Recording ${r.recordingId} began, but not every chunk was committed.`,`Run 'enhance recording discard --recording-id ${r.recordingId}' to remove the incomplete attempt before retrying the fixture.`)}},Ze=[`screen.create`,`screen.complete`],Qe=e=>async t=>{let i=n.parse(await e.mutate(Ze[0],{clientToken:t.clientToken,provenance:t.provenance,route:t.route,pageTitle:t.pageTitle,viewport:t.viewport,bytes:t.body.byteLength}));try{let n=await e.upload({url:i.upload.url,headers:i.upload.headers,body:t.body}),a=r.parse(await e.mutate(Ze[1],{screenId:i.screenId,etag:n}));return{screenId:a.screenId,route:t.route,title:t.pageTitle,viewport:t.viewport,atMs:t.provenance?.atMs??null,sourceRecordingId:t.provenance?.sourceRecordingId??null,assetBundle:null,download:null,storedBytes:a.storedBytes}}catch{throw new c(`Screen ${i.screenId} was reserved, but its upload did not complete.`,`Retry 'enhance fixture screen' with the same --client-token ${t.clientToken}.`)}},D=[`organisation.create`,`canvas.create`,`screen.create`,`screen.complete`,`canvas.document.get`,`canvas.document.save`],$e=(e,t)=>async n=>{let r=u.parse(await e.mutate(D[0],{name:n.organisationName})).organisation,i=ue.parse(await e.mutate(D[1],{title:n.canvasTitle,organisationId:r.id,sourceUrl:null}));try{let a=[];for(let e of n.screens)a.push(await t(e));let o=f.parse(await e.query(D[4],{canvasId:i.id})),s=We();for(let[e,t]of a.entries())s=Ke(s,{id:`fixture-screen-${String(e+1)}`,label:`Fixture screen ${String(e+1)}`,screenId:t.screenId,viewport:n.screens[e]?.viewport??{width:1440,height:900},at:{x:48+e*48,y:48+e*48}});let l=ee.parse(await e.mutate(D[5],{canvasId:i.id,baseVersion:o.version,document:s,screenIds:a.map(e=>e.screenId)}));if(l.outcome===`conflict`)throw new c(`World canvas ${i.id} was created, but another writer changed its document.`,`Read 'enhance canvas document get --canvas-id ${i.id}' before adding the screens.`);return{organisationId:r.id,canvasId:i.id,screenIds:a.map(e=>e.screenId),documentVersion:l.version}}catch(e){throw e instanceof c?e:new c(`Organisation ${r.id} and canvas ${i.id} exist, but the world is incomplete.`,`Inspect 'enhance canvas get --canvas-id ${i.id}' before retrying any missing steps.`)}},et=async(e,n)=>{if(e!==void 0&&e!==``)return e.trim();if(x.stdin.isTTY)throw new t(`BAD_REQUEST`,`A token is required and interactive prompting is disabled.`,`Pass '--token <token>' or pipe one line to '${n}'.`);let r=Ae({input:x.stdin,crlfDelay:1/0});for await(let e of r){r.close();let t=e.trim();if(t!==``)return t;break}throw new t(`BAD_REQUEST`,`A token is required.`,`Pass '--token <token>' or pipe one line to '${n}'.`)},tt=async e=>{if(e!==void 0)return e.trim();if(x.stdin.isTTY)return null;let t=Ae({input:x.stdin,crlfDelay:1/0});for await(let e of t){t.close();let n=e.trim();return n===``?null:n}return null},nt=(e,t,n)=>{let r=e.command(`auth`).description(`Store and inspect the agent credential.`);r.command(`login`).description(`Authenticate in a browser, then store a revocable agent credential.`).option(`--token <token>`,`Use an existing agent token instead of browser authentication.`).option(`--no-open`,`Print the authorization URL without opening the browser.`).action(async e=>{let r=await tt(e.token);if(r!==null){n.result(await t.loginWithToken(r));return}n.result(await t.loginWithBrowser({label:`CLI on ${Oe()}`.slice(0,120),openBrowser:e.open,onReady:e=>{n.result({status:`waiting_for_browser`,url:e})}}))}),r.command(`status`).description(`Resolve the stored token to its person, label, and expiry.`).action(async()=>{n.result(await t.status())}),r.command(`logout`).description(`Delete the local credential file; this does not revoke the server token.`).action(async()=>{n.result(await t.logout())})},O=1e3,rt=b.coerce.number().int().positive(),it=b.coerce.number().min(.1).max(4),at=b.uuid(),ot=b.union([b.string(),b.number(),b.null()]),st=b.record(b.string(),ot),ct=b.array(b.object({nodeId:b.string().min(1).max(200),textContent:b.string().max(1e5)})).min(1).max(O),lt=b.array(b.object({nodeId:b.string().min(1).max(200),name:b.string().max(500)})).min(1).max(O),ut=b.array(b.object({nodeIds:b.array(b.string().min(1).max(200)).min(1).max(100),styles:st})).min(1).max(100),dt=b.array(b.object({id:b.string().min(1).max(200),parentId:b.string().min(1).max(200).optional()})).min(1).max(100),ft=b.array(b.union([b.object({nodeId:b.string().min(1).max(200),before:b.string().min(1).max(200)}),b.object({nodeId:b.string().min(1).max(200),after:b.string().min(1).max(200)}),b.object({nodeId:b.string().min(1).max(200),parentId:b.string().min(1).max(200),index:b.number().int().nonnegative().optional()})])).min(1).max(100),pt=b.array(b.string().min(1).max(200)).min(1).max(O),mt=b.coerce.number().int().min(0).max(20),ht=b.uuid(),gt=b.array(b.string().min(1).max(200)).min(1),_t=/^\/c\/([^/]+)\/?$/u,vt=e=>{try{return new URL(e)}catch{return null}},k=e=>{let n=e.trim(),r=ht.safeParse(n);if(r.success)return{canvasId:r.data,nodeIds:[]};let i=vt(n);if(i!==null&&(i.protocol===`http:`||i.protocol===`https:`)){let e=ht.safeParse(_t.exec(i.pathname.toLowerCase())?.[1]);if(e.success){let n=new URLSearchParams(i.hash.slice(1)).getAll(`selection`);if(n.length===0)return{canvasId:e.data,nodeIds:[]};let r=gt.safeParse(n);if(!r.success)throw new t(`BAD_REQUEST`,`The link contains an invalid selection.`,`Copy the selection link again from the canvas.`);return{canvasId:e.data,nodeIds:[...new Set(r.data)]}}}throw new t(`BAD_REQUEST`,`The canvas reference is neither a canvas URL nor a UUID.`,`Paste an HTTP(S) URL shaped https://app.example/c/<UUID>, or pass the bare canvas UUID.`)},A=e=>{let n=k(e);if(n.nodeIds.length>0)throw new t(`BAD_REQUEST`,`This command cannot discard the link selection: ${n.nodeIds.join(`, `)}.`,`Inspect the selection with canvas tree and use a targeted edit. Use a canvas URL without a selection only when the request covers the whole canvas.`);return n.canvasId},j=(e,n)=>{let r=e.nodeIds.filter(e=>n.nodes[e]===void 0);if(r.length>0)throw new t(`NOT_FOUND`,`The link selection no longer exists: ${r.join(`, `)}.`,`Copy a current selection link; do not substitute other canvas content.`);let i=new Set(e.nodeIds),a=e=>{for(let[t,r]of Object.entries(n.relationships))r.parentId!==e||i.has(t)||(i.add(t),a(t))};for(let t of e.nodeIds)a(t);return i},M=(e,t,n)=>{if(e.nodeIds.length===0)return;let r=j(e,t);yt(r,n)},yt=(e,n)=>{let r=n.filter(t=>!e.has(t));if(r.length>0)throw new t(`BAD_REQUEST`,`These nodes are outside the link selection: ${r.join(`, `)}.`,`Limit the edit to the selected nodes and their descendants. Request a wider selection only when the person wants a wider change.`)},bt=(e,n)=>{switch(e.op){case`insertNode`:return{required:[e.parentage.parentId],inserted:[e.node.id]};case`insertText`:case`insertPrototype`:return{required:[e.parentId,...e.afterId===void 0?[]:[e.afterId]],inserted:[e.nodeId]};case`insertConvertedSubtree`:if(e.destination.kind===`adjacent`)throw new t(`BAD_REQUEST`,`Adjacent conversion would insert outside the link selection.`,`Use insert-children or replace with a selected target.`);return{required:[e.destination.targetNodeId],inserted:Object.keys(e.nodes)};case`move`:case`setParentage`:{let t=e.op===`move`?e.parentId:e.parentage.parentId;return{required:[e.nodeId,...t===n.relationships[e.nodeId]?.parentId?[]:[t]],inserted:[]}}case`setPrototypeDeployment`:case`setText`:case`setBox`:case`setLabel`:case`setVisibility`:case`setLocked`:case`setConstraints`:case`setStyles`:case`setAppearance`:case`setLayout`:case`setTypography`:case`setAdditionalStyles`:case`setProps`:case`remove`:return{required:[e.nodeId],inserted:[]}}},N=(e,t,n)=>{if(e.nodeIds.length===0)return;let r=new Set(j(e,t));for(let e of n){let{required:n,inserted:i}=bt(e,t);yt(r,[...n,...i.filter(e=>t.nodes[e]!==void 0)]);for(let e of i)r.add(e)}},xt=b.uuid().nullable(),P=(e,n,r)=>{let i=e.safeParse(n);if(i.success)return i.data;throw new t(`BAD_REQUEST`,`${r} is invalid.`,`Run the command with --help.`)},F=e=>P(rt,e,`--base-version`),I=(e,n,r)=>{let i=xt.safeParse(n??null);if(!i.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying the exact same command.`);e.mutationKey.select(i.data,r)},L=(e,t)=>e.mutationKey.current(`canvas.applyOperations`,{purpose:t}),R=async(e,n,r)=>{let i=f.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:n}));if(!i.success)throw new t(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(i.data.version!==r)throw new t(`CONFLICT`,`Canvas version ${String(i.data.version)} no longer matches --base-version ${String(r)}.`,`Run 'enhance canvas tree --canvas ${n}' and recompute against version ${String(i.data.version)}.`);let a=g.safeParse(i.data.document);if(a.success)return a.data;throw new t(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},z=async(e,t,n,r)=>{I(e,t.clientToken,!1);let i=k(t.canvas),a=F(t.baseVersion);return i.nodeIds.length>0&&N(i,await R(e,i.canvasId,a),r),y(e.remote).execute({canvasId:i.canvasId,mutationId:L(e,n),baseVersion:a,operations:[...r]})},St=b.array(a).min(1).max(o),Ct=e=>{if(!e.startsWith(`@`))return e;let n=e.slice(1);if(n===``)throw new t(`BAD_REQUEST`,`--operations @ must name a JSON file.`,`Pass --operations @/absolute/path/layout.json or an inline JSON array.`);let r=C.resolve(n);try{let e=Le(r);if(!e.isFile()||e.size>1048576)throw Error(`invalid size`);return Fe(r,`utf8`)}catch{throw new t(`BAD_REQUEST`,`Could not read a bounded operations file at ${r}.`,`Use a regular JSON file no larger than 1 MiB.`)}},wt=e=>{try{return JSON.parse(Ct(e))}catch(e){throw e instanceof t?e:new t(`BAD_REQUEST`,`--operations must be one valid JSON array.`,`Pass inline JSON or @/absolute/path/layout.json; run 'enhance canvas apply --help' for examples.`)}},Tt=e=>{let n=wt(e),r=St.safeParse(n);if(!r.success){let e=r.error.issues[0];throw new t(`BAD_REQUEST`,`The canvas operation batch is invalid${e===void 0||e.path.length===0?``:` at ${e.path.join(`.`)}`}.`,`Correct the named operation; run 'enhance canvas apply --help' for the supported vocabulary.`)}return r.data},B=(e,t)=>{let n=e.find(e=>e.id===t);if(n===void 0)throw TypeError(`${t} is missing from the capability catalogue`);return n},Et=b.coerce.number().int().positive(),Dt=e=>{let n=Et.safeParse(e);if(n.success)return n.data;throw new t(`BAD_REQUEST`,`--base-version is invalid.`,`Run 'enhance canvas apply --help'.`)},Ot=(e,n)=>{let r=b.uuid().nullable().safeParse(n??null);if(!r.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact operation batch.`);return e.mutationKey.select(r.data,!1),e.mutationKey.current(`canvas.applyOperations`,{})},kt=(e,t)=>{e.command(`apply`).description(`Apply an atomic canvas edit batch and return its affected bounds.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact version returned by canvas inspect or tree.`).requiredOption(`--operations <json-or-@path>`,`JSON operation array inline, or @path to a JSON file.`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this exact batch.`).addHelpText(`after`,[``,`Supported operations: insertNode, insertText, insertPrototype, setText, setBox, setLabel, setVisibility, setLocked, setConstraints, setStyles, setAppearance, setLayout, setTypography, setAdditionalStyles, setProps, setParentage, move, remove.`,`Example:`,` enhance canvas apply --canvas <url-or-id> --base-version 3 --operations '[{"op":"insertText","nodeId":"txt_summary","parentId":"root","text":"Checkout needs an address.","box":{"x":120,"y":594,"width":720,"height":80},"styles":{"font-size":24}}]'`].join(`
|
|
4
|
+
`)).action(async e=>{Ot(t,e.clientToken);let n=k(e.canvas),r=Dt(e.baseVersion),i=Tt(e.operations);n.nodeIds.length>0&&N(n,await R(t,n.canvasId,r),i);let a=await t.invocation.invoke({capability:B(t.catalog(),`canvas.apply`),arguments:{canvasId:n.canvasId,baseVersion:r,operations:[...i]},clientToken:e.clientToken??null});t.output.result(a)})},At=e=>{try{return JSON.parse(e)}catch{return}},jt=e=>{if(e===void 0)return null;let n=fe.safeParse(At(e));if(n.success)return n.data;throw new t(`BAD_REQUEST`,`--bounds must be a positive world rectangle.`,`Pass JSON with x, y, width and height.`)},Mt=e=>e===void 0?[]:e.split(`,`).map(e=>e.trim()).filter(e=>e!==``).slice(0,100),Nt=(e,n)=>{e.command(`begin`).description(`Start visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--phase <phase>`,`reading, writing, creating, deleting, or rendering.`).option(`--node-ids <ids>`,`Comma-separated stable node ids.`).option(`--bounds <json>`,`Optional world rectangle for not-yet-created content.`).action(async e=>{let r=i.safeParse(e.phase);if(!r.success)throw new t(`BAD_REQUEST`,`--phase is invalid.`,`Use reading, writing, creating, deleting, or rendering.`);let a=A(e.canvas),o=d.parse(await n.remote.mutate(`canvas.realtime.activity.begin`,{canvasId:a,phase:r.data,nodeIds:Mt(e.nodeIds),bounds:jt(e.bounds)}));n.output.result({...o,next:[`enhance canvas work update --canvas ${a} --activity-id ${o.activityId} --phase ${r.data}`,`enhance canvas finish-working-on-nodes --canvas ${a} --activity-id ${o.activityId}`]})})},Pt=(e,t)=>{e.command(`update`).description(`Move visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by work begin.`).requiredOption(`--phase <phase>`,`Current agent phase.`).option(`--node-ids <ids>`,`Comma-separated current stable node ids.`).option(`--bounds <json>`,`Optional current world rectangle.`).action(async e=>{t.output.result(d.parse(await t.remote.mutate(`canvas.realtime.activity.renew`,{canvasId:A(e.canvas),activityId:at.parse(e.activityId),phase:i.parse(e.phase),nodeIds:Mt(e.nodeIds),bounds:jt(e.bounds)})))})},Ft=(e,n)=>{e.command(`finish-working-on-nodes`).description(`End visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by canvas work begin.`).action(async e=>{if(!await Ce(n.remote).finish(A(e.canvas),at.parse(e.activityId)))throw new t(`NOT_FOUND`,`The activity could not be finished.`,`It may already have expired; run canvas work begin for new work.`);n.output.result({ended:!0,activityId:e.activityId})})},It=(e,t)=>{let n=e.command(`work`).description(`Manage visible agent activity.`);Nt(n,t),Pt(n,t),Ft(e,t)},Lt=/^(?:align|bottom|column-gap|display|flex|gap|height|justify|left|order|overflow|padding|position|right|row-gap|top|transform|width)/u,V=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e!=`string`)return null;let t=/^(-?\d+(?:\.\d+)?)(?:px)?$/u.exec(e.trim());return t===null?null:Number(t[1])},Rt=(e,t)=>{let n=V(e);return n===null?[`100%`,`fill`].includes(String(e))?{mode:`fill`}:[`fit-content`,`auto`,`hug`].includes(String(e))?{mode:`hug`}:t:{mode:`fixed`,value:Math.max(0,n)}},zt=(e,t,n)=>{let r=e[t],[i=n.top,a=i,o=i,s=a]=typeof r==`string`?r.split(/\s+/u).map(e=>V(e)??0):typeof r==`number`?[r]:[];return{top:Math.max(0,V(e[`${t}-top`])??i),right:Math.max(0,V(e[`${t}-right`])??a),bottom:Math.max(0,V(e[`${t}-bottom`])??o),left:Math.max(0,V(e[`${t}-left`])??s)}},Bt=(e,t)=>{switch(e){case`center`:case`start`:case`stretch`:return e;case`end`:case`flex-end`:return`end`;case`flex-start`:return`start`;default:return t}},Vt=(e,t)=>{switch(e){case`center`:case`space-around`:case`space-between`:case`space-evenly`:case`start`:return e;case`end`:case`flex-end`:return`end`;case`flex-start`:return`start`;default:return t}},Ht=()=>({direction:`column`,alignItems:`start`,alignContent:`start`,justifyContent:`start`,gap:0,rowGap:0,columnGap:0,wrap:`nowrap`,padding:{top:0,right:0,bottom:0,left:0}}),Ut=(e,t)=>{let n=t.display;if([`block`,`none`].includes(String(n)))return;let r=[`flex`,`inline-flex`].includes(String(n));if(e===void 0&&!r)return;let i={...e??Ht()},a=t[`flex-direction`];return i.direction=a===void 0?i.direction:String(a).startsWith(`row`)?`row`:`column`,i.alignItems=Bt(t[`align-items`],i.alignItems),i.justifyContent=Vt(t[`justify-content`],i.justifyContent),i.alignContent=Vt(t[`align-content`],i.alignContent===`stretch`?`start`:i.alignContent??`start`),i.gap=Math.max(0,V(t.gap)??i.gap),i.rowGap=Math.max(0,V(t[`row-gap`])??i.rowGap??i.gap),i.columnGap=Math.max(0,V(t[`column-gap`])??i.columnGap??i.gap),i.wrap=t[`flex-wrap`]===`wrap`?`wrap`:i.wrap??`nowrap`,i.padding=zt(t,`padding`,i.padding),i},Wt=(e,t)=>{let n=V(t[`flex-grow`]),r=V(t[`flex-shrink`]),i=V(t.order);return{horizontal:Rt(t.width,e.horizontal),vertical:Rt(t.height,e.vertical),...t[`align-self`]!==void 0&&{alignSelf:Bt(t[`align-self`],`start`)},...n!==null&&{flexGrow:Math.max(0,n)},...r!==null&&{flexShrink:Math.max(0,r)},...t[`flex-basis`]!==void 0&&{flexBasis:V(t[`flex-basis`])??`auto`},...i!==null&&{order:Math.round(i)}}},Gt=(e,t)=>{if(Object.keys(t).every(e=>!Lt.test(e)))return null;let n=e.box??{x:0,y:0,width:1,height:1},r=e.layout??{...He(),horizontal:{mode:`fixed`,value:n.width},vertical:{mode:`fixed`,value:n.height}},i=/rotate\(\s*(-?\d+(?:\.\d+)?)deg\s*\)/u.exec(String(t.transform??``))?.[1],a=`${String(t.overflow??``)} ${String(t[`overflow-x`]??``)} ${String(t[`overflow-y`]??``)}`,o=Ut(r.container,t),s=t.position;return{...r,...Wt(r,t),rotation:i===void 0?r.rotation:Number(i),position:s===`absolute`?`absolute`:[`relative`,`flow`].includes(String(s))?`flow`:r.position,clipContent:/\b(?:clip|hidden)\b/u.test(a)||r.clipContent,...o===void 0?{container:void 0}:{container:o}}},Kt=(e,t)=>{if(e.box===void 0)return null;let n=V(t.left),r=V(t.top),i=V(t.width),a=V(t.height);return n===null&&r===null&&i===null&&a===null?null:{op:`setBox`,nodeId:e.id,box:{x:n??e.box.x,y:r??e.box.y,width:Math.max(1,i??e.box.width),height:Math.max(1,a??e.box.height)}}},qt=/^(?:align|bottom|column-gap|display|flex|gap|height|justify|left|margin|order|overflow|padding|position|right|row-gap|top|transform|width)/u,Jt=e=>e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),Yt=e=>!/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu.test(e),Xt=(e,n)=>{let r=new Map((e.additionalStyles?.declarations??[]).map(e=>[e.property,e])),i=!1;for(let[e,a]of Object.entries(n)){if(p.safeParse({[e]:a}).success||qt.test(e))continue;if(i=!0,a===null){r.delete(e);continue}let n=String(a);if(!Yt(n))throw new t(`BAD_REQUEST`,`Style ${e} contains executable CSS.`,`Remove imports, expressions, and executable URL schemes.`);r.set(e,{id:r.get(e)?.id??`css-${e}`.slice(0,200),property:e,value:n,enabled:!0})}let a=[];for(let e of r.values()){if(a.length>=128)break;a.push(e)}return i?{op:`setAdditionalStyles`,nodeId:e.id,additionalStyles:{declarations:a}}:null},Zt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[Jt(e),t])),Qt=(e,t)=>{let n=Zt(t),r=[],i=Kt(e,n);i!==null&&r.push(i);let a=Object.fromEntries(Object.entries(n).filter(([e,t])=>p.safeParse({[e]:t}).success));Object.keys(a).length>0&&r.push({op:`setStyles`,nodeId:e.id,styles:p.parse(a)});let o=Gt(e,n);o!==null&&r.push({op:`setLayout`,nodeId:e.id,layout:o});let s=Xt(e,n);return s!==null&&r.push(s),n.display===`none`&&r.push({op:`setVisibility`,nodeId:e.id,visible:!1}),r},$t=(e,n)=>{let r=e[n];if(r!==void 0)return r;throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use current stable node ids.`)},en=(e,n)=>{let r=n.flatMap(t=>t.nodeIds.flatMap(n=>Qt($t(e,n),t.styles)));if(r.length===0)throw new t(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return r},tn=(e,n,r)=>{if(!e.startsWith(`@`))return e;let i=e.slice(1);if(i===``)throw new t(`BAD_REQUEST`,`${r} @ must name a file.`,`Pass ${r} @/absolute/path/to/file or an inline value.`);let a=C.resolve(i);try{let e=Le(a);if(!e.isFile()||e.size>n)throw Error(`invalid size`);return Fe(a,`utf8`)}catch{throw new t(`BAD_REQUEST`,`Could not read a bounded file at ${a}.`,`Use a regular UTF-8 file no larger than ${String(n)} bytes.`)}},H=(e,n,r)=>{let i=(()=>{try{return JSON.parse(tn(e,1048576,r))}catch(e){throw e instanceof t?e:new t(`BAD_REQUEST`,`${r} must be valid JSON.`,`Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`)}})(),a=n.safeParse(i);if(a.success)return a.data;let o=a.error.issues[0];throw new t(`BAD_REQUEST`,`${r} is invalid${o===void 0||o.path.length===0?``:` at ${o.path.join(`.`)}`}.`,o?.message??`Correct the JSON shape and retry.`)},nn=(e,t)=>{e.command(`set-text-content`).description(`Set Text node values.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,textContent} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=H(e.updates,ct,`--updates`).map(e=>({op:`setText`,nodeId:e.nodeId,text:e.textContent}));t.output.result(await z(t,e,`set-text-content`,n))})},rn=(e,t)=>{e.command(`rename-nodes`).description(`Rename layers.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,name} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=H(e.updates,lt,`--updates`).map(e=>({op:`setLabel`,nodeId:e.nodeId,label:e.name,labelOrigin:`user`}));t.output.result(await z(t,e,`rename-nodes`,n))})},an=(e,t)=>{e.command(`delete-nodes`).description(`Delete node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=H(e.nodeIds,pt,`--node-ids`);t.output.result(await z(t,e,`delete-nodes`,n.map(e=>({op:`remove`,nodeId:e}))))})},on=(e,t)=>{e.command(`update-styles`).description(`Update visual and layout styles.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeIds,styles} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=k(e.canvas).canvasId,r=await R(t,n,F(e.baseVersion)),i=H(e.updates,ut,`--updates`);t.output.result(await z(t,e,`update-styles`,en(r.nodes,i)))})},sn=(e,t)=>{nn(e,t),rn(e,t),an(e,t),on(e,t)},U=e=>e.space===`display-p3`?`color(display-p3 ${String(e.red)} ${String(e.green)} ${String(e.blue)} / ${String(e.alpha)})`:`rgba(${String(Math.round(e.red*255))}, ${String(Math.round(e.green*255))}, ${String(Math.round(e.blue*255))}, ${String(e.alpha)})`,W=e=>{if(!e.visible)return null;if(e.kind===`solid`)return U(e.color);if(e.kind===`image`)return`url(${JSON.stringify(e.assetId)})`;let t=e.stops.map(e=>`${U(e.color)} ${String(e.position*100)}%`).join(`, `);return e.kind===`linear-gradient`?`linear-gradient(${String(e.angle)}deg, ${t})`:`radial-gradient(at ${String(e.center.x*100)}% ${String(e.center.y*100)}%, ${t})`},cn=e=>{if(e.kind===`blur`)return`blur(${String(e.value)}px)`;if(e.kind===`hue-rotate`)return`hue-rotate(${String(e.value)}deg)`;let t=[`grayscale`,`invert`,`sepia`].includes(e.kind)?`${String(e.value*100)}%`:String(e.value);return`${e.kind}(${t})`},ln=e=>e?.flatMap(e=>{let t=W(e);return t===null?[]:[t]})??[],un=e=>{if(e?.visible!==!0)return{};let t=W(e.paint);return{"border-width":[e.width.top,e.width.right,e.width.bottom,e.width.left].map(e=>`${String(e)}px`).join(` `),"border-style":e.style,...t!==null&&{"border-color":t}}},dn=e=>{if(e?.visible!==!0)return{};let t=W(e.paint);return{"outline-width":`${String(e.width)}px`,"outline-offset":`${String(e.offset)}px`,"outline-style":e.style,...t!==null&&{"outline-color":t}}},fn=e=>{let t=e.shadows?.filter(e=>e.visible).map(e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${U(e.color)}`),n=e.filters?.filter(e=>e.visible).map(cn),r=e.backdropFilters?.filter(e=>e.visible).map(cn);return{...t!==void 0&&t.length>0&&{"box-shadow":t.join(`, `)},...n!==void 0&&n.length>0&&{filter:n.join(` `)},...r!==void 0&&r.length>0&&{"backdrop-filter":r.join(` `)}}},pn=e=>{if(e===void 0)return{};let t=ln(e.fills),n=e.radius;return{...e.opacity!==void 0&&{opacity:e.opacity},...e.blendMode!==void 0&&{"mix-blend-mode":e.blendMode},...t.length>0&&{background:t.join(`, `)},...n!==void 0&&{"border-radius":[n.topLeft,n.topRight,n.bottomRight,n.bottomLeft].map(e=>`${String(e)}px`).join(` `)},...un(e.border),...dn(e.outline),...fn(e)}},mn=e=>e===void 0?{}:{"font-family":[e.family,...e.fallbackFamilies].join(`, `),"font-size":`${String(e.size)}px`,"font-weight":e.weight,"font-style":e.style,"line-height":e.lineHeight.mode===`normal`?`normal`:`${String(e.lineHeight.value)}px`,"letter-spacing":`${String(e.letterSpacing)}px`,"text-align":e.align,"text-transform":e.transform,"text-decoration-line":e.decoration.line,"text-decoration-style":e.decoration.style,"white-space":e.wrapping},G=e=>e===`start`?`flex-start`:e===`end`?`flex-end`:e,hn=(e,t)=>e.mode===`fixed`?`${String(e.value)}px`:e.mode===`fill`?`100%`:`${String(t)}px`,gn=(e,t)=>({position:e.position===`absolute`?`absolute`:`relative`,...e.position===`absolute`&&{left:`${String(t.x)}px`,top:`${String(t.y)}px`},width:hn(e.horizontal,t.width),height:hn(e.vertical,t.height),...e.clipContent===!0&&{overflow:`hidden`}}),_n=e=>{let t=[...e.rotation===0?[]:[`rotate(${String(e.rotation)}deg)`],...e.flipHorizontal===!0?[`scaleX(-1)`]:[],...e.flipVertical===!0?[`scaleY(-1)`]:[]];return t.length===0?{}:{transform:t.join(` `)}},vn=e=>{if(typeof e!=`object`)return e===`auto`?e:`${String(e)}px`;let t=`${String(e.ratio*100)}%`,n=e.offset??0;return n===0?t:`calc(${t} ${n<0?`-`:`+`} ${String(Math.abs(n))}px)`},yn=e=>({...e.alignSelf!==void 0&&{"align-self":G(e.alignSelf===`auto`?`start`:e.alignSelf)},...e.flexGrow!==void 0&&{"flex-grow":e.flexGrow},...e.flexShrink!==void 0&&{"flex-shrink":e.flexShrink},...e.flexBasis!==void 0&&{"flex-basis":vn(e.flexBasis)},...e.order!==void 0&&{order:e.order}}),bn=e=>{let t=e.container;return t===void 0?{}:{display:`flex`,"flex-direction":t.direction,"align-items":G(t.alignItems),"align-content":G(t.alignContent??`start`),"justify-content":G(t.justifyContent),gap:`${String(t.gap)}px`,"row-gap":`${String(t.rowGap??t.gap)}px`,"column-gap":`${String(t.columnGap??t.gap)}px`,"flex-wrap":t.wrap??`nowrap`,padding:[t.padding.top,t.padding.right,t.padding.bottom,t.padding.left].map(e=>`${String(e)}px`).join(` `)}},xn=e=>{let t=Object.fromEntries((e.additionalStyles?.declarations??[]).filter(e=>e.enabled).map(e=>[e.property,e.value])),n=e.layout===void 0||e.box===void 0?{}:{...gn(e.layout,e.box),..._n(e.layout),...yn(e.layout),...bn(e.layout)};return{...e.styles,...t,...mn(e.typography),...pn(e.appearance),...n,...e.visible===!1&&{display:`none`}}},Sn=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),Cn=(e,n)=>{let r=e.nodes[n];if(r===void 0)throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use a current stable node id.`);return r},K=(e,t)=>{let n=e.props?.[t];return typeof n==`string`?n:``},wn=e=>`{${JSON.stringify(e)}}`,Tn=(e,t,n,r)=>{let i=Cn(e,t),a=` `.repeat(n),o=[`data-node-id=${JSON.stringify(i.id)}`,`data-name=${JSON.stringify(i.label)}`,`style={${JSON.stringify(xn(i))}}`];if(i.locked===!0&&o.push(`data-locked="true"`),i.component===`image`)return`${a}<img ${o.join(` `)} alt=${JSON.stringify(K(i,`alt`))} src=${JSON.stringify(K(i,`src`))} />`;if(i.component===`svg`)return`${a}<div ${o.join(` `)} data-component="svg" />`;let s=i.component===`text`?`span`:`div`,c=i.component===`text`?wn(K(i,`text`)):``,l=(n>=r?[]:Sn(e,t)).map(t=>Tn(e,t,n+1,r));return c===``&&l.length===0?`${a}<${s} ${o.join(` `)} />`:[`${a}<${s} ${o.join(` `)}>`,...c===``?[]:[`${a} ${c}`],...l,`${a}</${s}>`].join(`
|
|
5
|
+
`)},En=(e,t,n)=>Tn(e,t,0,n),Dn=(e,t)=>t.map(t=>{let n=Cn(e,t);return{nodeId:t,name:n.label,component:n.component,box:n.box,css:xn(n),layout:n.layout,appearance:n.appearance,typography:n.typography}}),On={topic:`canvas-agent-authoring`,workflow:[`Run canvas inspect, then canvas tree, before editing. Keep a pasted selection link intact as --canvas on every read and edit; it limits the request to those nodes and their descendants.`,`Render the target before changing it and inspect the PNG.`,`Write small visual groups incrementally with write-html.`,`Use duplicate-nodes, set-text-content, update-styles, and move-nodes instead of rewriting existing structure.`,`Use flex, padding, and gap as the primary layout tools. Avoid margin, grid, tables, and inline layout.`,`Every write requires the exact version returned by the latest read.`,`Inspect the review PNG returned by write-html and correct visual discrepancies.`,`Automatic commands show and clear their work indicator. Finish a manual work lease explicitly.`],html:{modes:[`insert-children`,`replace`],rules:[`Use inline styles and concrete CSS values.`,`Use layer-name for meaningful hierarchy names.`,`One call should add roughly one visual group.`,`Styled text controls become a frame plus an editable text child.`,`Scripts, event handlers, embedded documents, executable URLs, and CSS imports are rejected.`]},completion:[`The hierarchy is natural and uses the fewest useful editable primitives.`,`The affected version and node ids match the intended change.`,`The post-write PNG has been inspected.`,`Text, layout, paint, effects, and additional CSS remain editable in the ordinary inspector.`]},kn=async(e,t)=>{let n=f.parse(await e.remote.query(`canvas.document.get`,{canvasId:t}));return{held:n,document:g.parse(n.document)}},An=(e,t)=>{e.command(`guide`).description(`Agent design workflow.`).action(()=>{t.output.result(On)}),e.command(`get-jsx`).description(`Read concise subtree JSX.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-id <id>`,`Stable subtree root id.`).option(`--depth <integer>`,`Maximum descendant depth from 0 to 20.`,`8`).action(async e=>{let n=k(e.canvas),r=n.canvasId,{held:i,document:a}=await kn(t,r);M(n,a,[e.nodeId]),t.output.result({canvasId:r,version:i.version,nodeId:e.nodeId,jsx:En(a,e.nodeId,P(mt,e.depth,`--depth`)),warning:`This is a structural reading projection. Use canvas render as the pixel authority.`})}),e.command(`get-computed-styles`).description(`Read effective node CSS.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).action(async e=>{let n=k(e.canvas),r=n.canvasId,{held:i,document:a}=await kn(t,r),o=H(e.nodeIds,pt,`--node-ids`);M(n,a,o),t.output.result({canvasId:r,version:i.version,nodes:Dn(a,o)})})},q=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),jn=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),J=(e,n)=>{let r=e.nodes[n];if(r!==void 0)return r;throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use a current stable node id.`)},Mn=(e,t)=>{let n=new Set,r=t=>{for(let i of q(e,t))n.add(i),r(i)};return r(t),n},Nn=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},Pn=e=>{let t=0;return n=>(t+=1,`${Nn(e)}_${Nn(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},Fn=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of q(e,t))r(n)};return r(t),n},In=(e,t,n)=>Object.fromEntries(Fn(e,t).map(t=>[t,n(J(e,t).label)])),Ln=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=J(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let p=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??p}}},Rn=e=>{let{document:n,input:r,inputIndex:i,nextId:a}=e,o=J(n,r.id);if(r.id===`root`)throw new t(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let s=n.relationships[r.id];if(s===void 0)throw new t(`BAD_REQUEST`,`Canvas node ${r.id} is detached.`,`Choose a reachable node from canvas tree.`);let c=r.parentId??s.parentId;if(!jn(n.nodes[c]))throw new t(`BAD_REQUEST`,`Canvas node ${c} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let l=In(n,r.id,a),u={document:n,rootId:r.id,parentId:c,inputIndex:i,sourceSortKey:s.sortKey,map:l},d=Fn(n,r.id).map(e=>Ln(u,e)),f=l[r.id];if(f===void 0)throw Error(`Missing duplicate root id for ${r.id}`);return{operations:d,summary:{sourceId:r.id,newId:f,name:o.label,component:o.component,descendantIdMap:Object.fromEntries(Object.entries(l).filter(([e])=>e!==r.id))}}},zn=(e,n,r)=>{if(n.length===0)throw new t(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let i=Pn(r),a=n.map((t,n)=>Rn({document:e,input:t,inputIndex:n,nextId:i}));return{operations:a.flatMap(e=>e.operations),duplicatedNodes:a.map(e=>e.summary)}},Bn=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,q(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),Vn=(e,t)=>{let n=(t.children.get(e.parentId)??[]).filter(t=>t!==e.nodeId);return{parentId:e.parentId,index:Math.max(0,Math.min(e.index??n.length,n.length))}},Hn=(e,n)=>{let r=`before`in e?e.before:e.after;if(r===e.nodeId||n.document.nodes[r]===void 0)throw new t(`BAD_REQUEST`,`Sibling ${r} is not a valid move target.`,`Choose another current sibling node.`);let i=n.parentOf.get(r);if(i===void 0)throw new t(`BAD_REQUEST`,`Sibling ${r} is detached.`,`Choose a reachable sibling from canvas tree.`);let a=(n.children.get(i)??[]).filter(t=>t!==e.nodeId).indexOf(r);return{parentId:i,index:`before`in e?a:a+1}},Un=(e,t)=>`parentId`in e?Vn(e,t):Hn(e,t),Wn=(e,n,r)=>{if(e.nodeId===`root`||r.document.nodes[e.nodeId]===void 0)throw new t(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Mn(r.document,e.nodeId).has(n.parentId)||!jn(r.document.nodes[n.parentId]))throw new t(`BAD_REQUEST`,`Canvas node ${n.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},Gn=(e,t,n)=>{let r=n.parentOf.get(e.nodeId);r!==void 0&&(n.children.set(r,(n.children.get(r)??[]).filter(t=>t!==e.nodeId)),n.affected.add(r));let i=[...n.children.get(t.parentId)??[]];i.splice(t.index,0,e.nodeId),n.children.set(t.parentId,i),n.parentOf.set(e.nodeId,t.parentId),n.affected.add(t.parentId);let a=i[t.index-1];return{op:`move`,nodeId:e.nodeId,parentId:t.parentId,...a!==void 0&&{afterId:a}}},Kn=(e,n)=>{if(n.length===0)throw new t(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let r=Bn(e),i=[];return{operations:n.map(e=>{let t=Un(e,r);return Wn(e,t,r),i.push({nodeId:e.nodeId,...t}),Gn(e,t,r)}),moves:i,affectedParents:Array.from(r.affected,e=>({parentId:e,children:[...r.children.get(e)??[]]}))}},qn=(e,t)=>{e.command(`duplicate-nodes`).description(`Deep-clone node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--nodes <json-or-@path>`,`Array of {id,parentId?} requests.`).option(`--id-prefix <prefix>`,`Stable namespace for cloned ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{I(t,e.clientToken,!1);let n=k(e.canvas),r=n.canvasId,i=F(e.baseVersion),a=await R(t,r,i),o=L(t,`duplicate-nodes`),s=H(e.nodes,dt,`--nodes`);M(n,a,s.flatMap(e=>[e.id,...e.parentId===void 0||e.parentId===a.relationships[e.id]?.parentId?[]:[e.parentId]]));let c=zn(a,s,e.idPrefix??`copy_${o.replaceAll(`-`,``)}`),l=await y(t.remote).execute({canvasId:r,mutationId:o,baseVersion:i,operations:[...c.operations]});t.output.result({duplicatedNodes:c.duplicatedNodes,apply:l})})},Jn=(e,t)=>{e.command(`move-nodes`).description(`Reorder or reparent nodes.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--moves <json-or-@path>`,`Sequential before, after, or parent/index moves.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{I(t,e.clientToken,!1);let n=k(e.canvas),r=n.canvasId,i=F(e.baseVersion),a=await R(t,r,i),o=Kn(a,H(e.moves,ft,`--moves`));N(n,a,o.operations);let s=await y(t.remote).execute({canvasId:r,mutationId:L(t,`move-nodes`),baseVersion:i,operations:[...o.operations]});t.output.result({moves:o.moves,affectedParents:o.affectedParents,apply:s})})},Yn=(e,t)=>{qn(e,t),Jn(e,t)},Xn=262144,Zn=e=>{let n=tn(e,Xn,`--html`);if(Buffer.byteLength(n,`utf8`)>Xn)throw new t(`BAD_REQUEST`,`--html exceeds 262144 bytes.`,`Write one visual group at a time, as taught by canvas guide.`);return n},Qn=new Set([`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`]),$n=(e,n)=>{e.command(`write-html`).description(`Compile HTML/CSS primitives.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--target-node-id <id>`,`Container receiving children, or node to replace.`).requiredOption(`--html <html-or-@path>`,`Inline HTML fragment or @path to a UTF-8 file.`).option(`--mode <mode>`,`insert-children or replace.`,`insert-children`).option(`--id-prefix <prefix>`,`Stable namespace for generated node ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact write and review.`).option(`--output <path>`,`Write the review PNG to this path.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--scale <number>`,`Review pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--timeout-ms <integer>`,`Review render polling deadline.`,`120000`).addHelpText(`after`,`
|
|
6
6
|
Write one visual group at a time. Use flex, padding and gap; use targeted commands for later edits. Inspect the returned PNG.
|
|
7
|
-
`).action(async e=>{if(![`insert-children`,`replace`].includes(e.mode))throw new t(`BAD_REQUEST`,`--mode must be insert-children or replace.`,`Choose one of the two documented modes.`);
|
|
7
|
+
`).action(async e=>{if(![`insert-children`,`replace`].includes(e.mode))throw new t(`BAD_REQUEST`,`--mode must be insert-children or replace.`,`Choose one of the two documented modes.`);I(n,e.clientToken,!0);let r=e.mode===`replace`?`replace`:`insert-children`,i=k(e.canvas),a=F(e.baseVersion);i.nodeIds.length>0&&M(i,await R(n,i.canvasId,a),[e.targetNodeId]),n.output.result(await n.invocation.invoke({capability:B(n.catalog(),`canvas.writeHtml`),arguments:{canvasId:i.canvasId,targetNodeId:e.targetNodeId,mode:r,html:Zn(e.html),...e.idPrefix!==void 0&&{idPrefix:e.idPrefix},baseVersion:a,renderOutputPath:e.output??null,overwriteRender:e.force===!0,renderScale:P(it,e.scale,`--scale`),renderTimeoutMs:P(rt,e.timeoutMs,`--timeout-ms`)},clientToken:e.clientToken??null}))})},er=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),tr=(e,t)=>typeof t==`number`&&!Qn.has(e)?`${String(t)}px`:String(t),nr=e=>Object.entries(e).filter(([,e])=>e!==null).map(([e,t])=>{let n=er(e);return`${n}:${tr(n,t??``)}`}).join(`;`).replaceAll(`&`,`&`).replaceAll(`"`,`"`),rr=e=>e.length===0?0:Math.max(...e.map(e=>e.x+e.width))+80,ir=(e,n)=>{e.command(`create-artboard`).description(`Create a top-level frame.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--name <name>`,`Meaningful layer name.`).requiredOption(`--styles <json-or-@path>`,`CSSProperties with width and height.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact creation and review.`).option(`--output <path>`,`Review PNG path.`).option(`--force`,`Replace an existing review PNG.`,!1).action(async e=>{let r=H(e.styles,st,`--styles`);if(r.width===void 0||r.height===void 0)throw new t(`BAD_REQUEST`,`--styles must include width and height.`,`Use explicit whole-pixel dimensions such as 1440px and 900px.`);I(n,e.clientToken,!0);let i=A(e.canvas),a=F(e.baseVersion),o=await R(n,i,a),s=Object.entries(o.relationships).flatMap(([e,t])=>{let n=o.nodes[e]?.box;return n!==void 0&&t.parentId===`root`?[n]:[]}),c={display:`flex`,flexDirection:`column`,...r,left:rr(s),top:0,position:`absolute`},l=e.name.replaceAll(`&`,`&`).replaceAll(`"`,`"`);n.output.result(await he(n.remote,n.render).execute({canvasId:i,targetNodeId:`root`,mode:`insert-children`,html:`<div layer-name="${l}" data-enhance-kind="frame" style="${nr(c)}"></div>`,idPrefix:`artboard_${n.mutationKey.current(`canvas.render.importSource`,{canvasId:i})}`,baseVersion:a,renderClientToken:n.mutationKey.current(`canvas.render.create`,{purpose:`create-artboard-review`}),renderOutputPath:e.output??null,overwriteRender:e.force===!0,renderScale:1,renderTimeoutMs:12e4}))})},ar=(e,t)=>{$n(e,t),ir(e,t)},or=(e,t)=>{An(e,t),ar(e,t),sn(e,t),Yn(e,t),It(e,t)},sr=e=>{let n=e.getOptionValue(`canvas`),r=e.getOptionValue(`canvasId`);if(n!==void 0&&r!==void 0)throw new t(`BAD_REQUEST`,`--canvas and --canvas-id cannot be combined.`,`Pass the pasted URL or UUID through --canvas.`);let i=n??r;if(typeof i!=`string`)throw new t(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);return{reference:k(i),url:i}},cr=(e,n)=>{let r=e.getOptionValue(`nodeId`)??(n.nodeIds.length===1?n.nodeIds[0]:void 0);if(typeof r!=`string`||r===``)throw new t(`BAD_REQUEST`,`--node-id or a single-node selection link is required.`,`Choose one node, or use canvas tree to inspect the linked selection.`);return r},lr=async(e,t,n,r)=>{let i=f.parse(await t.remote.query(`canvas.document.get`,{canvasId:n.canvasId})),a=g.parse(i.document),o=j(n,a),s=Object.values(a.nodes).filter(e=>o.has(e.id)).map(e=>({...e,kind:e.component,parentId:a.relationships[e.id]?.parentId??null,children:Object.entries(a.relationships).filter(([,t])=>t.parentId===e.id).map(([e])=>e)})),c={canvasId:n.canvasId,version:i.version,source:`selection-link`,selectedNodeIds:n.nodeIds,next:[`Keep this selection link as --canvas for every edit: ${r}`,`Edit only these nodes or their descendants; other canvas content is outside the request.`]};if(e.name()===`node`){let t=cr(e,n);return M(n,a,[t]),{...c,node:s.find(e=>e.id===t)}}return{...c,nodes:s}},ur=(e,t)=>{for(let n of[`inspect`,`tree`,`node`,`selection`]){let r=e.commands.find(e=>e.name()===n),i=r?.options.find(e=>e.long===`--canvas-id`);r!==void 0&&i!==void 0&&(i.makeOptionMandatory(!1),r.options.find(e=>e.long===`--node-id`)?.makeOptionMandatory(!1),r.option(`--canvas <url-or-id>`,`Pasted canvas URL or UUID. Selection links limit reads and edits to the linked subtree.`),r.action(async()=>{let{reference:e,url:i}=sr(r),a=e.nodeIds.length>0?await lr(r,t,e,i):await t.remote.query(`canvas.${n}`,{canvasId:e.canvasId,...n===`node`&&{nodeId:cr(r,e)}});t.output.result(a)}))}},dr=b.coerce.number().int().positive(),fr=b.coerce.number().int().nonnegative(),pr=b.coerce.number().min(ne).max(4),Y=(e,n,r,i=`canvas render`)=>{let a=e.safeParse(n);if(!a.success)throw new t(`BAD_REQUEST`,`${r} is invalid.`,`Run 'enhance ${i} --help'.`);return a.data},mr=e=>{if(e===void 0)return null;try{let t=fe.safeParse(JSON.parse(e));if(t.success)return t.data}catch{}throw new t(`BAD_REQUEST`,`--bounds must be a finite positive world rectangle.`,`Pass JSON such as '{"x":0,"y":0,"width":800,"height":600}'.`)},hr=(e,t)=>e===void 0?t===null?{kind:`content`}:{kind:`bounds`,bounds:t}:{kind:`node`,nodeId:e},gr=e=>{if(!(typeof e!=`string`||!e.startsWith(`rec_`)))return b.uuid().safeParse(e.slice(4)).data},_r=(e,n)=>{let r=b.uuid().nullable().safeParse(n??null);if(!r.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact render.`);return e.mutationKey.select(r.data,!1),e.mutationKey.current(`canvas.render.create`,{})},vr=async(e,n)=>{let r=k(e.canvas??``);if(r.nodeIds.length===0)return e.nodeId;let i=e.nodeId??(r.nodeIds.length===1?r.nodeIds[0]:void 0);if(i===void 0||e.bounds!==void 0)throw new t(`BAD_REQUEST`,`A selection link requires one selected node to render.`,`Pass --node-id for one node in the selection; bounds and whole-canvas renders would include unrelated content.`);let a=f.parse(await n.remote.query(`canvas.document.get`,{canvasId:r.canvasId}));return M(r,g.parse(a.document),[i]),i},yr=async(e,n)=>{if(e.canvas===void 0)throw new t(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);if(e.nodeId!==void 0&&e.bounds!==void 0)throw new t(`BAD_REQUEST`,`--node-id and --bounds cannot be combined.`,`Choose one focused target, or omit both to render all authored content.`);let r=await vr(e,n);if(r===void 0&&e.atMs!==void 0)throw new t(`BAD_REQUEST`,`--at-ms requires --node-id.`,"Render the stable recording node returned by `enhance canvas tree`.");let i=e.atMs===void 0?null:gr(r);if(i===void 0&&e.atMs!==void 0)throw new t(`BAD_REQUEST`,`--at-ms requires a stable recording node id such as rec_<recording-uuid>.`,"Run `enhance canvas tree --canvas <url-or-id>` and choose a recording node.");_r(n,e.clientToken);let a=await n.invocation.invoke({capability:B(n.catalog(),`canvas.render`),arguments:{canvasId:k(e.canvas).canvasId,expectedVersion:e.expectedVersion===void 0?null:Y(dr,e.expectedVersion,`--expected-version`),target:hr(r,mr(e.bounds)),sourceState:i==null?null:{kind:`recording`,recordingId:i,atMs:Y(fr,e.atMs??``,`--at-ms`)},scale:Y(pr,e.scale,`--scale`),outputPath:e.output??null,overwrite:e.force===!0,timeoutMs:Y(dr,e.timeoutMs,`--timeout-ms`)},clientToken:e.clientToken??null});n.output.result(a)},br=(e,t)=>{e.option(`--canvas <url-or-id>`,`Canvas URL or UUID to render.`).option(`--node-id <id>`,`Render one stable canvas node instead of all authored content.`).option(`--bounds <json>`,`Render an explicit rectangle in canvas world coordinates.`).option(`--expected-version <integer>`,`Refuse pixels from any other document version.`).option(`--at-ms <integer>`,`Pause a recording node at this millisecond; inspect the PNG before snapshotting it.`).option(`--scale <number>`,`Output pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--output <path>`,`Write the PNG to this path instead of a protected temporary file.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--timeout-ms <integer>`,`Local polling deadline in milliseconds.`,`120000`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this render request.`).addHelpText(`after`,`
|
|
8
8
|
For transcript-led selection, inspect nearby --at-ms renders and reject transitions or duplicate states before running recording snapshot.
|
|
9
|
-
`).action(async e=>
|
|
10
|
-
`).filter(e=>e.trim()!==``).map(e=>JSON.parse(e)),n=t.map(e=>
|
|
9
|
+
`).action(async e=>yr(e,t))},xr=(e,t)=>{let n=e.commands.find(e=>e.name()===`canvas`);if(n===void 0)throw TypeError(`the API router did not supply canvas commands`);let r=n.commands.find(e=>e.name()===`render`);if(r===void 0)throw TypeError(`the API router did not supply canvas render`);let i=ge(t.remote,xe(t.configDirectory),t.now,t.output.result);kt(n,t),or(n,{...t,render:i}),ur(n,t),br(r,t)},Sr={"canvas.createEditableFrame":`Insert editable primitives beside a source screen.`,"canvas.create":`Create a canvas and return its id.`,"canvas.get":`Read one canvas and viewer access.`,"canvas.setAccess":`Change canvas link access.`,"canvas.markViewed":`Mark a canvas as viewed.`,"canvas.list":`Find canvases by shelf, title, access, or state.`,"canvas.rename":`Rename a canvas.`,"canvas.setReviewState":`Change your canvas review state.`,"canvas.delete":`Move a canvas to its recoverable bin.`,"canvas.move":`Move a canvas between shelves.`,"canvas.duplicate":`Copy a canvas into a shelf.`,"canvas.deletePermanently":`Permanently delete a binned canvas.`,"canvas.restore":`Restore a binned canvas.`,"canvas.inspect":`Summarize a canvas and suggest inspection commands.`,"canvas.tree":`List canvas node ids, hierarchy, kinds, and boxes.`,"canvas.node":`Read one canvas node and its children.`,"canvas.selection":`Read the person’s current live browser selection.`,"canvas realtime":`Canvas presence and activity.`,"canvas document":`Read or replace a canvas document.`,"canvas version":`Retained canvas history.`,"canvas render":`Create and inspect faithful canvas renders.`,"canvas participants":`List and change canvas participants.`,"canvas invites":`Invite people to a canvas.`},Cr=(e,t=!1)=>{let n=Symbol(`explicit-null`),r=e.parseArg;return r===void 0?()=>!1:(e.argParser((e,i)=>{if(t&&e===`null`)return n;try{return r(e,i)}catch(t){try{return r(JSON.stringify(e),i)}catch{throw t}}}),e=>e===n)},wr=()=>({exit:e=>{throw new m(e)}}),Tr={canvas:`Canvases: create, find, share, and manage review surfaces.`,"canvas render":`Render production-faithful canvas pixels after inspecting exact structure and geometry.`,"canvas version":`Inspect and name retained canvas history.`,"canvas document":`Read or replace the opaque document stored on a canvas.`,"canvas invites":`Invite people to a canvas and manage pending invitations.`,"canvas participants":`List and change the people who can reach a canvas.`,comment:`Comment threads and replies anchored to canvas content.`,organisation:`Teams the authenticated person belongs to or creates.`,"organisation invites":`Invite people to a team and manage pending invitations.`,"organisation people":`Team roster membership and roles.`,person:`The current person, sharing recipients, and agent tokens.`,"person recipients":`People available when choosing sharing recipients.`,recording:`Recorded walkthroughs, chunks, recovery, and completion.`,"recording-asset":`External page assets mirrored for durable replay.`,screen:`Captured pages uploaded for placement on a canvas.`},Er=new Set([`canvas.invites.accept`,`canvas.invites.preview`,`organisation.invites.accept`,`organisation.invites.preview`]),Dr=new Set([`canvas.create --organisation-id`,`canvas.create --source-url`,`recording.start --audio`,`recording.start --page-title`,`screen.create --page-title`,`screen.create --provenance`,`screen.create --route`]),Or=new Set([`comment.resolve --resolved`,`recording.start --page-title`,`recording.start --viewport`,`screen.create --page-title`,`screen.create --provenance`,`screen.create --route`,`screen.create --viewport`]),kr=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,X=e=>{let t=kr(Reflect.get(e,`__trpcCli`)),n=t===null?void 0:t.path;return typeof n==`string`?n:null},Ar=(e,t,n,r)=>{let i=t.long,a=X(e)??r.join(` `),o=a===``||i===void 0?void 0:_[`${a} ${i}`];if(o!==void 0)return o;if(i!==void 0&&_[i]!==void 0)return _[i];let s=(n.split(/Any of:|One of:/u,1)[0]?.trim()??``).split(`;`).map(e=>e.trim()).filter(e=>e!==``&&[`Format:`,`Pattern:`,`Min length:`,`Max length:`].every(t=>!e.startsWith(t))).join(`; `);return s===``?`Value for ${i??t.attributeName()} on ${e.name()}.`:s},jr=(e,n,r)=>{let i=wr();e.exitOverride(e=>i.exit(e.exitCode)),e.configureOutput({writeOut:e=>n.output.logger.info?.(e),writeErr:e=>n.output.logger.error?.(e)}),e.showHelpAfterError(!1).showSuggestionAfterError(!1);let a=[],o=[];for(let t of e.options){let n=X(e)??r.join(` `);Or.has(`${n} ${t.long??``}`)&&o.push({flag:t.long??``,name:t.attributeName()});let i=Dr.has(`${n} ${t.long??``}`),s=Cr(t,i);i&&a.push({name:t.attributeName(),matches:s}),t.description=Ar(e,t,t.description,r)}a.length>0&&e.hook(`preAction`,e=>{for(let t of a)t.matches(e.getOptionValue(t.name))&&e.setOptionValueWithSource(t.name,null,`cli`)}),o.length>0&&e.hook(`preAction`,e=>{if(e.getOptionValueSource(`json`)===`cli`)return;let n=o.find(({name:t})=>e.getOptionValueSource(t)!==`cli`);if(n!==void 0)throw new t(`BAD_REQUEST`,`${n.flag} is required unless --json supplies the complete input.`,`Pass ${n.flag} explicitly, including false or null when that is the intended value.`)})},Mr=(e,n,r,i)=>{(r!==null&&i.mutationPaths.has(r)||n[0]===`fixture`)&&(e.options.every(e=>e.long!==`--client-token`)&&e.option(`--client-token <uuid>`,_[`--client-token`]),e.hook(`preAction`,e=>{let r=e.getOptionValue(`clientToken`),a=b.uuid().nullable().safeParse(r??null);if(!a.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact command.`);i.mutationKey.select(a.data,n[0]===`fixture`)}))},Nr=(e,t,n)=>{n===null||!Er.has(n)||(e.options.find(e=>e.long===`--token`)?.makeOptionMandatory(!1),e.hook(`preAction`,async e=>{let n=e.getOptionValue(`token`);if(n===void 0&&e.getOptionValue(`json`)!==void 0)return;let r=await et(typeof n==`string`?n:void 0,`enhance ${t.join(` `)}`);e.setOptionValueWithSource(`token`,r,`cli`)}))},Pr=(e,t,n,r)=>{let i=Tr[t.join(` `)];i===void 0?n!==null&&e.description(oe[n]??r.get(n)??`Run the ${n} API operation.`):e.description(i);let a=Sr[t.join(` `)]??(n===null?void 0:Sr[n]);a!==void 0&&e.summary(a)},Fr=(e,t,n=[])=>{jr(e,t,n);for(let r of e.commands){let e=[...n,r.name()],i=X(r);Mr(r,e,i,t),Pr(r,e,i,t.descriptions),Nr(r,e,i),Fr(r,t,e)}},Ir=te().excludedProcedures,Lr=new Set([`canvas thumbnail`,`telemetry`]),Rr=e=>{let t=Reflect.get(e,`__trpcCli`);if(typeof t!=`object`||!t)return null;let n=Reflect.get(t,`path`);return typeof n==`string`?n:null},zr=(e,t=[])=>{let n=e.commands.filter(e=>{let n=Rr(e),r=[...t,e.name()].join(` `);return!Lr.has(r)&&(n===null||!Ir.has(n))});Reflect.set(e,`commands`,n);for(let e of n)zr(e,[...t,e.name()])},Br=e=>{let t=Reflect.get(e,`__trpcCli`);if(typeof t!=`object`||!t)return null;let n=Reflect.get(t,`path`);return typeof n==`string`?n:null},Vr=(e,t=[])=>e.commands.filter(e=>e.name()!==`help`).flatMap(e=>{let n=[...t,e.name()],r=Br(e);return[{path:n.join(` `),procedure:r,description:e.description(),kind:r===null?e.commands.length>0?`namespace`:`utility`:`derived`,helpCharacters:e.helpInformation().length},...Vr(e,n)]}),Hr=(e,t,n)=>{e.command(`commands`).description(`Emit the command inventory as NDJSON without walking the help tree.`).option(`--namespace <path>`,`Keep commands at or below this space-separated path.`).option(`--capabilities`,`Emit the transport-neutral capability inventory.`,!1).option(`--reference`,`Emit complete shared capability contracts for documentation.`,!1).action(r=>{if(r.reference){let e=se(n()),r=le(e);t.result({items:e.map(e=>r.describe(e.id)),truncated:!1});return}if(r.capabilities){t.result({items:we(n()),truncated:!1});return}let i=r.namespace?.trim(),a=Vr(e).filter(e=>i===void 0||e.path===i||e.path.startsWith(`${i} `));t.result({items:a,truncated:!1})})},Ur=(e,t,n,r)=>{let i=e.commands.find(e=>e.name()===`comment`);if(i===void 0)throw TypeError(`derived comment namespace is missing`);i.command(`attention`).description(`List every open comment needing attention; source metadata is included when a capture has it.`).argument(`<canvas-url-or-id>`,`A pasted Enhance canvas URL shaped /c/<UUID>, or a bare canvas UUID.`).action(async e=>{r.result(await t.invoke({capability:B(n(),`comment.attention`),arguments:{canvasId:A(e)},clientToken:null}))})},Wr=(e,t)=>{let{version:n,credentials:r,remote:i,output:a}=t;e.command(`doctor`).description(`Check the installed binary, API reachability, and credential file without changes.`).action(async()=>{let[e,t]=await Promise.all([i.health(),r.read()]);a.result({status:t!==null&&e.reachable?`ok`:`degraded`,binary:x.argv[1]??`enhance`,version:n,api:e,credential:{path:r.path,present:t!==null}})})},Gr=e=>b.coerce.number().int().positive().parse(e),Kr=b.record(b.string(),b.unknown()),qr=(e,t)=>{let n=Kr.safeParse(e);if(!n.success)return 0;let r=n.data.atMs;if(typeof r==`number`&&Number.isFinite(r))return Math.max(0,Math.round(r));let i=n.data.timestamp;return typeof i==`number`&&Number.isFinite(i)?Math.max(0,Math.round(i-t)):0},Jr=async e=>{let t=(await Be(e,`utf8`)).split(`
|
|
10
|
+
`).filter(e=>e.trim()!==``).map(e=>JSON.parse(e)),n=t.map(e=>Kr.safeParse(e).data?.timestamp).find(e=>typeof e==`number`&&Number.isFinite(e));return t.map(e=>({atMs:qr(e,n??0),event:e}))},Yr=async e=>({clientToken:e.clientToken??w(),body:await Be(e.file),route:e.route??null,pageTitle:e.pageTitle??C.basename(e.file),viewport:{width:e.width,height:e.height},provenance:null}),Z=e=>e.option(`--width <pixels>`,`Captured viewport width.`,Gr,1440).option(`--height <pixels>`,`Captured viewport height.`,Gr,900),Xr=(e,t,n)=>{Z(e.command(`screen`).description(`Upload one captured page and return its reusable screen id.`).requiredOption(`--file <path>`,`File containing the captured HTML bytes.`).option(`--client-token <uuid>`,`Stable UUID to reuse when retrying the same upload.`).option(`--route <url>`,`Original browser route, when it is safe to retain.`).option(`--page-title <title>`,`Captured page title.`)).action(async e=>{n.result(await t(await Yr(e)))})},Zr=(e,t,n)=>{Z(e.command(`recording`).description(`Upload NDJSON rrweb events as a walkthrough; chunk offsets start at the first event.`).requiredOption(`--file <path>`,'NDJSON with one rrweb event per line; minimum example: `{"type":2,"timestamp":1000}`.').requiredOption(`--source-url <url>`,`Required route the recording represents.`).option(`--page-title <title>`,`Title for a newly created walkthrough canvas.`).option(`--canvas-id <uuid>`,`Existing canvas to receive the walkthrough.`)).action(async e=>{n.result(await t({entries:await Jr(e.file),sourceUrl:e.sourceUrl,pageTitle:e.pageTitle??null,viewport:{width:e.width,height:e.height},...e.canvasId!==void 0&&{canvasId:e.canvasId}}))})},Qr=(e,t,n)=>{Z(e.command(`world`).description(`Create a team, a canvas, and zero or more attached screen fixtures.`).requiredOption(`--organisation-name <name>`,`Name of the team to create.`).requiredOption(`--canvas-title <title>`,`Title of the canvas to create.`).option(`--screen <path...>`,`Captured HTML files to upload and attach.`)).action(async e=>{let r=[],i=e.screen??[];for(let t of i)r.push(await Yr({file:t,width:e.width,height:e.height}));n.result(await t({organisationName:e.organisationName,canvasTitle:e.canvasTitle,screens:r}))})},$r=(e,t,n)=>{let r=e.command(`fixture`).description(`Build deterministic product fixtures.`);Xr(r,t.screen,n),Zr(r,t.recording,n),Qr(r,t.world,n)},ei=e=>b.coerce.number().parse(e),ti=e=>b.coerce.number().positive().parse(e),ni=e=>b.coerce.number().int().positive().parse(e),ri=(e,t,n,r)=>{(e.commands.find(e=>e.name()===`prototype`)??e.command(`prototype`).description(`Publish static frontend prototypes.`)).command(`publish`).description(`Package and publish an unpacked static build directory. The CLI creates the upload artifact.`).requiredOption(`--canvas-id <uuid>`,`Canvas that receives the prototype.`).requiredOption(`--directory <path>`,`Unpacked static build directory; do not pass a ZIP file.`).requiredOption(`--title <title>`,`Label above the prototype frame.`).requiredOption(`--base-version <number>`,`Current canvas document version.`,ni).option(`--prototype-id <uuid>`,`Existing prototype identity to publish a new deployment.`).option(`--client-token <uuid>`,`Stable retry token for this exact build.`).option(`--node-id <id>`,`Stable canvas node id for a new prototype.`).option(`--entry <path>`,`HTML entry relative to the uploaded directory.`,`index.html`).option(`--x <pixels>`,`Canvas x coordinate.`,ei,48).option(`--y <pixels>`,`Canvas y coordinate.`,ei,48).option(`--width <pixels>`,`Prototype viewport width.`,ti,1440).option(`--height <pixels>`,`Prototype viewport height.`,ti,900).action(async e=>{let i=e.clientToken??w();r.result(await t.invoke({capability:B(n(),`prototype.publish`),arguments:{canvasId:e.canvasId,prototypeId:e.prototypeId??null,nodeId:e.nodeId??`proto_${i.replaceAll(`-`,``)}`,title:e.title,directory:e.directory,entryPath:e.entry,baseVersion:e.baseVersion,box:{x:e.x,y:e.y,width:e.width,height:e.height}},clientToken:i}))})},ii=(e,n,r)=>{let i=(r?b.coerce.number().int().positive():b.coerce.number().int().nonnegative()).safeParse(e);if(!i.success)throw new t(`BAD_REQUEST`,`${n} is invalid.`,`Run 'enhance recording snapshot --help'.`);return i.data},ai=(e,n)=>{let r=e.commands.find(e=>e.name()===`recording`);if(r===void 0)throw TypeError(`the API router did not supply recording commands`);r.command(`snapshot`).description(`Persist one visually accepted recording moment as an ordinary screen and frame.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID containing the recording.`).requiredOption(`--recording-id <uuid>`,`Recording UUID returned by recording list.`).requiredOption(`--at-ms <integer>`,`Accepted recording timestamp in milliseconds.`).option(`--timeout-ms <integer>`,`Local polling deadline in milliseconds.`,`120000`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this exact snapshot.`).addHelpText(`after`,`
|
|
11
11
|
Preview first: canvas render --node-id rec_<recording-uuid> --at-ms <integer>, then inspect its PNG. This command persists the accepted moment.
|
|
12
|
-
`).action(async e=>{let r=
|
|
13
|
-
`)}\n`;if(!(t.length>25e3||e.some(e=>e.length>2e3))){
|
|
14
|
-
`)}\n`;
|
|
12
|
+
`).action(async e=>{let r=b.uuid().nullable().safeParse(e.clientToken??null),i=b.uuid().safeParse(e.recordingId);if(!r.success||!i.success)throw new t(`BAD_REQUEST`,`The recording id or client token is not a UUID.`,"Use the recording id from `recording list`; mint one client token per accepted moment.");n.output.result(await n.invocation.invoke({capability:B(n.catalog(),`recording.snapshot`),arguments:{canvasId:A(e.canvas),recordingId:i.data,atMs:ii(e.atMs,`--at-ms`,!1),timeoutMs:ii(e.timeoutMs,`--timeout-ms`,!0)},clientToken:r.data}))})},oi=(e,n,r)=>{if(e!==`canvas.document.save`||typeof r!=`object`||!r||!(`outcome`in r)||r.outcome!==`conflict`)return r;throw new t(`CONFLICT`,`The canvas document changed before this save landed.`,`Run 'enhance canvas document get --canvas-id ${typeof n==`object`&&n&&`canvasId`in n&&typeof n.canvasId==`string`?n.canvasId:`<canvas-id>`}', merge your change into that document, then retry with its version.`)},si=(e,t)=>Ve(e,e=>({[e]:{query:async n=>t.query(e,n),mutate:async n=>oi(e,n,await t.mutate(e,n))}})),ci=(e,n)=>{let r=e.commands.find(e=>e.name()===`transcript`);if(r===void 0)throw TypeError(`the API router did not supply transcript commands`);r.command(`get`).description(`Read timestamped speech cues as candidate moments; render and inspect candidate PNGs before snapshotting.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID containing the recording.`).requiredOption(`--recording-id <uuid>`,`Recording UUID returned by recording list.`).action(async e=>{let r=b.uuid().safeParse(e.recordingId);if(!r.success)throw new t(`BAD_REQUEST`,`--recording-id must be a UUID.`,"Use the recording id returned by `enhance recording list`.");n.output.result(await n.invocation.invoke({capability:B(n.catalog(),`transcript.read`),arguments:{canvasId:A(e.canvas),recordingId:r.data},clientToken:null}))})},li={jsonInput:`auto`,prompts:!1,logger:`ndjson`,errorMapping:`stable-exit-codes`},ui=e=>{let t=e.state;return{logger:e.output.logger,prompts:li.prompts,process:wr(),formatError:e=>{let n=re(e,t.pendingParserMessage);return t.exitCode=ce(n,!1,e),t.pendingParserMessage=null,JSON.stringify(n)}}},di=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,fi=e=>{let t=di(e),n=t===null?void 0:t.description;return typeof n==`string`&&n!==``?n:null},pi=e=>{let t=De({router:e});return{descriptions:new Map(t.flatMap(([e,t])=>{let n=fi(t.meta);return n===null?[]:[[e,n]]})),mutationPaths:new Set(t.flatMap(([e,t])=>t.type===`mutation`?[e]:[]))}},mi=()=>{let e=null;return()=>(e??=ae(),e)},hi=(e,t,n)=>{let r=Qe(t.remote),i=ye({remote:t.remote,mutationKey:t.mutationKey,configDirectory:t.configDirectory,now:()=>new Date,progress:t.output.result});nt(e,_e(t.credentials,t.remote,me(t.remote)),t.output),Ur(e,i,n,t.output),Wr(e,{version:t.version,credentials:t.credentials,remote:t.remote,output:t.output}),$r(e,{screen:r,recording:Xe(t.remote),world:$e(t.remote,r)},t.output),Hr(e,t.output,n),xr(e,{remote:t.remote,mutationKey:t.mutationKey,invocation:i,catalog:n,output:t.output,configDirectory:t.configDirectory,now:()=>new Date}),ai(e,{invocation:i,catalog:n,output:t.output}),ri(e,i,n,t.output),ci(e,{invocation:i,catalog:n,output:t.output})},gi=e=>{let t=pe(),n=mi(),{descriptions:r,mutationPaths:i}=pi(t),a=Ee({router:si(t,e.remote),name:e.commandName,version:e.version,description:`Operate Enhance as the authenticated person.`,jsonInput:li.jsonInput}),o=ui(e),s=a.buildProgram(o);if(!(s instanceof Te))throw TypeError(`trpc-cli did not return a Commander program`);zr(s),hi(s,e,n),Fr(s,{descriptions:r,mutationPaths:i,mutationKey:e.mutationKey,output:e.output}),s.description(`Operate Enhance as the authenticated person.`);let c=e.state;return{program:s,run:async()=>{try{await a.run(o,s)}catch(t){if(!(t instanceof m))throw t;if(t.requestedCode!==0&&c.pendingParserMessage!==null){let n=re(t,c.pendingParserMessage);c.exitCode=ce(n,!0),c.pendingParserMessage=null,e.output.failure(n)}throw t}}}},_i=e=>x.exit(e),vi=36e5,Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e),yi=e=>{if(Array.isArray(e))return e.map(e=>JSON.stringify(e));if(!Q(e)||!Array.isArray(e.items))return[JSON.stringify(e)];let t=e.items;if(t.length===0)return[JSON.stringify(e)];let n=e.truncated===!0;return t.map(e=>JSON.stringify(Q(e)?{...e,truncated:n}:{value:e,truncated:n}))},bi=e=>{let t=`${e.join(`
|
|
13
|
+
`)}\n`;if(!(t.length>25e3||e.some(e=>e.length>2e3))){x.stdout.write(t);return}let n=ze(`sha256`).update(t).digest(`hex`).slice(0,16),r=C.join(ke(),`enhance-${n}.ndjson`);S(r,t,{mode:384}),x.stdout.write(`${JSON.stringify({path:r,characters:t.length,records:e.length})}\n`)},xi=e=>{try{let t=new URL(e),n=new Set;for(let e of t.searchParams.keys())n.add(e.toLowerCase());return n.has(`x-amz-signature`)||n.has(`x-amz-credential`)||n.has(`x-amz-algorithm`)}catch{return!1}},$=e=>typeof e==`string`?xi(e):Array.isArray(e)?e.some(e=>$(e)):Q(e)?Object.values(e).some(e=>$(e)):!1,Si=e=>{Pe(e,{recursive:!0,mode:448}),je(e,448)},Ci=e=>{if(!Me(e))return;let t=Date.now()-vi,n=Ie(e,{withFileTypes:!0});for(let r of n){if(!r.isFile()||!r.name.startsWith(`result-`))continue;let n=C.join(e,r.name);Ne(n).mtimeMs<t&&Re(n)}},wi=e=>({...e,sensitive:!0,cleanup:`unlink-after-use`,deleteAfter:new Date(Date.now()+vi).toISOString()}),Ti=(e,t)=>{let n=yi(e),r=`${n.join(`
|
|
14
|
+
`)}\n`;Si(t);let i=C.join(t,`result-${w()}.ndjson`);S(i,r,{mode:384,flag:`wx`}),x.stdout.write(`${JSON.stringify(wi({path:i,characters:r.length,records:n.length,reason:`signed-url`}))}\n`)},Ei=e=>Q(e)?typeof e.token==`string`?{field:`token`,value:e.token}:typeof e.acceptToken==`string`?{field:`acceptToken`,value:e.acceptToken}:null:null,Di=(e,t,n)=>{let r=`${t.value}\n`;Si(n);let i=C.join(n,`result-${w()}.token`);S(i,r,{mode:384,flag:`wx`});let a=Object.fromEntries(Object.entries(e).filter(([e])=>e!==t.field));x.stdout.write(`${JSON.stringify({...a,secret:wi({path:i,field:t.field,characters:r.length})})}\n`)},Oi=e=>e.includes(`Usage:`)||e.includes(`Options:`)||e.includes(`Commands:`),ki=l.omit({fields:!0}).extend({remediation:b.string(),fields:b.array(b.object({path:b.string(),message:b.string()})).optional()}),Ai=e=>{try{let t=JSON.parse(e),n=ki.safeParse(t);return n.success?{code:n.data.code,message:n.data.message,remediation:n.data.remediation,...n.data.fields!==void 0&&{fields:n.data.fields}}:null}catch{return null}},ji=(e,t)=>{if(typeof e==`string`&&Oi(e)){x.stdout.write(e);return}let n=Ei(e);if(n!==null&&Q(e)){Di(e,n,t);return}if($(e)){Ti(e,t);return}bi(yi(e))},Mi=e=>{x.stderr.write(`${JSON.stringify(e)}\n`)},Ni=(e,t,n=`enhance`)=>{let r=e,i=C.join(t,`sensitive`);return Ci(i),{result:e=>{ji(h(e,n),i)},failure:e=>{Mi(de(e,n))},logger:{info:(...e)=>{ji(h(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(h(e.map(String).join(``),n)),i=Ai(t);i===null?r.pendingParserMessage=t:Mi(i)}}}};(async()=>{let e={exitCode:1,pendingParserMessage:null},t=Ni(e,v.configDirectory,v.commandName),n=be(v.configDirectory),r=Se(),i=gi({version:`0.1.7-dev.sha-3345ac7ecaec`,credentials:n,remote:ve(v.apiUrl,n,r),mutationKey:r,output:t,state:e,configDirectory:v.configDirectory,commandName:v.commandName});try{await i.run()}catch(n){n instanceof m&&_i(n.requestedCode===0?0:e.exitCode),t.failure(re(n,null)),_i(1)}})();export{};
|
package/dist/mcp-main.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{f as e,l as t}from"./cli-output-identity.lib-
|
|
2
|
+
import{f as e,l as t}from"./cli-output-identity.lib-C3dhDJfG.mjs";import{a as n,f as r,i,n as a,o,r as s,t as c}from"./mutation-key.adapter-HiEQIg6a.mjs";import{t as l}from"./mcp-server.adapter-BVeDABQv.mjs";import{z as u}from"zod";import d from"node:process";import{serveStdio as f}from"@modelcontextprotocol/server/stdio";const p=new Set([`auth.login`,`auth.logout`,`auth.status`,`doctor`]),m=u.object({openBrowser:u.boolean()}),h=async e=>{let t=r(e.credentials,e.remote,n(e.remote));switch(e.capability){case`auth.login`:{let n=m.parse(e.arguments);return t.loginWithBrowser({label:`Agent plugin`,openBrowser:n.openBrowser,onReady:()=>null})}case`auth.logout`:return t.logout();case`auth.status`:return await e.credentials.read()===null?{authenticated:!1}:t.status();case`doctor`:{let[t,n]=await Promise.all([e.remote.health(),e.credentials.read()]);return{status:n!==null&&t.reachable?`ok`:`degraded`,runtimeVersion:e.version,api:{reachable:t.reachable,status:t.status,...t.error!==void 0&&{error:t.error}},credential:{present:n!==null}}}default:throw TypeError(`${e.capability} has no MCP transport execution`)}},g=(e,t,n,r)=>{let i=a(e,t,c());return{invoke:async s=>{if(p.has(s.capability.id))return h({capability:s.capability.id,arguments:s.arguments,credentials:t,remote:i,version:r});let l=c();return o({remote:a(e,t,l),mutationKey:l,configDirectory:n}).invoke(s)}}},_=u.object({authenticated:u.literal(!1)}),v=u.object({authenticated:u.literal(!0),personId:u.uuid(),displayName:u.string().min(1),tokenId:u.uuid(),tokenLabel:u.string().min(1),expiresAt:u.iso.datetime().nullable()}),y=u.object({openBrowser:u.boolean().default(!0).describe(`Open the system browser for the human sign-in and wait for completion.`)}),b=u.strictObject({}),x=u.union([_,v]),S=u.object({loggedOut:u.boolean()}),C=u.object({status:u.enum([`ok`,`degraded`]),runtimeVersion:u.string().min(1),api:u.object({reachable:u.boolean(),status:u.number().int().nullable(),error:u.string().optional()}),credential:u.object({present:u.boolean()})}),w=e=>({summary:e.summary,useWhen:e.useWhen,preconditions:[`Run through the local Enhance MCP runtime, which owns the user-scoped credential.`,`Keep credential values outside model-visible input and output.`],input:[],output:[],result:e.result,recovery:[`BAD_REQUEST: correct the named option and call again.`,`UNAUTHORIZED: start browser sign-in and let the person complete consent.`,`FORBIDDEN: leave the credential unchanged and report the governing account policy.`,`INTERNAL: call doctor, report the failing boundary, and stop repeating the call.`],next:e.next,examples:[{input:e.exampleInput,output:e.exampleOutput}]}),T=t=>e({...t,source:`composite`,idempotency:t.operation===`query`?`none`:`single`,execution:{kind:`composite`,procedures:[]},meta:{description:t.guide.summary},policy:{exposure:`mcp-transport`,reason:`The local MCP runtime owns its own authentication and installation diagnostics.`,owner:`mcp`},cliPath:null,inputExample:t.guide.examples[0]?.input,outputExample:t.guide.examples[0]?.output}),E=[T({id:`auth.login`,operation:`mutation`,effect:`external`,inputSchema:y,outputSchema:v,guide:w({summary:`Open browser sign-in and store a revocable user-scoped Enhance credential.`,useWhen:`Use when Enhance is not authenticated or its credential was revoked.`,result:`Waits for browser consent, stores the credential locally, and returns safe identity metadata.`,next:[`Call auth.status, then read the target canvas.`],exampleInput:{openBrowser:!0},exampleOutput:{authenticated:!0,personId:`00000000-0000-4000-8000-000000000001`,displayName:`Ada`,tokenId:`00000000-0000-4000-8000-000000000002`,tokenLabel:`Agent plugin`,expiresAt:null}})}),T({id:`auth.logout`,operation:`mutation`,effect:`delete`,inputSchema:b,outputSchema:S,guide:w({summary:`Remove the user-scoped local Enhance credential.`,useWhen:`Use only when the person asks to disconnect this local agent host.`,result:`Reports whether a local credential was removed without returning its value.`,next:[`Call auth.status to confirm the local runtime is disconnected.`],exampleInput:{},exampleOutput:{loggedOut:!0}})}),T({id:`auth.status`,operation:`query`,effect:`read`,inputSchema:b,outputSchema:x,guide:w({summary:`Check whether the local Enhance MCP runtime is authenticated.`,useWhen:`Use before a workflow or after login, logout, expiry, or an authorization failure.`,result:`Returns safe identity metadata or authenticated false, never a credential value.`,next:[`When unauthenticated, call auth.login; otherwise continue with the requested workflow.`],exampleInput:{},exampleOutput:{authenticated:!1}})}),T({id:`doctor`,operation:`query`,effect:`read`,inputSchema:b,outputSchema:C,guide:w({summary:`Check MCP runtime identity, API reachability, and credential presence without changes.`,useWhen:`Use after repeated connection, authentication, or compatibility failure.`,result:`Returns bounded diagnostics without machine paths, credentials, or customer data.`,next:[`Follow the failing boundary; do not repeat a mutation while diagnostics are degraded.`],exampleInput:{},exampleOutput:{status:`ok`,runtimeVersion:`0.1.7`,api:{reachable:!0,status:200},credential:{present:!0}}})})].toSorted((e,t)=>e.id.localeCompare(t.id)),D=()=>E,O=s(i.configDirectory),k=g(i.apiUrl,O,i.configDirectory,`0.1.7-dev.sha-3345ac7ecaec`),A=[...t(),...D()];f(()=>l({version:`0.1.7-dev.sha-3345ac7ecaec`,name:i.mcpServiceName,commandName:i.commandName,invocation:k,catalog:A,exposures:[`shared`,`mcp-transport`]}),{legacy:`serve`,onerror:()=>d.stderr.write(`${i.mcpServiceName} transport failure\n`)});export{};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{C as e,a as t,i as n,l as r,n as i,s as a,t as o}from"./cli-output-identity.lib-C3dhDJfG.mjs";import{z as s}from"zod";import{createHash as c,randomUUID as l}from"node:crypto";import{readFile as u,rm as d}from"node:fs/promises";import{McpServer as f}from"@modelcontextprotocol/server";const p=e=>e.replaceAll(/\s+/gu,` `).trim(),m=e=>{let t=`${e.id} [${e.effect}] — `,n=p(e.guide.summary),r=180-t.length;return`${t}${n.slice(0,r)}`},h=(e,t)=>{let n=e.toSorted((e,t)=>e.id.localeCompare(t.id)).map(e=>m(e)),r=c(`sha256`).update(n.join(`
|
|
3
|
+
`)).digest(`hex`),i=[`Enhance MCP ${t} — ${String(n.length)} capabilities — sha256:${r}`,...n].join(`
|
|
4
|
+
`);if(Buffer.byteLength(i)>24576)throw RangeError(`the complete capability catalogue exceeds 24 KiB`);return{digest:r,text:i}},g=(e,t,n=`enhance`)=>{let r=h(e,t),a=String(i(r.text,n));return{register:t=>{t.registerTool(`capability_catalogue`,{title:`Scan every Enhance capability`,description:`Return the complete bounded capability inventory when the task is broad, uncertain, or capability_search does not find the right words. Call capability_describe with one exact id before invoking it.`,inputSchema:s.strictObject({}),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":e.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":e.length}},()=>({content:[{type:`text`,text:a}]}))}}},_=s.object({ok:s.literal(!1),error:s.object({code:s.string(),message:s.string(),remediation:s.string(),fields:s.array(s.object({path:s.string(),message:s.string()})).optional()})}),v=s.object({ok:s.literal(!0),artifact:s.object({uri:s.string(),mimeType:s.string(),bytes:s.number().int().nonnegative()})}),y=s.object({id:s.string(),operation:s.enum([`query`,`mutation`]),effect:s.enum([`read`,`write`,`delete`,`external`]),idempotency:s.enum([`none`,`single`,`composite`]),summary:s.string(),useWhen:s.string(),preconditions:s.array(s.string()),inputSchema:s.unknown(),exampleInput:s.unknown(),output:s.array(s.object({name:s.string(),required:s.boolean(),meaning:s.string()})),result:s.string(),recovery:s.array(s.string()),next:s.array(s.string()),schemaDigest:s.string(),guidanceDigest:s.string(),behaviorDigest:s.string()}),b=y.pick({id:!0,operation:!0,effect:!0,summary:!0,useWhen:!0}),x=s.union([s.object({ok:s.literal(!0),result:s.unknown()}),v,_]),S=s.union([s.object({ok:s.literal(!0),result:s.object({matches:s.array(b),totalMatches:s.number().int().nonnegative(),truncated:s.boolean()})}),_]),C=s.union([s.object({ok:s.literal(!0),result:y}),_]),w=s.object({capability:s.string().min(1).describe(`Exact capability id returned by capability_search or capability_catalogue.`)}),T=(t,n)=>({register:r=>{r.registerTool(`capability_describe`,{title:`Load one Enhance capability contract`,description:`Load the exact input schema, example, preconditions, result guidance, recovery, and next steps for one id returned by capability_search or capability_catalogue.`,inputSchema:w,outputSchema:C,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},({capability:r})=>{let i=t.describe(r);return i===null?n.failure(new e(`BAD_REQUEST`,`Unknown shared capability: ${r}.`,`Call capability_search or capability_catalogue and use an exact id from its results.`,{capability:`No shared capability has this id.`})):n.inline(i)})}}),E=/(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu,D=/[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu,O=e=>JSON.stringify(e),k=(e,t=``)=>typeof e==`string`?D.test(e)||E.test(t)&&!t.endsWith(`Id`):Array.isArray(e)?e.some(e=>k(e,t)):typeof e!=`object`||!e?!1:Reflect.get(e,`sensitive`)===!0||Object.entries(e).some(([e,t])=>k(t,e)),A=async(e,t,n)=>{if(typeof t!=`object`||!t)return null;let r=Reflect.get(t,`path`);if(typeof r!=`string`)return null;let i=Reflect.get(t,`contentType`);if(typeof i!=`string`||!i.startsWith(`image/`)||Reflect.get(t,`sensitive`)!==!0)return null;let a=await u(r),o=l(),s=`enhance://artifact/${o}`;if(n===`embedded`){await d(r,{force:!0});let e={ok:!0,artifact:{uri:s,mimeType:i,bytes:a.byteLength}};return{content:[{type:`text`,text:O(e)},{type:`image`,data:a.toString(`base64`),mimeType:i}],structuredContent:e}}e.registerResource(`artifact-${o}`,s,{title:`Enhance artifact`,mimeType:i},e=>({contents:[{uri:e.href,mimeType:i,blob:a.toString(`base64`)}]}));let c={ok:!0,artifact:{uri:s,mimeType:i,bytes:a.byteLength}};return{content:[{type:`text`,text:O(c)},{type:`resource_link`,name:`Enhance artifact`,uri:s,mimeType:i}],structuredContent:c}},j=(e,t,n)=>{let r=l(),i=`enhance://result/${r}`,a=Buffer.byteLength(t);if(n===`embedded`){let e={ok:!0,artifact:{uri:i,mimeType:`application/json`,bytes:a}};return{content:[{type:`text`,text:O(e)},{type:`resource`,resource:{uri:i,mimeType:`application/json`,text:t}}],structuredContent:e}}e.registerResource(`result-${r}`,i,{title:`Protected Enhance result`,mimeType:`application/json`},e=>({contents:[{uri:e.href,mimeType:`application/json`,text:t}]}));let o={ok:!0,artifact:{uri:i,mimeType:`application/json`,bytes:a}};return{content:[{type:`text`,text:O(o)},{type:`resource_link`,name:`Protected Enhance result`,uri:i,mimeType:`application/json`}],structuredContent:o}},M=t=>new e(`BAD_REQUEST`,`Input validation error.`,`Call capability_search again and rewrite every rejected input field.`,Object.fromEntries(t.issues.map(e=>[e.path.length===0?`input`:e.path.join(`.`),e.message]))),N=(e,t=`enhance`)=>({success:async(e,n,r)=>{let a=i(n,t),o=await A(e,a,r);if(o!==null)return o;let s=O(a);if(Buffer.byteLength(s)>2e4||k(a))return j(e,s,r);let c={ok:!0,result:a};return{content:[{type:`text`,text:O(c)}],structuredContent:c}},inline:e=>{let n={ok:!0,result:i(e,t)};return{content:[{type:`text`,text:O(n)}],structuredContent:n}},failure:r=>{let i=o(n(r instanceof s.ZodError?M(r):r,null),t),a={ok:!1,error:i.code===`UNAUTHORIZED`?{...i,remediation:e}:i};return{content:[{type:`text`,text:O(a)}],structuredContent:a,isError:!0}}}),P=s.object({query:s.string().trim().min(1).max(200).describe(`Plain-language task, domain, or exact capability id to discover.`),operation:s.enum([`any`,`query`,`mutation`]).default(`any`).describe(`Limit matches to reads or mutations when the intended effect is known.`),limit:s.number().int().min(1).max(10).default(5).describe(`Maximum contracts to return.`)}),F=s.object({capability:s.string().min(1).describe(`Exact query id returned by capability_describe.`),input:s.record(s.string(),s.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`)}),I=s.object({capability:s.string().min(1).describe(`Exact mutation id returned by capability_describe.`),input:s.record(s.string(),s.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`),clientToken:s.uuid().optional().describe(`Stable UUID reused only when retrying this exact mutation input.`)}),L=(t,n,r)=>{let i=t.find(e=>e.id===n);if(i===void 0)throw new e(`BAD_REQUEST`,`Unknown shared capability: ${n}.`,`Call capability_search or capability_catalogue and use an exact id from its results.`,{capability:`No shared capability has this id.`});if(i.operation!==r){let t=i.operation===`query`?`capability_query`:`capability_mutate`;throw new e(`BAD_REQUEST`,`${n} is a ${i.operation}, not a ${r}.`,`Call ${t} with the same capability and input.`,{capability:`Use ${t} for this capability.`})}return i},R=(e,t,n,r)=>{e.registerTool(`capability_search`,{title:`Discover Enhance capabilities`,description:`Search the Enhance capability catalogue for a specific likely action. Returns only the most relevant summaries; use capability_catalogue when the request is broad or the matches look wrong, then call capability_describe before invoking.`,inputSchema:P,outputSchema:S,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":t.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":t.length}},async({query:e,operation:t,limit:i})=>r.inline(n.search({query:e,operation:t,limit:i})))},z=(e,t,n,r)=>{e.registerTool(`capability_query`,{title:`Run a discovered Enhance query`,description:`Run one read-only capability using the exact id and input loaded by capability_describe. Search and describe first whenever the contract is not already present in the conversation.`,inputSchema:F,outputSchema:x,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a})=>{try{return await r.results.success(e,await n.invoke({capability:L(t,i,`query`),arguments:a,clientToken:null}),r.delivery)}catch(e){return r.results.failure(e)}})},B=(e,t,n,r)=>{e.registerTool(`capability_mutate`,{title:`Run a discovered Enhance mutation`,description:`Run one state-changing capability using the exact id and input loaded by capability_describe. Search and describe first, respect its preconditions, and reuse clientToken only when retrying the identical mutation.`,inputSchema:I,outputSchema:x,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a,clientToken:o})=>{try{return await r.results.success(e,await n.invoke({capability:L(t,i,`mutation`),arguments:a,clientToken:o??null}),r.delivery)}catch(e){return r.results.failure(e)}})},V=e=>{let n=new f({name:e.name??`enhance-mcp`,version:e.version},{capabilities:{tools:{listChanged:!1},resources:{listChanged:!0}},...e.exposures?.includes(`mcp-transport`)===!0&&{instructions:`Transport attachment is not Enhance sign-in, even when the host reports mcp_auth success. Use capability_query with capability auth.status to check the person. If authenticated is false or a read returns UNAUTHORIZED, use capability_mutate with capability auth.login and input {"openBrowser":true}, then let the person complete browser sign-in. Verify auth.status and a read such as canvas.list before reporting setup complete.`}}),i=t(e.catalog??r(),e.exposures??[`shared`]),o=a(i),s=e.delivery??`linked`,c=N(e.exposures?.includes(`mcp-transport`)===!0?`Call capability_mutate with capability auth.login and input {"openBrowser":true}. Complete browser sign-in, then verify auth.status and a read such as canvas.list.`:`Reconnect this hosted MCP server through your host’s browser OAuth sign-in. Then verify person.me and a read such as canvas.list.`,e.commandName);g(i,e.version,e.commandName).register(n),R(n,i,o,c),T(o,c).register(n);let l={delivery:s,results:c};return z(n,i,e.invocation,l),B(n,i,e.invocation,l),n};export{V as t};
|
package/dist/mcp.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{l as e,o as t}from"./cli-output-identity.lib-
|
|
2
|
+
import{l as e,o as t}from"./cli-output-identity.lib-C3dhDJfG.mjs";import{t as n}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{t as r}from"./mcp-server.adapter-BVeDABQv.mjs";export{e as createCapabilityCatalogAdapter,r as createEnhanceMcpServer,n as toCapabilityInventory,t as toSharedCapabilities};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{$ as e,B as t,C as n,F as r,H as i,I as a,L as o,M as s,N as c,P as l,Q as u,R as ee,S as te,V as ne,W as re,X as ie,_ as ae,at as oe,b as se,g as ce,h as le,it as ue,j as de,nt as fe,ot as pe,q as me,rt as he,v as ge,w as _e,x as ve,y as ye,z as be}from"./cli-output-identity.lib-C3dhDJfG.mjs";import{z as d}from"zod";import{homedir as xe,tmpdir as Se}from"node:os";import f from"node:process";import{chmodSync as p,createReadStream as m,createWriteStream as Ce,mkdirSync as we,writeFileSync as Te}from"node:fs";import h from"node:path";import{createHash as g,randomBytes as Ee,randomUUID as _}from"node:crypto";import{setTimeout as De}from"node:timers/promises";import{chmod as v,mkdir as Oe,mkdtemp as ke,readFile as Ae,realpath as je,rename as Me,rm as y,stat as b,unlink as Ne,writeFile as Pe}from"node:fs/promises";import{Readable as Fe,Transform as x}from"node:stream";import{pipeline as Ie}from"node:stream/promises";import{ZipFile as Le}from"yazl";import{createTRPCUntypedClient as Re,httpLink as ze}from"@trpc/client";import{spawn as Be}from"node:child_process";import{createServer as Ve}from"node:http";const He=/^enh_[\w-]{43}$/,S=e=>{let r=t.parse(e);if(r.authentication.kind!==`agent`||r.person===null)throw new n(`UNAUTHORIZED`,`The credential is missing, expired, revoked, or invalid.`,`Run 'enhance auth login' and complete authentication in the browser.`);return{authenticated:!0,personId:r.person.id,displayName:r.person.displayName,tokenId:r.authentication.tokenId,tokenLabel:r.authentication.tokenLabel,expiresAt:r.authentication.expiresAt}},Ue=(e,t,r)=>({loginWithToken:async r=>{if(!He.test(r))throw new n(`BAD_REQUEST`,`Agent tokens begin with enh_ and contain 32 base64url bytes.`,`Pass a manual token from Settings to 'enhance auth login' through stdin.`);let i=S(await t.queryWithToken(`person.me`,{},r));return await e.write(r),i},loginWithBrowser:async a=>{let o=ne.parse(await t.authenticationConfig());if(o.method===`token`)throw new n(`BAD_REQUEST`,`Browser authentication is not configured for this Enhance environment.`,`Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.`);let s=await r.authorize({issuer:o.issuer,clientId:o.clientId,scope:o.scope,openBrowser:a.openBrowser,onReady:a.onReady}),c=i.parse(await t.mutateWithToken(`person.createAgentToken`,{label:a.label,expiresAt:null},s)),l=S(await t.queryWithToken(`person.me`,{},c.token));return await e.write(c.token),l},status:async()=>{if(await e.read()===null)throw new n(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return S(await t.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),We=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),Ge=e=>{if(e.byteLength<24||We.some((t,n)=>e[n]!==t))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{width:t.getUint32(16),height:t.getUint32(20)}},Ke=async(e,t)=>{let r=ue.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!r.success)throw new n(`INTERNAL`,`The API returned an invalid render download response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");let i=await e.download(r.data.download.url),a=Ge(i);if(a===null||i.byteLength!==t.result.bytes||a.width!==t.result.width||a.height!==t.result.height)throw new n(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return i},qe=[`canvas.render.create`,`canvas.render.get`],C=e=>new n(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),Je=e=>{let t=e.failure;if(t===null)return C(`render job`);let r=t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,i=t.reason===`VERSION_CHANGED`?`Run 'enhance canvas inspect --canvas ${e.canvasId}', then render its returned version.`:t.reason===`TARGET_NOT_FOUND`?`Run 'enhance canvas tree --canvas ${e.canvasId}' and choose a current node id.`:t.retryable?"Retry the render. If it repeats, run `enhance doctor` and report the job id.":`Change the target or scale using the failure details, then retry.`;return new n(r,t.message,i,{jobId:e.id,reason:t.reason,phase:t.phase})},Ye=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Xe=async(e,t)=>{let n=oe.safeParse(await e.query(qe[1],{jobId:t}));if(!n.success)throw C(`render status`);return n.data.job},Ze=async(e,t)=>{let r=Date.now(),i=0,a=``,o=t.initial;for(;o.state===`queued`||o.state===`running`;){let s=Date.now(),c=`${o.state}:${o.phase}`;if((c!==a||s-i>=5e3)&&(t.progress({event:`render.progress`,jobId:o.id,state:o.state,phase:o.phase,elapsedMs:s-r,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),i=s,a=c),s>=t.deadline)throw new n(`INTERNAL`,`Render ${o.id} did not finish before the local timeout.`,`Retry the exact command with --client-token ${t.retryClientToken} and a larger --timeout-ms. If the render remains unavailable, run \`enhance doctor\` and report the job id.`,{jobId:o.id,phase:o.phase});await Ye(250),o=await Xe(e,o.id)}if(o.state!==`succeeded`)throw Je(o);return o},Qe=e=>{let t=`enhance canvas inspect --canvas ${e.canvasId}`;return e.result.sourceState===void 0?e.target.kind===`node`?[t,`enhance canvas node --canvas ${e.canvasId} --node-id ${e.target.nodeId}`]:[t]:[`Inspect the PNG at path before persisting this moment.`,`enhance recording snapshot --canvas ${e.canvasId} --recording-id ${e.result.sourceState.recordingId} --at-ms ${String(e.result.sourceState.settledAtMs)}`,t]},$e=(e,t)=>({jobId:e.id,canvasId:e.canvasId,requestedVersion:e.requestedVersion,loadedVersion:e.result.loadedVersion,target:e.target,sourceState:e.result.sourceState??null,bounds:e.result.bounds,width:e.result.width,height:e.result.height,scale:e.result.scale,contentType:e.result.contentType,bytes:e.result.bytes,warnings:e.result.warnings,path:t.path,sensitive:!0,cleanup:t.temporary?`unlink-after-use`:`caller-owned`,...t.deleteAfter!==null&&{deleteAfter:t.deleteAfter.toISOString()},next:Qe(e)}),et=async(e,t)=>{let n=fe.safeParse(await e.remote.mutate(qe[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,format:`png`}));if(!n.success)throw C(`render creation`);let r=await Ze(e.remote,{initial:n.data.job,deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress}),i=await Ke(e.remote,r),a=e.files.write({body:i,outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()});return $e(r,a)},w=(e,t,n,r=()=>null)=>({execute:async i=>et({remote:e,files:t,now:n,progress:r},i)}),T={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},E=async e=>{try{return await e(),!0}catch{return!1}},tt=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await E(async()=>e.mutate(T.renew,{...i,nodeIds:[...i.nodeIds],activityId:n})),o=!1)},c=setInterval(()=>void s(),r);return{activityId:n,update:async e=>{a||(i={...i,...e},await s())},finish:async()=>{a||(a=!0,clearInterval(c),await E(async()=>e.mutate(T.end,{canvasId:i.canvasId,activityId:n})))}}},D=e=>({begin:async t=>{try{let n=re.safeParse(await e.mutate(T.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?tt(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>E(async()=>e.mutate(T.end,{canvasId:t,activityId:n}))}),nt=new Set([`insertPrototype`,`insertText`,`setBox`]),rt=e=>nt.has(e.op),it=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,at=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],ot=e=>[...new Set(e.operations.flatMap(e=>at(e)))].slice(0,100),st=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:rt(e)?e.box:null,ct=e=>{let t=e[0];if(t===void 0)return null;let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}},O=async(e,t)=>{let r=await e.mutate(`canvas.applyOperations`,t),i=me.safeParse(r);if(!i.success)throw new n(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return i.data},k=e=>({execute:async(t,n)=>{if(n?.activity===!1)return O(e,t);let r=await D(e).begin({canvasId:t.canvasId,phase:it(t),nodeIds:ot(t),bounds:ct(t.operations.flatMap(e=>{let t=st(e);return t===null?[]:[t]}))});try{return await O(e,t)}finally{await r?.finish()}}}),A=e=>new n(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),lt=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),ut=e=>{let t=e.failure;return new n(t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`CONVERSION_FAILED`?`BAD_REQUEST`:`INTERNAL`,t.message,t.retryable?"Retry the exact write. If it repeats, run `enhance doctor` and report the job id.":`Inspect the current canvas tree and correct the HTML or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},dt=async(t,n)=>{let r=e.safeParse(await t.query(`canvas.render.getImport`,{jobId:n}));if(!r.success)throw A(`HTML import status`);return r.data.job},ft=async(e,t,r)=>{let i=Date.now()+r,a=t;for(;a.state===`queued`||a.state===`running`;){if(Date.now()>=i)throw new n(`INTERNAL`,`HTML import ${a.id} did not finish before the local timeout.`,"Retry the exact command with a larger --timeout-ms. If the queue remains stuck, run `enhance doctor`.",{jobId:a.id,phase:a.phase});await lt(250),a=await dt(e,a.id)}if(a.state!==`succeeded`)throw ut(a);return a},pt=async(e,t)=>{let n=u.safeParse(await e.mutate(`canvas.render.importSource`,{canvasId:t.canvasId,expectedVersion:t.baseVersion,source:{kind:`html`,html:t.html,label:`Agent-authored HTML`,...t.idPrefix!==void 0&&{idPrefix:t.idPrefix}},destination:{kind:t.mode,targetNodeId:t.targetNodeId}}));if(!n.success)throw A(`HTML import creation`);return ft(e,n.data.job,t.renderTimeoutMs)},mt=(e,t,r)=>({state:`failed`,mutationCommitted:!0,requestedVersion:r,...e instanceof n?{code:e.code,message:e.message,remediation:e.remediation,...e.fields!==void 0&&{fields:e.fields}}:{code:`INTERNAL`,message:`The post-write review render failed.`,remediation:`Read the current canvas version, then render the affected area again.`},next:[`enhance canvas inspect --canvas ${t.canvasId}`,`enhance canvas render --canvas ${t.canvasId} --expected-version ${String(r)}`,`Do not replay the committed write with a new mutation id.`]}),ht=async(e,t,n)=>{try{return await e.execute({canvasId:t.canvasId,expectedVersion:n.result.version,target:{kind:`node`,nodeId:n.result.rootNodeId},sourceState:null,scale:t.renderScale,outputPath:t.renderOutputPath,overwrite:t.overwriteRender,timeoutMs:t.renderTimeoutMs,retryClientToken:t.renderClientToken})}catch(e){return mt(e,t,n.result.version)}},gt=async(e,t)=>{let n=ie.safeParse(await e.query(`canvas.document.get`,{canvasId:t.canvasId}));if(!n.success)throw A(`canvas document`);let r=pe.safeParse(n.data.document);if(!r.success)throw A(`editable canvas document`);return t.result.insertedNodeIds.map(e=>{let t=r.data.nodes[e];return{id:e,name:t?.label??``,component:t?.component??``}})},_t=async(e,t,n,r)=>({canvasId:t.canvasId,mutationCommitted:!0,mode:t.mode,targetNodeId:t.targetNodeId,previousVersion:n.result.previousVersion,version:n.result.version,createdNodes:await gt(e,n),removedNodeIds:n.result.removedNodeIds,affectedBounds:n.result.affectedBounds,review:r,next:[`enhance canvas tree --canvas ${t.canvasId}`,`Inspect the review PNG before continuing.`]}),j=(e,t)=>({execute:async n=>{let r=await D(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await pt(e,n);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await ht(t,n,i);return await _t(e,n,i,a)}finally{await r?.finish()}}}),M=(e,t,r)=>{try{Te(e,t,{flag:r?`w`:`wx`,mode:384}),p(e,384)}catch(t){let r=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new n(r,r===`CONFLICT`?`Refusing to replace ${e}.`:`Could not write ${e}.`,r===`CONFLICT`?`Choose another --output path or pass --force deliberately.`:`Create the parent directory and verify it is writable, then retry.`)}},N=e=>({write:t=>{if(t.outputPath!==null){let e=h.resolve(t.outputPath);return M(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=h.join(e,`sensitive`);we(n,{recursive:!0,mode:448}),p(n,448);let r=h.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return M(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),P=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`,`prototype.attach`],F=e=>new n(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),vt=async(e,t)=>{let r=Date.now()+3e5,i=50;for(;Date.now()<r;){let r=a.safeParse(await e.query(P[3],t));if(!r.success)throw F(`status`);if(r.data.state===`ready`||r.data.state===`failed`)return r.data;if(r.data.state===`abandoned`)throw new n(`NOT_FOUND`,`Prototype deployment ${t.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);await De(i),i=Math.min(i*2,1e3)}throw Error(`prototype ingestion is still running`)},yt=async(e,t,n,r)=>{let i=c.safeParse(await e.mutate(P[1],{canvasId:t.canvasId,...t.prototypeId!==null&&{prototypeId:t.prototypeId},clientToken:t.clientToken,nodeId:t.nodeId,title:t.title,entryPath:n.manifest.entryPath,artifact:n.identity,box:t.box}));if(!i.success)throw F(`artifact creation`);if(r(i.data.deploymentId),i.data.state===`uploading`&&await e.upload({url:i.data.upload.url,headers:i.data.upload.headers,body:n.open()}),(i.data.state===`uploading`||i.data.state===`queued`)&&!be.safeParse(await e.mutate(P[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId})).success)throw F(`artifact submission`);return i.data},bt=e=>{if(e.state!==`failed`)return;let{failure:t}=e;throw new n(`BAD_REQUEST`,t.message,`Fix the build and publish it with a new client token.`,t.path===void 0?void 0:{path:t.path})},xt=async(e,t,i)=>{let a=r.safeParse(await e.query(P[0],{}));if(!a.success)throw F(`capabilities`);let o=await t.package({directory:i.directory,entryPath:i.entryPath,limits:a.data.limits}),c={deploymentId:null};try{let t=await yt(e,i,o,e=>{c.deploymentId=e}),n=await vt(e,{canvasId:i.canvasId,deploymentId:t.deploymentId});bt(n);let r=s.safeParse(await e.mutate(P[4],{canvasId:i.canvasId,deploymentId:t.deploymentId,baseVersion:i.baseVersion}));if(!r.success)throw F(`attachment`);return{...r.data,fileCount:n.fileCount,totalBytes:n.totalBytes,alreadyExists:t.alreadyExists,next:[r.data.openUrl,`enhance canvas render --canvas ${i.canvasId} --node-id ${r.data.nodeId} --expected-version ${String(r.data.version)}`]}}catch(e){throw e instanceof n&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||c.deploymentId===null?e:new te(`Prototype deployment ${c.deploymentId} was created, but publishing did not complete.`,`Retry 'enhance prototype publish' with the same --client-token ${i.clientToken}.`)}finally{await o.dispose()}},St=(e,t)=>({execute:async n=>xt(e,t,n)}),Ct=[`transcript.get`],wt=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),Tt=e=>({execute:async t=>{let r=_e.safeParse(await e.query(Ct[0],t));if(!r.success)throw new n(`INTERNAL`,`The API returned an invalid transcript response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data.state===`ready`?{...r.data,guidance:`Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.`,next:wt(t.canvasId,t.recordingId,r.data.cues.map(e=>e.startMs))}:r.data}}),I=[`canvas.render.get`,`canvas.render.snapshot`],Et=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),Dt=e=>new n(e.failure?.reason===`VERSION_CHANGED`?`CONFLICT`:e.failure?.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:e.failure?.reason===`TARGET_INVALID`||e.failure?.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,e.failure?.message??`The snapshot job ended without a result.`,`Run 'enhance canvas tree --canvas ${e.canvasId}' and retry the exact snapshot if its recording node still exists.`,{jobId:e.id,phase:e.phase}),Ot=async(e,t)=>{let r=oe.safeParse(await e.query(I[0],{jobId:t}));if(!r.success)throw new n(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return r.data.job},kt=async(e,t,r,i)=>{let a=Date.now()+r.timeoutMs,o=Date.now(),s=t,c=0,l=``;for(;s.state===`queued`||s.state===`running`;){let t=Date.now(),u=`${s.state}:${s.phase}`;if((u!==l||t-c>=5e3)&&(i({event:`snapshot.progress`,jobId:s.id,state:s.state,phase:s.phase,elapsedMs:t-o,timeoutMs:r.timeoutMs,retryClientToken:r.retryClientToken}),c=t,l=u),t>=a)throw new n(`INTERNAL`,`Snapshot ${s.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${r.retryClientToken} and a larger --timeout-ms.`,{jobId:s.id,phase:s.phase});await Et(),s=await Ot(e,s.id)}if(s.state!==`succeeded`||s.result.snapshot===void 0)throw Dt(s);return{...s,result:{...s.result,snapshot:s.result.snapshot}}},At=async(e,t,r)=>{let i=he.safeParse(await e.mutate(I[1],{canvasId:r.canvasId,recordingId:r.recordingId,atMs:r.atMs}));if(!i.success)throw new n(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");let a=await kt(e,i.data.job,r,t),o=a.result.snapshot;return{jobId:a.id,canvasId:a.canvasId,...o,warnings:a.result.warnings,retryClientToken:r.retryClientToken,next:[`enhance canvas node --canvas ${a.canvasId} --node-id ${o.screenNodeId}`,`enhance canvas render --canvas ${a.canvasId} --node-id ${o.screenNodeId} --expected-version ${String(o.version)}`]}},jt=(e,t)=>({execute:async n=>At(e,t,n)}),L=new Date(`1980-01-01T00:00:00.000Z`),R=33188,z=(e,t)=>new n(`BAD_REQUEST`,e,t),Mt=(e,t)=>{let n=g(`sha256`),r=0;return new x({transform:(e,t,i)=>{r+=e.byteLength,n.update(e),i(null,e)},flush:i=>{if(r!==e.bytes){i(Error(`prototype file ${e.path} changed while it was packaged`));return}t({path:e.path,contentType:e.contentType,bytes:r,sha256:n.digest(`hex`)}),i()}})},Nt=e=>{let t=o.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),n=Buffer.from(JSON.stringify(t),`utf8`);if(n.byteLength>e.limits.manifestBytes)throw z(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,de,{mtime:L,mode:R,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},Pt=async e=>{let t=new Le,n=g(`sha256`),r=new x({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=Ie(t.outputStream,r,Ce(e.artifactPath));t.on(`error`,e=>r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)));let s=n=>{i.set(n.path,n),a.manifest===null&&i.size===e.files.length&&(a.manifest=Nt({zip:t,completed:i,...e}))};for(let n of e.files)t.addReadStreamLazy(n.path,{size:n.bytes,mtime:L,mode:R,compress:!0,forceDosTimestamp:!0},e=>{e(null,m(n.absolutePath).pipe(Mt(n,s)))});if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let c=await b(e.artifactPath);if(c.size>e.limits.artifactBytes)throw z(`The packaged prototype artifact is too large.`,`This environment accepts ${String(e.limits.artifactBytes)} compressed bytes.`);return{manifest:a.manifest,bytes:c.size,sha256:n.digest(`hex`)}},Ft={".avif":`image/avif`,".css":`text/css; charset=utf-8`,".gif":`image/gif`,".html":`text/html; charset=utf-8`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".map":`application/json; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".mp3":`audio/mpeg`,".mp4":`video/mp4`,".ogg":`audio/ogg`,".otf":`font/otf`,".png":`image/png`,".svg":`image/svg+xml`,".ttf":`font/ttf`,".txt":`text/plain; charset=utf-8`,".wasm":`application/wasm`,".webm":`video/webm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`,".xml":`application/xml`},It=e=>Ft[h.extname(e).toLowerCase()]??`application/octet-stream`,B=async e=>{try{return await b(e)}catch{return null}},Lt=e=>Buffer.byteLength(e,`utf8`),V=(e,t)=>new n(`BAD_REQUEST`,e,t),H=(e,t)=>{if(!ee.safeParse(e).success)throw V(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(Lt(e)>t.pathBytes)throw V(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},U=async(e,t,n,r)=>{let i=await je(t);if(n.has(i))throw V(`Cannot package the circular directory link at ${t}.`,`Pass a directory tree that can be read once from top to bottom.`);let a=new Set(n).add(i),{readdir:o}=await import(`node:fs/promises`),s=await o(t,{withFileTypes:!0}),c=[],l=s.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of l){let i=h.join(t,n.name),o=await B(i);if(o?.isDirectory()===!0){c.push(...await U(e,i,a,r));continue}if(o?.isFile()!==!0)throw V(`Cannot read ${i} as a prototype file.`,`Pass a directory containing only regular files and directory links.`);let s=h.relative(e,i).split(h.sep).join(`/`).normalize(`NFC`);H(s,r),c.push({absolutePath:i,path:s,bytes:Number(o.size),contentType:It(i)})}return c},Rt=(e,t,n)=>{if(e.length===0)throw V(`The prototype build is empty.`,`Build the app before publishing it.`);if(e.length>n.fileCount)throw V(`The prototype has ${String(e.length)} files.`,`This environment currently accepts ${String(n.fileCount)} files per deployment.`);let r=new Set,i=0;for(let t of e){let e=l(t.path);if(r.has(e))throw V(`The prototype path ${t.path} collides by case or Unicode normalization.`,`Rename one of the colliding files so the build is portable.`);if(r.add(e),t.bytes>n.fileBytes)throw V(`The prototype file ${t.path} is too large.`,`This environment accepts ${String(n.fileBytes)} bytes in one runtime file.`);if(i+=t.bytes,i>n.expandedBytes)throw V(`The prototype build is too large.`,`This environment accepts ${String(n.expandedBytes)} expanded bytes.`)}let a=e.find(e=>e.path===t);if(a===void 0)throw V(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw V(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},zt=async e=>{let t=h.resolve(e.directory),r=await B(t);if(r===null)throw new n(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!r.isDirectory())throw V(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let i=e.entryPath.split(h.sep).join(`/`).normalize(`NFC`);H(i,e.limits);let a=await U(t,t,new Set,e.limits);Rt(a,i,e.limits);let o=await ke(h.join(Se(),`enhance-prototype-artifact-`)),s=h.join(o,`artifact.zip`);try{let t=await Pt({artifactPath:s,files:a,entryPath:i,limits:e.limits});return{identity:{protocolVersion:1,format:`zip`,bytes:t.bytes,sha256:t.sha256,fileCount:t.manifest.files.length,expandedBytes:t.manifest.files.reduce((e,t)=>e+t.bytes,0)},manifest:t.manifest,open:()=>m(s),dispose:async()=>y(o,{recursive:!0})}}catch(e){throw await y(o,{recursive:!0}),e}},Bt=()=>({package:zt}),W=e=>w(e.remote,N(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Vt=async(e,t)=>{let n=le.parse(t);return k(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Ht=async(e,t,n)=>{let r=ce.parse(t);return W(e).execute({...r,retryClientToken:n})},Ut=async(e,t)=>{let n=ae.parse(t);return j(e.remote,W(e)).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},Wt=async(e,t)=>{let n=ge.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},Gt=async(e,t,n)=>{let r=ye.parse(t);return St(e.remote,Bt()).execute({...r,clientToken:n})},Kt=async(e,t,n)=>{let r=se.parse(t);return jt(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},qt=async(e,t)=>{let n=ve.parse(t);return Tt(e.remote).execute(n)},Jt=async(e,t,n,r)=>{switch(t){case`canvas.apply`:return Vt(e,n);case`canvas.render`:return Ht(e,n,r);case`canvas.writeHtml`:return Ut(e,n);case`comment.attention`:return Wt(e,n);case`prototype.publish`:return Gt(e,n,r);case`recording.snapshot`:return Kt(e,n,r);case`transcript.read`:return qt(e,n);default:throw TypeError(`${t} has no composite execution`)}},Yt=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??_();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Jt(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),G=`/callback`,Xt=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),Zt=e=>{let t=f.platform===`darwin`?{executable:`open`,arguments:[e]}:f.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=Be(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},Qt=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==G){n.writeHead(404).end();return}if(r.searchParams.get(`state`)!==e.state){n.writeHead(400).end(`The OAuth state did not match. Return to the terminal and retry.`);return}let i=r.searchParams.get(`error`),a=r.searchParams.get(`code`);if(i!==null||a===null||a===``){n.writeHead(400).end(`Enhance authentication was not approved.`),e.completion.reject(Error(i??`the authorization response carried no code`));return}n.writeHead(200,{"content-type":`text/html; charset=utf-8`}).end(`<!doctype html><meta charset="utf-8"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>`),e.completion.resolve(a)},$t=e=>{let t=Xt(e.issuer,`oauth/authorize`);return t.search=new URLSearchParams({response_type:`code`,client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,code_challenge:e.challenge,code_challenge_method:`S256`}).toString(),t.href},en=async e=>{let t=Promise.withResolvers(),n=Ve((n,r)=>{Qt({state:e.state,completion:t},n,r)});await new Promise((e,t)=>{n.once(`error`,t),n.listen(0,`127.0.0.1`,e)});let r=n.address();if(r===null||typeof r==`string`)throw n.close(),Error(`the OAuth callback listener has no TCP port`);let i=`http://127.0.0.1:${String(r.port)}${G}`,a=$t({...e,redirectUri:i});e.onReady(a),e.openBrowser&&Zt(a);let o=setTimeout(()=>{t.reject(Error(`browser authorization timed out`))},12e4);try{return{code:await t.promise,redirectUri:i}}finally{clearTimeout(o),await new Promise(e=>{n.close(()=>{e()})})}},tn=e=>({authorize:async t=>{try{let n=Ee(32).toString(`base64url`),r=g(`sha256`).update(n).digest(`base64url`),i=Ee(32).toString(`base64url`),a=await en({...t,challenge:r,state:i});return await e.exchangeOauthCode({issuer:t.issuer,clientId:t.clientId,code:a.code,redirectUri:a.redirectUri,verifier:n})}catch(e){throw new n(`UNAUTHORIZED`,e instanceof Error?`Browser authentication failed: ${e.message}.`:`Browser authentication failed.`,`Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.`)}}}),K=e=>e===void 0||e===``?void 0:e,nn=((e,t,n)=>{let r=K(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=K(e.ENHANCE3_API_URL),a=h.join(t,`.config`,n.configDirectoryName),o=K(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&i!==n.apiUrl)throw TypeError(`Enhance development cannot use ${i}`);if(o!==void 0&&h.resolve(o)!==h.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}})(f.env,xe(),{apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`}),rn=d.object({token:d.string().startsWith(`enh_`)}),an=e=>{let t=h.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await Ae(t,`utf8`));return rn.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Oe(e,{recursive:!0,mode:448}),await v(e,448);let r=h.join(e,`credentials.${String(f.pid)}.tmp`);await Pe(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await Me(r,t),await v(t,384)},remove:async()=>{try{return await Ne(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},on=d.object({access_token:d.string().min(1)}),sn=d.object({code:d.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),q=`Check network access and proxy settings for this API, then run enhance doctor again.`,J=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,Y=e=>{let t=sn.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?Y(e.cause):e instanceof Error?e.name:`Network request failed`},X=(e,t)=>new n(`INTERNAL`,`${J(e)} answered HTTP ${String(t)}.`,q),Z=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new n(`INTERNAL`,`Could not reach ${J(e)}: ${Y(t)}.`,q)}},cn=async(e,t)=>{let n=await Z(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw X(e,n.status);return n},Q=(e,t,n=null)=>Re({links:[ze({url:`${e}/trpc`,fetch:async(e,t)=>cn(e,{...t,signal:t?.signal??null}),headers:{...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),ln=async e=>{let t=await fetch(e);if(!t.ok)throw new n(t.status===404||t.status===403?`NOT_FOUND`:`INTERNAL`,`Render download answered HTTP ${String(t.status)}.`,`The result may have expired. Request a new render.`);return new Uint8Array(await t.arrayBuffer())},un=async e=>{let t=await Z(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new n(`BAD_REQUEST`,`This Enhance API does not support browser authentication.`,`Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.`):new n(`INTERNAL`,`${J(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,q);return t.json()},dn=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await Z(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw X(e,n.status);return n.json()},fn=async e=>{let t=await Z(new URL(`oauth/token`,e.issuer.endsWith(`/`)?e.issuer:`${e.issuer}/`),{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`authorization_code`,client_id:e.clientId,code:e.code,redirect_uri:e.redirectUri,code_verifier:e.verifier})});if(!t.ok)throw new n(`INTERNAL`,`${J(e.issuer)} token exchange answered HTTP ${String(t.status)}`,q);return on.parse(await t.json()).access_token},pn=async e=>{try{let t=await Z(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:X(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${J(e)}.`}}},mn=(e,t,r)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>un(i),oauthMetadata:dn,exchangeOauthCode:fn,query:async(e,n)=>Q(i,await t.read()).query(e,n),queryWithToken:async(e,t,n)=>Q(i,n).query(e,t),mutate:async(e,n)=>Q(i,await t.read(),r.current(e,n)).mutation(e,n),mutateWithToken:async(e,t,n)=>Q(i,n).mutation(e,t),download:ln,upload:async e=>{let t=!(e.body instanceof Uint8Array),r=t?Fe.toWeb(e.body):e.body,i={method:`PUT`,headers:e.headers,body:r,...t&&{duplex:`half`}},a=await fetch(e.url,i);if(!a.ok)throw new n(`INTERNAL`,`Signed upload answered HTTP ${String(a.status)}.`,`Retry the fixture command with the same source file.`);let o=a.headers.get(`etag`);if(o===null||o===``)throw new n(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return o.replaceAll(`"`,``)},health:async()=>pn(i)}},$=e=>Array.isArray(e)?e.map(e=>$(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,$(t)])),hn=(e,t,n)=>g(`sha256`).update(`${e}\0${t}\0${JSON.stringify($(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),gn=()=>{let e=_(),t=!1;return{current:(n,r)=>t?hn(e,n,r):e,select:(n,r)=>{e=n??_(),t=r}}};export{tn as a,j as c,w as d,Ue as f,nn as i,k as l,mn as n,Yt as o,an as r,N as s,gn as t,D as u};
|