@enhance-eng/enhance-dev 0.1.20-dev.sha-e63643fbee08 → 0.1.20-dev.sha-20969365248e

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/main.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import{$ as e,A as t,At as n,Ct as r,D as i,Dt as a,E as o,Et as s,F as c,I as l,L as u,M as d,O as ee,Ot as te,P as ne,Q as re,R as ie,T as ae,Tt as f,a as oe,c as se,ct as ce,d as le,dt as ue,et as de,f as fe,g as pe,h as p,ht as me,i as he,it as ge,j as m,k as h,l as _e,n as g,o as _,ot as v,p as ve,rt as ye,st as be,t as xe,u as y,vt as b,wt as x,z as Se}from"./cli-output-identity.lib-BxOq1eK4.mjs";import{a as Ce,c as we,d as Te,f as Ee,i as S,l as De,m as Oe,n as ke,o as Ae,p as je,r as Me,s as Ne,t as Pe,u as C}from"./mutation-key.adapter-Cl4fSIbD.mjs";import{t as Fe}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{Command as Ie}from"commander";import{createCli as Le,parseRouter as Re}from"trpc-cli";import{z as w}from"zod";import{hostname as ze,tmpdir as Be}from"node:os";import T from"node:process";import{createInterface as Ve}from"node:readline";import{chmodSync as He,existsSync as Ue,lstatSync as We,mkdirSync as Ge,readFileSync as Ke,readdirSync as qe,statSync as E,unlinkSync as Je,writeFileSync as D}from"node:fs";import O from"node:path";import{createHash as Ye,randomUUID as k}from"node:crypto";import{readFile as Xe}from"node:fs/promises";import{proxify as Ze}from"trpc-cli/dist/proxify.js";const Qe=e=>`${JSON.stringify(e)}\n`,$e=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()]:[]}},et=(e,t)=>{let n=$e(t);return[...e.flatMap(e=>n.add(e)),...n.drain()]},A=[`recording.start`,`recording.appendChunk`,`recording.complete`],tt=e=>async t=>{let n=Se.parse(await e.mutate(A[0],{sourceUrl:t.sourceUrl,viewport:t.viewport,pageTitle:t.pageTitle,audio:null})),r=n.upload;try{let i=et(t.entries,8388608);for(let[t,a]of i.entries()){let i=new TextEncoder().encode(a.body),o=await e.upload({url:r.url,headers:r.headers,body:i});r=u.parse(await e.mutate(A[1],{recordingId:n.recordingId,index:t,firstEventMs:a.firstEventMs,lastEventMs:a.lastEventMs,eventCount:a.eventCount,continues:a.continues,bytes:i.byteLength,etag:o})).upload}let a=Math.max(0,...t.entries.map(e=>e.atMs));return ie.parse(await e.mutate(A[2],{recordingId:n.recordingId,durationMs:a,viewport:t.viewport,sourceUrl:t.sourceUrl,interrupted:!1,...t.canvasId!==void 0&&{canvasId:t.canvasId},audioChunkCount:0,hasRecoverableBytes:!1}))}catch{throw new m(`Recording ${n.recordingId} began, but not every chunk was committed.`,`Run 'enhance recording discard --recording-id ${n.recordingId}' to remove the incomplete attempt before retrying the fixture.`)}},j=[`screen.create`,`screen.complete`],nt=e=>async t=>{let n=l.parse(await e.mutate(j[0],{clientToken:t.clientToken,provenance:t.provenance,route:t.route,pageTitle:t.pageTitle,viewport:t.viewport,bytes:t.body.byteLength}));try{let r=await e.upload({url:n.upload.url,headers:n.upload.headers,body:t.body}),i=c.parse(await e.mutate(j[1],{screenId:n.screenId,etag:r}));return{screenId:i.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:i.storedBytes}}catch{throw new m(`Screen ${n.screenId} was reserved, but its upload did not complete.`,`Retry 'enhance fixture screen' with the same --client-token ${t.clientToken}.`)}},M=[`organisation.create`,`canvas.create`,`screen.create`,`screen.complete`,`canvas.document.get`,`canvas.document.save`],rt=(t,r)=>async i=>{let a=re.parse(await t.mutate(M[0],{name:i.organisationName})).organisation,o=n.parse(await t.mutate(M[1],{title:i.canvasTitle,organisationId:a.id,sourceUrl:null}));try{let n=[];for(let e of i.screens)n.push(await r(e));let s=v.parse(await t.query(M[4],{canvasId:o.id})),c=e();for(let[e,t]of n.entries())c=de(c,{id:`fixture-screen-${String(e+1)}`,label:`Fixture screen ${String(e+1)}`,screenId:t.screenId,viewport:i.screens[e]?.viewport??{width:1440,height:900},at:{x:48+e*48,y:48+e*48}});let l=be.parse(await t.mutate(M[5],{canvasId:o.id,baseVersion:s.version,document:c,screenIds:n.map(e=>e.screenId)}));if(l.outcome===`conflict`)throw new m(`World canvas ${o.id} was created, but another writer changed its document.`,`Read 'enhance canvas document get --canvas-id ${o.id}' before adding the screens.`);return{organisationId:a.id,canvasId:o.id,screenIds:n.map(e=>e.screenId),documentVersion:l.version}}catch(e){throw e instanceof m?e:new m(`Organisation ${a.id} and canvas ${o.id} exist, but the world is incomplete.`,`Inspect 'enhance canvas get --canvas-id ${o.id}' before retrying any missing steps.`)}},it=async(e,t)=>{if(e!==void 0&&e!==``)return e.trim();if(T.stdin.isTTY)throw new d(`BAD_REQUEST`,`A token is required and interactive prompting is disabled.`,`Pass '--token <token>' or pipe one line to '${t}'.`);let n=Ve({input:T.stdin,crlfDelay:1/0});for await(let e of n){n.close();let t=e.trim();if(t!==``)return t;break}throw new d(`BAD_REQUEST`,`A token is required.`,`Pass '--token <token>' or pipe one line to '${t}'.`)},at=async e=>{if(e!==void 0)return e.trim();if(T.stdin.isTTY)return null;let t=Ve({input:T.stdin,crlfDelay:1/0});for await(let e of t){t.close();let n=e.trim();return n===``?null:n}return null},ot=(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 at(e.token);if(r!==null){n.result(await t.loginWithToken(r));return}n.result(await t.loginWithBrowser({label:`CLI on ${ze()}`.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())})},N=1e3,st=w.coerce.number().int().positive(),ct=w.coerce.number().min(.1).max(4),lt=w.uuid(),ut=w.union([w.string(),w.number(),w.null()]),dt=w.record(w.string(),ut),ft=w.array(w.object({nodeId:w.string().min(1).max(200),textContent:w.string().max(1e5)})).min(1).max(N),pt=w.array(w.object({nodeId:w.string().min(1).max(200),name:w.string().max(500)})).min(1).max(N),mt=w.array(w.object({nodeIds:w.array(w.string().min(1).max(200)).min(1).max(100),styles:dt})).min(1).max(100),ht=w.array(w.object({id:w.string().min(1).max(200),parentId:w.string().min(1).max(200).optional()})).min(1).max(100),gt=w.array(w.union([w.object({nodeId:w.string().min(1).max(200),before:w.string().min(1).max(200)}),w.object({nodeId:w.string().min(1).max(200),after:w.string().min(1).max(200)}),w.object({nodeId:w.string().min(1).max(200),parentId:w.string().min(1).max(200),index:w.number().int().nonnegative().optional()})])).min(1).max(100),_t=w.array(w.string().min(1).max(200)).min(1).max(N),vt=w.coerce.number().int().min(0).max(20),yt=w.uuid().nullable(),P=(e,t,n)=>{let r=e.safeParse(t);if(r.success)return r.data;throw new d(`BAD_REQUEST`,`${n} is invalid.`,`Run the command with --help.`)},F=e=>P(st,e,`--base-version`),I=(e,t,n)=>{let r=yt.safeParse(t??null);if(!r.success)throw new d(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying the exact same command.`);e.mutationKey.select(r.data,n)},bt=(e,t)=>e.mutationKey.current(`canvas.applyOperations`,{purpose:t}),xt=async(e,n,r,a)=>{I(e,n.clientToken,!1);let o=t(n.canvas),s=F(n.baseVersion);return o.nodeIds.length>0&&i(o,await C(e,o.canvasId,s),a),Te(e.remote).execute({canvasId:o.canvasId,mutationId:bt(e,r),baseVersion:s,operations:[...a]})},L=async(e,n,r,i)=>{I(e,n.clientToken,!1);let a=t(n.canvas);return De(e.remote).execute({...a,baseVersion:F(n.baseVersion),mutationId:bt(e,`canvas.edit`),edits:r,...i!==void 0&&{idPrefix:i}})},St=w.array(ue).min(1).max(ce),Ct=e=>{if(!e.startsWith(`@`))return e;let t=e.slice(1);if(t===``)throw new d(`BAD_REQUEST`,`--operations @ must name a JSON file.`,`Pass --operations @/absolute/path/layout.json or an inline JSON array.`);let n=O.resolve(t);try{let e=E(n);if(!e.isFile()||e.size>1048576)throw Error(`invalid size`);return Ke(n,`utf8`)}catch{throw new d(`BAD_REQUEST`,`Could not read a bounded operations file at ${n}.`,`Use a regular JSON file no larger than 1 MiB.`)}},wt=e=>{try{return JSON.parse(Ct(e))}catch(e){throw e instanceof d?e:new d(`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 t=wt(e),n=St.safeParse(t);if(!n.success){let e=n.error.issues[0];throw new d(`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 n.data},R=(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=w.coerce.number().int().positive(),Dt=e=>{let t=Et.safeParse(e);if(t.success)return t.data;throw new d(`BAD_REQUEST`,`--base-version is invalid.`,`Run 'enhance canvas apply --help'.`)},Ot=(e,t)=>{let n=w.uuid().nullable().safeParse(t??null);if(!n.success)throw new d(`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(n.data,!1),e.mutationKey.current(`canvas.applyOperations`,{})},kt=(e,n)=>{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, editText, setBox, setLabel, setVisibility, setLocked, setConstraints, setStyles, setAppearance, setLayout, patchTypography, setTypography, patchAdditionalStyles, setAdditionalStyles, setProps, setParentage, move, remove.`,`Use editText for revision-aware character or range changes. setText replaces the whole text and is rejected if it conflicts with a newer text edit.`,`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(n,e.clientToken);let r=t(e.canvas),a=Dt(e.baseVersion),o=Tt(e.operations);r.nodeIds.length>0&&i(r,await C(n,r.canvasId,a),o);let s=await n.invocation.invoke({capability:R(n.catalog(),`canvas.apply`),arguments:{canvasId:r.canvasId,baseVersion:a,operations:[...o]},clientToken:e.clientToken??null});n.output.result(s)})},At=e=>{try{return JSON.parse(e)}catch{return}},jt=e=>{if(e===void 0)return null;let t=b.safeParse(At(e));if(t.success)return t.data;throw new d(`BAD_REQUEST`,`--bounds must be a positive world rectangle.`,`Pass JSON with x, y, width and height.`)},z=e=>e===void 0?[]:e.split(`,`).map(e=>e.trim()).filter(e=>e!==``).slice(0,100),Mt=(e,t)=>{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 n=ge.safeParse(e.phase);if(!n.success)throw new d(`BAD_REQUEST`,`--phase is invalid.`,`Use reading, writing, creating, deleting, or rendering.`);let r=h(e.canvas),i=ye.parse(await t.remote.mutate(`canvas.realtime.activity.begin`,{canvasId:r,phase:n.data,nodeIds:z(e.nodeIds),bounds:jt(e.bounds)}));t.output.result({...i,next:[`enhance canvas work update --canvas ${r} --activity-id ${i.activityId} --phase ${n.data}`,`enhance canvas finish-working-on-nodes --canvas ${r} --activity-id ${i.activityId}`]})})},Nt=(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(ye.parse(await t.remote.mutate(`canvas.realtime.activity.renew`,{canvasId:h(e.canvas),activityId:lt.parse(e.activityId),phase:ge.parse(e.phase),nodeIds:z(e.nodeIds),bounds:jt(e.bounds)})))})},Pt=(e,t)=>{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 Ee(t.remote).finish(h(e.canvas),lt.parse(e.activityId)))throw new d(`NOT_FOUND`,`The activity could not be finished.`,`It may already have expired; run canvas work begin for new work.`);t.output.result({ended:!0,activityId:e.activityId})})},Ft=(e,t)=>{let n=e.command(`work`).description(`Manage visible agent activity.`);Mt(n,t),Nt(n,t),Pt(e,t)},B=(e,t,n)=>{if(!e.startsWith(`@`))return e;let r=e.slice(1);if(r===``)throw new d(`BAD_REQUEST`,`${n} @ must name a file.`,`Pass ${n} @/absolute/path/to/file or an inline value.`);let i=O.resolve(r);try{let e=E(i);if(!e.isFile()||e.size>t)throw Error(`invalid size`);return Ke(i,`utf8`)}catch{throw new d(`BAD_REQUEST`,`Could not read a bounded file at ${i}.`,`Use a regular UTF-8 file no larger than ${String(t)} bytes.`)}},V=(e,t,n)=>{let r=(()=>{try{return JSON.parse(B(e,1048576,n))}catch(e){throw e instanceof d?e:new d(`BAD_REQUEST`,`${n} must be valid JSON.`,`Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`)}})(),i=t.safeParse(r);if(i.success)return i.data;let a=i.error.issues[0];throw new d(`BAD_REQUEST`,`${n} is invalid${a===void 0||a.path.length===0?``:` at ${a.path.join(`.`)}`}.`,a?.message??`Correct the JSON shape and retry.`)},It=(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,ft,`--updates`).map(e=>({kind:`set_text`,nodeId:e.nodeId,text:e.textContent}));t.output.result(await L(t,e,n))})},Lt=(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,pt,`--updates`).map(e=>({kind:`rename`,nodeId:e.nodeId,name:e.name}));t.output.result(await L(t,e,n))})},Rt=(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,_t,`--node-ids`);t.output.result(await xt(t,e,`delete-nodes`,n.map(e=>({op:`remove`,nodeId:e}))))})},zt=(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=V(e.updates,mt,`--updates`);t.output.result(await L(t,e,n.map(e=>({kind:`set_styles`,...e}))))})},Bt=(e,t)=>{e.command(`edit`).description(`Apply an atomic canvas edit batch.`).requiredOption(`--canvas <url-or-id>`,`Canvas or selection URL, or canvas UUID.`).requiredOption(`--base-version <integer>`,`Canvas version to edit; use the previous write result to continue.`).requiredOption(`--edits <json-or-@path>`,`Array of edits with kind set_text, set_styles, rename, duplicate or move.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).addHelpText(`after`,`
2
+ import{$ as e,A as t,D as n,Dt as r,E as i,Et as a,F as o,I as s,L as c,M as l,O as ee,Ot as te,P as ne,Q as re,R as ie,T as ae,Tt as u,a as oe,at as se,c as ce,ct as le,d as ue,et as de,f as fe,ft as pe,g as me,gt as he,h as d,i as ge,it as _e,j as f,jt as ve,k as p,kt as ye,l as be,lt as xe,n as m,o as h,p as Se,rt as Ce,st as g,t as we,u as _,wt as v,yt as Te,z as Ee}from"./cli-output-identity.lib-DZVeJQIS.mjs";import{a as De,c as Oe,d as ke,f as Ae,i as y,l as je,m as Me,n as Ne,o as Pe,p as Fe,r as Ie,s as Le,t as Re,u as b}from"./mutation-key.adapter-DAuPDkh5.mjs";import{t as ze}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{Command as Be}from"commander";import{createCli as Ve,parseRouter as He}from"trpc-cli";import{z as x}from"zod";import{hostname as Ue,tmpdir as We}from"node:os";import S from"node:process";import{createInterface as Ge}from"node:readline";import{chmodSync as Ke,existsSync as qe,lstatSync as Je,mkdirSync as Ye,readFileSync as C,readdirSync as Xe,statSync as Ze,unlinkSync as Qe,writeFileSync as w}from"node:fs";import T from"node:path";import{createHash as $e,randomUUID as E}from"node:crypto";import{readFile as et}from"node:fs/promises";import{proxify as tt}from"trpc-cli/dist/proxify.js";const nt=1e6,rt=e=>Math.round(e*255*nt)/nt,it=(e,t=1)=>{let n=e.alpha*t;if(e.space===`srgb`){let t=[e.red,e.green,e.blue].map(e=>String(rt(e))).join(` `);return n===1?`rgb(${t})`:`rgb(${t} / ${String(n)})`}let r=`${String(e.red)} ${String(e.green)} ${String(e.blue)}`;return`color(${e.space} ${r} / ${String(n)})`},at=e=>e===void 0?{}:{...e!==`auto`&&{direction:e},"unicode-bidi":e===`auto`?`plaintext`:`isolate`},ot=/^-?[_a-z][-\w]*$/iu,st=/^var\(--[-\w]+\)$/iu,ct=e=>ot.test(e)||st.test(e)?e:JSON.stringify(e),lt=e=>[...new Set([e.family,...e.family===`Inter`?[`Inter Variable`]:[],...e.family===`JetBrains Mono`?[`JetBrains Mono Variable`]:[],...e.fallbackFamilies])].map(e=>ct(e)).join(`, `),ut=e=>Object.entries({...e.variations,...e.weight!==void 0&&{wght:e.weight},...e.opticalSize?.mode===`fixed`&&{opsz:e.opticalSize.value}}).toSorted(([e],[t])=>e.localeCompare(t,`en`,{caseFirst:`upper`})).map(([e,t])=>`${JSON.stringify(e)} ${String(t)}`).join(`, `),dt=e=>{let t=Object.entries(e??{}).toSorted(([e],[t])=>e.localeCompare(t,`en`)).map(([e,t])=>`${JSON.stringify(e)} ${String(t)}`).join(`, `);return t===``?`normal`:t},ft=e=>e.mode===`normal`?`normal`:e.mode===`percent`?String(e.value/100):e.value;function pt(e){return{...e.lineHeight!==void 0&&{"line-height":ft(e.lineHeight)},...e.letterSpacing!==void 0&&{"letter-spacing":typeof e.letterSpacing==`number`?e.letterSpacing:`${String(e.letterSpacing.value/100)}em`}}}const D=e=>e===void 0?`auto`:typeof e==`number`?e:e.mode===`font-default`?`from-font`:`${String(e.value)}%`,mt=e=>({"text-decoration-line":e.line,"text-decoration-style":e.style,"text-decoration-color":e.color===void 0?`currentColor`:it(e.color),"text-decoration-thickness":D(e.thickness),"text-underline-offset":D(e.offset),"text-decoration-skip-ink":e.skipInk??`auto`}),ht=e=>`${JSON.stringify(e)}\n`,gt=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=ht(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()]:[]}},_t=(e,t)=>{let n=gt(t);return[...e.flatMap(e=>n.add(e)),...n.drain()]},O=[`recording.start`,`recording.appendChunk`,`recording.complete`],vt=e=>async t=>{let n=Ee.parse(await e.mutate(O[0],{sourceUrl:t.sourceUrl,viewport:t.viewport,pageTitle:t.pageTitle,audio:null})),r=n.upload;try{let i=_t(t.entries,8388608);for(let[t,a]of i.entries()){let i=new TextEncoder().encode(a.body),o=await e.upload({url:r.url,headers:r.headers,body:i});r=c.parse(await e.mutate(O[1],{recordingId:n.recordingId,index:t,firstEventMs:a.firstEventMs,lastEventMs:a.lastEventMs,eventCount:a.eventCount,continues:a.continues,bytes:i.byteLength,etag:o})).upload}let a=Math.max(0,...t.entries.map(e=>e.atMs));return ie.parse(await e.mutate(O[2],{recordingId:n.recordingId,durationMs:a,viewport:t.viewport,sourceUrl:t.sourceUrl,interrupted:!1,...t.canvasId!==void 0&&{canvasId:t.canvasId},audioChunkCount:0,hasRecoverableBytes:!1}))}catch{throw new f(`Recording ${n.recordingId} began, but not every chunk was committed.`,`Run 'enhance recording discard --recording-id ${n.recordingId}' to remove the incomplete attempt before retrying the fixture.`)}},k=[`screen.create`,`screen.complete`],yt=e=>async t=>{let n=s.parse(await e.mutate(k[0],{clientToken:t.clientToken,provenance:t.provenance,route:t.route,pageTitle:t.pageTitle,viewport:t.viewport,bytes:t.body.byteLength}));try{let r=await e.upload({url:n.upload.url,headers:n.upload.headers,body:t.body}),i=o.parse(await e.mutate(k[1],{screenId:n.screenId,etag:r}));return{screenId:i.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:i.storedBytes}}catch{throw new f(`Screen ${n.screenId} was reserved, but its upload did not complete.`,`Retry 'enhance fixture screen' with the same --client-token ${t.clientToken}.`)}},A=[`organisation.create`,`canvas.create`,`screen.create`,`screen.complete`,`canvas.document.get`,`canvas.document.save`],bt=(t,n)=>async r=>{let i=re.parse(await t.mutate(A[0],{name:r.organisationName})).organisation,a=ve.parse(await t.mutate(A[1],{title:r.canvasTitle,organisationId:i.id,sourceUrl:null}));try{let o=[];for(let e of r.screens)o.push(await n(e));let s=g.parse(await t.query(A[4],{canvasId:a.id})),c=e();for(let[e,t]of o.entries())c=de(c,{id:`fixture-screen-${String(e+1)}`,label:`Fixture screen ${String(e+1)}`,screenId:t.screenId,viewport:r.screens[e]?.viewport??{width:1440,height:900},at:{x:48+e*48,y:48+e*48}});let l=le.parse(await t.mutate(A[5],{canvasId:a.id,baseVersion:s.version,document:c,screenIds:o.map(e=>e.screenId)}));if(l.outcome===`conflict`)throw new f(`World canvas ${a.id} was created, but another writer changed its document.`,`Read 'enhance canvas document get --canvas-id ${a.id}' before adding the screens.`);return{organisationId:i.id,canvasId:a.id,screenIds:o.map(e=>e.screenId),documentVersion:l.version}}catch(e){throw e instanceof f?e:new f(`Organisation ${i.id} and canvas ${a.id} exist, but the world is incomplete.`,`Inspect 'enhance canvas get --canvas-id ${a.id}' before retrying any missing steps.`)}},xt=async(e,t)=>{if(e!==void 0&&e!==``)return e.trim();if(S.stdin.isTTY)throw new l(`BAD_REQUEST`,`A token is required and interactive prompting is disabled.`,`Pass '--token <token>' or pipe one line to '${t}'.`);let n=Ge({input:S.stdin,crlfDelay:1/0});for await(let e of n){n.close();let t=e.trim();if(t!==``)return t;break}throw new l(`BAD_REQUEST`,`A token is required.`,`Pass '--token <token>' or pipe one line to '${t}'.`)},St=async e=>{if(e!==void 0)return e.trim();if(S.stdin.isTTY)return null;let t=Ge({input:S.stdin,crlfDelay:1/0});for await(let e of t){t.close();let n=e.trim();return n===``?null:n}return null},Ct=(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 St(e.token);if(r!==null){n.result(await t.loginWithToken(r));return}n.result(await t.loginWithBrowser({label:`CLI on ${Ue()}`.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())})},j=1e3,wt=x.coerce.number().int().positive(),Tt=x.coerce.number().min(.1).max(4),Et=x.uuid(),Dt=x.union([x.string(),x.number(),x.null()]),Ot=x.record(x.string(),Dt),kt=x.array(x.object({nodeId:x.string().min(1).max(200),textContent:x.string().max(1e5)})).min(1).max(j),At=x.array(x.object({nodeId:x.string().min(1).max(200),name:x.string().max(500)})).min(1).max(j),jt=x.array(x.object({nodeIds:x.array(x.string().min(1).max(200)).min(1).max(100),styles:Ot})).min(1).max(100),Mt=x.array(x.object({id:x.string().min(1).max(200),parentId:x.string().min(1).max(200).optional()})).min(1).max(100),Nt=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),Pt=x.array(x.string().min(1).max(200)).min(1).max(j),Ft=x.coerce.number().int().min(0).max(20),It=x.uuid().nullable(),M=(e,t,n)=>{let r=e.safeParse(t);if(r.success)return r.data;throw new l(`BAD_REQUEST`,`${n} is invalid.`,`Run the command with --help.`)},N=e=>M(wt,e,`--base-version`),P=(e,t,n)=>{let r=It.safeParse(t??null);if(!r.success)throw new l(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying the exact same command.`);e.mutationKey.select(r.data,n)},Lt=(e,t)=>e.mutationKey.current(`canvas.applyOperations`,{purpose:t}),Rt=async(e,r,i,a)=>{P(e,r.clientToken,!1);let o=t(r.canvas),s=N(r.baseVersion);return o.nodeIds.length>0&&n(o,await b(e,o.canvasId,s),a),ke(e.remote).execute({canvasId:o.canvasId,mutationId:Lt(e,i),baseVersion:s,operations:[...a]})},F=async(e,n,r,i)=>{P(e,n.clientToken,!1);let a=t(n.canvas);return je(e.remote).execute({...a,baseVersion:N(n.baseVersion),mutationId:Lt(e,`canvas.edit`),edits:r,...i!==void 0&&{idPrefix:i}})},zt=x.array(pe).min(1).max(xe),Bt=e=>{if(!e.startsWith(`@`))return e;let t=e.slice(1);if(t===``)throw new l(`BAD_REQUEST`,`--operations @ must name a JSON file.`,`Pass --operations @/absolute/path/layout.json or an inline JSON array.`);let n=T.resolve(t);try{let e=Ze(n);if(!e.isFile()||e.size>1048576)throw Error(`invalid size`);return C(n,`utf8`)}catch{throw new l(`BAD_REQUEST`,`Could not read a bounded operations file at ${n}.`,`Use a regular JSON file no larger than 1 MiB.`)}},Vt=e=>{try{return JSON.parse(Bt(e))}catch(e){throw e instanceof l?e:new l(`BAD_REQUEST`,`--operations must be one valid JSON array.`,`Pass inline JSON or @/absolute/path/layout.json; run 'enhance canvas apply --help' for examples.`)}},Ht=e=>{let t=Vt(e),n=zt.safeParse(t);if(!n.success){let e=n.error.issues[0];throw new l(`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 n.data},I=(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},Ut=x.coerce.number().int().positive(),Wt=e=>{let t=Ut.safeParse(e);if(t.success)return t.data;throw new l(`BAD_REQUEST`,`--base-version is invalid.`,`Run 'enhance canvas apply --help'.`)},Gt=(e,t)=>{let n=x.uuid().nullable().safeParse(t??null);if(!n.success)throw new l(`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(n.data,!1),e.mutationKey.current(`canvas.applyOperations`,{})},Kt=(e,r)=>{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, editText, setBox, setLabel, setVisibility, setLocked, setConstraints, setStyles, setAppearance, setLayout, patchTypography, setTypography, patchAdditionalStyles, setAdditionalStyles, setProps, setParentage, move, remove.`,`Use editText for revision-aware character or range changes. setText replaces the whole text and is rejected if it conflicts with a newer text edit.`,`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=>{Gt(r,e.clientToken);let i=t(e.canvas),a=Wt(e.baseVersion),o=Ht(e.operations);i.nodeIds.length>0&&n(i,await b(r,i.canvasId,a),o);let s=await r.invocation.invoke({capability:I(r.catalog(),`canvas.apply`),arguments:{canvasId:i.canvasId,baseVersion:a,operations:[...o]},clientToken:e.clientToken??null});r.output.result(s)})},qt=e=>{try{return JSON.parse(e)}catch{return}},L=e=>{if(e===void 0)return null;let t=Te.safeParse(qt(e));if(t.success)return t.data;throw new l(`BAD_REQUEST`,`--bounds must be a positive world rectangle.`,`Pass JSON with x, y, width and height.`)},R=e=>e===void 0?[]:e.split(`,`).map(e=>e.trim()).filter(e=>e!==``).slice(0,100),Jt=(e,t)=>{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 n=se.safeParse(e.phase);if(!n.success)throw new l(`BAD_REQUEST`,`--phase is invalid.`,`Use reading, writing, creating, deleting, or rendering.`);let r=p(e.canvas),i=_e.parse(await t.remote.mutate(`canvas.realtime.activity.begin`,{canvasId:r,phase:n.data,nodeIds:R(e.nodeIds),bounds:L(e.bounds)}));t.output.result({...i,next:[`enhance canvas work update --canvas ${r} --activity-id ${i.activityId} --phase ${n.data}`,`enhance canvas finish-working-on-nodes --canvas ${r} --activity-id ${i.activityId}`]})})},Yt=(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(_e.parse(await t.remote.mutate(`canvas.realtime.activity.renew`,{canvasId:p(e.canvas),activityId:Et.parse(e.activityId),phase:se.parse(e.phase),nodeIds:R(e.nodeIds),bounds:L(e.bounds)})))})},Xt=(e,t)=>{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 Ae(t.remote).finish(p(e.canvas),Et.parse(e.activityId)))throw new l(`NOT_FOUND`,`The activity could not be finished.`,`It may already have expired; run canvas work begin for new work.`);t.output.result({ended:!0,activityId:e.activityId})})},Zt=(e,t)=>{let n=e.command(`work`).description(`Manage visible agent activity.`);Jt(n,t),Yt(n,t),Xt(e,t)},z=(e,t,n)=>{if(!e.startsWith(`@`))return e;let r=e.slice(1);if(r===``)throw new l(`BAD_REQUEST`,`${n} @ must name a file.`,`Pass ${n} @/absolute/path/to/file or an inline value.`);let i=T.resolve(r);try{let e=Ze(i);if(!e.isFile()||e.size>t)throw Error(`invalid size`);return C(i,`utf8`)}catch{throw new l(`BAD_REQUEST`,`Could not read a bounded file at ${i}.`,`Use a regular UTF-8 file no larger than ${String(t)} bytes.`)}},B=(e,t,n)=>{let r=(()=>{try{return JSON.parse(z(e,1048576,n))}catch(e){throw e instanceof l?e:new l(`BAD_REQUEST`,`${n} must be valid JSON.`,`Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`)}})(),i=t.safeParse(r);if(i.success)return i.data;let a=i.error.issues[0];throw new l(`BAD_REQUEST`,`${n} is invalid${a===void 0||a.path.length===0?``:` at ${a.path.join(`.`)}`}.`,a?.message??`Correct the JSON shape and retry.`)},Qt=(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=B(e.updates,kt,`--updates`).map(e=>({kind:`set_text`,nodeId:e.nodeId,text:e.textContent}));t.output.result(await F(t,e,n))})},$t=(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=B(e.updates,At,`--updates`).map(e=>({kind:`rename`,nodeId:e.nodeId,name:e.name}));t.output.result(await F(t,e,n))})},en=(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=B(e.nodeIds,Pt,`--node-ids`);t.output.result(await Rt(t,e,`delete-nodes`,n.map(e=>({op:`remove`,nodeId:e}))))})},tn=(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=B(e.updates,jt,`--updates`);t.output.result(await F(t,e,n.map(e=>({kind:`set_styles`,...e}))))})},nn=(e,t)=>{e.command(`edit`).description(`Apply an atomic canvas edit batch.`).requiredOption(`--canvas <url-or-id>`,`Canvas or selection URL, or canvas UUID.`).requiredOption(`--base-version <integer>`,`Canvas version to edit; use the previous write result to continue.`).requiredOption(`--edits <json-or-@path>`,`Array of edits with kind set_text, set_styles, rename, duplicate or move.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).addHelpText(`after`,`
5
5
  Edit shapes (combine related edits in one array):
6
6
  {"kind":"set_text","nodeId":"title","text":"Your day"}
7
7
  {"kind":"set_styles","nodeIds":["button"],"styles":{"background":"#0f766e"}}
@@ -10,14 +10,16 @@ Edit shapes (combine related edits in one array):
10
10
  {"kind":"move","nodeId":"card","destination":{"kind":"before","nodeId":"other"}}
11
11
  Move destinations also accept {"kind":"after","nodeId":"other"} or {"kind":"parent","parentId":"screen","index":0}.
12
12
  Use input-version IDs. Duplicate mappings are returned for a subsequent call.
13
- `).action(async e=>{let n=V(e.edits,ae,`--edits`);t.output.result(await L(t,e,n))})},Vt=(e,t)=>{Bt(e,t),It(e,t),Lt(e,t),Rt(e,t),zt(e,t)},Ht=new Set([`flex-grow`,`flex-shrink`,`order`,`aspect-ratio`]),H=e=>e===`start`||e===`end`?`flex-${e}`:e,U=e=>{let t=`${String(e.ratio*100)}%`,n=e.offset??0;return n===0?t:`calc(${t} ${n<0?`-`:`+`} ${String(Math.abs(n))}px)`},Ut=(e,t)=>{let n=e[t],r=e[t===`min`?`minParent`:`maxParent`];if(r===void 0)return n;let i=U(r);return n===void 0?i:`${t===`min`?`max`:`min`}(${String(n)}px, ${i})`},Wt=(e,t,n)=>{if(t===void 0)return{};if(t.mode===`fixed`)return{[e]:t.value};let r={};for(let n of[`min`,`max`]){let i=Ut(t,n);i!==void 0&&(r[`${n}-${e}`]=i)}if(t.mode===`hug`)return{[e]:`max-content`,...r};let i=t.offset??0,a=i===0?`100%`:`calc(100% + ${String(i)}px)`;return{[e]:n&&i===0?`auto`:a,...r}},Gt=(e,t)=>{let n=e.box;if(n===void 0)return{};let r=f(e),i=e.layout?.position??x(e,`position`),a=i===void 0||[`absolute`,`fixed`].includes(i),o=e=>(e===`horizontal`?[`left`,`right`,`inset`,`inset-inline`,`inset-inline-start`,`inset-inline-end`]:[`top`,`bottom`,`inset`,`inset-block`,`inset-block-start`,`inset-block-end`]).some(e=>r[e]!==void 0),c=n=>s(e,n,t).some(t=>r[t]!==void 0||e.additionalStyles?.declarations.some(e=>e.property.toLowerCase()===t)===!0);return{...r[`box-sizing`]===void 0&&{"box-sizing":`border-box`},...a&&r.position===void 0&&{position:`absolute`},...a&&!o(`horizontal`)&&{left:n.x},...a&&!o(`vertical`)&&{top:n.y},...a&&e.layout?.horizontal===void 0&&!c(`horizontal`)&&{width:n.width},...a&&e.layout?.vertical===void 0&&!c(`vertical`)&&{height:n.height}}},Kt=e=>{if(e.gridColumns!==void 0)return`repeat(${String(e.gridColumns)}, minmax(0, 1fr))`;if(e.gridAutoRepeat!==void 0)return`repeat(${e.gridAutoRepeat.mode}, minmax(${String(e.gridAutoRepeat.minimum)}px, 1fr))`},qt=e=>{let t=e.layout,n=t?.container,r=t?.clipContent===void 0?{}:{overflow:t.clipContent?`hidden`:`visible`};if(n===void 0)return r;let i=Kt(n),a=n.rowGap??n.gap,o=n.columnGap??n.gap;return{...r,...x(e,`display`)===void 0&&{display:i===void 0?`flex`:`grid`},...i!==void 0&&{"grid-template-columns":i},...n.direction!==void 0&&{"flex-direction":n.direction},...n.wrap!==void 0&&{"flex-wrap":n.wrap},...n.alignItems!==void 0&&{"align-items":H(n.alignItems)},...n.alignContent!==void 0&&{"align-content":H(n.alignContent)},...n.justifyContent!==void 0&&{"justify-content":H(n.justifyContent)},...a!==void 0&&{"row-gap":a},...o!==void 0&&{"column-gap":o},...Object.fromEntries(Object.entries(n.padding??{}).map(([e,t])=>[`padding-${e}`,t]))}},Jt=(e,t)=>{let n=e.layout??{},r=n=>t!==void 0&&x(e,n)===void 0,i=n.flexBasis??(t?.mode===`fill`?0:`auto`);return{...(r(`flex-basis`)||n.flexBasis!==void 0)&&{"flex-basis":typeof i==`object`?U(i):i},...(r(`flex-grow`)||n.flexGrow!==void 0)&&{"flex-grow":n.flexGrow??+(t?.mode===`fill`)},...(r(`flex-shrink`)||n.flexShrink!==void 0)&&{"flex-shrink":n.flexShrink??+(t?.mode===`fill`)},...n.flowOffset!==void 0&&{left:n.flowOffset.x,top:n.flowOffset.y},...n.order!==void 0&&{order:n.order},...Object.fromEntries(Object.entries(n.margin??{}).map(([e,t])=>[`margin-${e}`,t]))}},Yt=e=>{let t=[...e.rotation===void 0||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(` `)}},Xt=(e,t)=>e.alignSelf===void 0||e.alignSelf===`auto`?t?.mode===`fill`?`stretch`:void 0:H(e.alignSelf),Zt=(e,t)=>{if(t===void 0)return{};let n=e.layout?.[t],r=t===`horizontal`?`min-width`:`min-height`;return n?.mode!==`fill`||n.min!==void 0||n.minParent!==void 0||f(e)[r]!==void 0?{}:{[r]:0}},Qt=(e,t)=>{let n=e.layout;if(n===void 0)return{};let r=t?.relationships[e.id]?.parentId,i=a(r===void 0?void 0:t?.nodes[r],t),o=n.position??x(e,`position`),s=o===`flow`||o!==`absolute`&&o!==`fixed`&&(o!==void 0||e.box===void 0),c=i===`horizontal`?n.horizontal:n.vertical,l=i===`horizontal`?n.vertical:n.horizontal,u=Xt(n,l);return{...n.position!==void 0&&{position:s?`relative`:`absolute`},...Wt(`width`,n.horizontal,s&&(i===`horizontal`||u===`stretch`)),...Wt(`height`,n.vertical,s&&(i===`vertical`||u===`stretch`)),...s&&i!==void 0&&Jt(e,c),...s&&u!==void 0&&{"align-self":u},...s&&Zt(e,i),...u===`stretch`&&l?.mode===`hug`&&i!==void 0&&{[i===`horizontal`?`height`:`width`]:`auto`},...n.aspectRatio!==void 0&&{"aspect-ratio":n.aspectRatio},...Yt(n)}},$t=(e,t)=>Object.fromEntries(Object.entries({...Gt(e,t),...te(e,{...Qt(e,t),...qt(e)})}).map(([e,t])=>[e,typeof t==`number`&&!Ht.has(e)?`${String(t)}px`:t])),W=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)})`,G=e=>{if(!e.visible)return null;if(e.kind===`solid`)return W(e.color);if(e.kind===`image`)return`url(${JSON.stringify(e.assetId)})`;let t=e.stops.map(e=>`${W(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})`},en=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})`},tn=e=>e?.flatMap(e=>{let t=G(e);return t===null?[]:[t]})??[],nn=e=>{if(e?.visible!==!0)return{};let t=G(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}}},rn=e=>{if(e?.visible!==!0)return{};let t=G(e.paint);return{"outline-width":`${String(e.width)}px`,"outline-offset":`${String(e.offset)}px`,"outline-style":e.style,...t!==null&&{"outline-color":t}}},an=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 ${W(e.color)}`),n=e.filters?.filter(e=>e.visible).map(en),r=e.backdropFilters?.filter(e=>e.visible).map(en);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(` `)}}},on=e=>{if(e===void 0)return{};let t=tn(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(` `)},...nn(e.border),...rn(e.outline),...an(e)}},sn=e=>{let t={},n=e.lineHeight;n!==void 0&&(t[`line-height`]=n.mode===`normal`?`normal`:`${String(n.value)}${n.mode===`percent`?`%`:`px`}`);let r=e.letterSpacing;return r!==void 0&&(t[`letter-spacing`]=typeof r==`number`?`${String(r)}px`:`${String(r.value/100)}em`),t},cn=e=>{let t=e.typography??{},n={},r=String(f(e)[`font-family`]??`sans-serif`).split(`,`);(t.family!==void 0||t.fallbackFamilies!==void 0)&&(n[`font-family`]=[t.family??r[0],...t.fallbackFamilies??r.slice(1)].join(`, `)),t.size!==void 0&&(n[`font-size`]=`${String(t.size)}px`);for(let[e,r]of[[`weight`,`font-weight`],[`style`,`font-style`],[`align`,`text-align`],[`transform`,`text-transform`]]){let i=t[e];i!==void 0&&(n[r]=i)}return t.decoration!==void 0&&(n[`text-decoration-line`]=t.decoration.line,n[`text-decoration-style`]=t.decoration.style),t.wrapping!==void 0&&(n[`white-space`]=t.wrapping===`wrap`?`normal`:t.wrapping),{...n,...sn(t)}},ln=(e,t)=>({...Object.fromEntries(Object.entries(f(e)).filter(([t])=>e.layout?.clipContent===void 0||![`overflow`,`overflow-x`,`overflow-y`].includes(t))),...cn(e),...on(e.appearance),...$t(e,t),...e.visible===!1&&{display:`none`}}),un=(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),dn=(e,t)=>{let n=e.nodes[t];if(n===void 0)throw new d(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`);return n},K=(e,t)=>{let n=e.props?.[t];return typeof n==`string`?n:``},fn=e=>`{${JSON.stringify(e)}}`,pn=(e,t,n,r)=>{let i=dn(e,t),a=` `.repeat(n),o=[`data-node-id=${JSON.stringify(i.id)}`,`data-name=${JSON.stringify(i.label)}`,`style={${JSON.stringify(ln(i,e))}}`];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`?fn(K(i,`text`)):``,l=(n>=r?[]:un(e,t)).map(t=>pn(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(`
14
- `)},mn=(e,t,n)=>pn(e,t,0,n),hn=(e,t)=>t.map(t=>{let n=dn(e,t);return{nodeId:t,name:n.label,component:n.component,box:n.box,css:ln(n,e),layout:n.layout,appearance:n.appearance,typography:n.typography}}),gn={topic:`canvas-agent-authoring`,workflow:[`Keep the complete selection link as --canvas; only selected nodes and descendants are in scope.`,`Unknown state: canvas inspect. When nodeCount=0, use target root and its version to create a populated screen using write-html --review none. No blank pre-render or empty shell.`,`Multiple screens: publish each populated screen before authoring the next so users see progress. Prepare only what that screen needs; do not prepare the whole set before the first write.`,`Existing content: read only missing subtree structure or ids. Reuse useful context and product styles.`,`Batch related text, style, rename, duplicate and move changes with canvas edit --edits. Existing focused commands also work.`,`Use the version from the latest successful read or write as --base-version. After a conflict, reread and recompute the requested edit.`,`Render the affected screen when ready for review and inspect the PNG. Repeat after changes or a concrete discrepancy.`],html:{modes:[`insert-children`,`replace`],rules:[`Use inline concrete CSS; flex, padding and gap. Avoid margin, grid, tables and inline layout.`,`Give screen rows, cards and buttons explicit dimensions; avoid relying on implicit stretch. Use block frames for colored badges.`,`Name meaningful groups with layer-name; include content and structure together.`,`Styled text controls become frames with editable text children.`,`Scripts, event handlers, embedded documents, executable URLs and CSS imports are rejected.`]},completion:[`Natural hierarchy with the fewest useful editable primitives.`,`The committed version and affected ids match the request.`,`Inspect the final PNG for hierarchy, alignment, clipping and overflow.`,`Keep text, layout and appearance editable in the ordinary inspector.`]},_n=async(e,t)=>{let n=v.parse(await e.remote.query(`canvas.document.get`,{canvasId:t}));return{held:n,document:r.parse(n.document)}},vn=(e,n)=>{e.command(`guide`).description(`Agent design workflow.`).action(()=>{n.output.result(gn)}),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 r=t(e.canvas),i=r.canvasId,{held:a,document:s}=await _n(n,i);o(r,s,[e.nodeId]),n.output.result({canvasId:i,version:a.version,nodeId:e.nodeId,jsx:mn(s,e.nodeId,P(vt,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 r=t(e.canvas),i=r.canvasId,{held:a,document:s}=await _n(n,i),c=V(e.nodeIds,_t,`--node-ids`);o(r,s,c),n.output.result({canvasId:i,version:a.version,nodes:hn(s,c),warning:`These are authored CSS instructions, not measured browser dimensions. Use canvas render as the pixel authority.`})})},yn=(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=>{let n=await L(t,e,V(e.nodes,ht,`--nodes`).map(e=>({kind:`duplicate`,nodeIds:[e.id],...e.parentId!==void 0&&{parentId:e.parentId}})),e.idPrefix),{duplicatedNodes:r,...i}=n;t.output.result({...n,duplicatedNodes:r,apply:i})})},bn=(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=>{let n=await L(t,e,V(e.moves,gt,`--moves`).map(e=>({kind:`move`,nodeId:e.nodeId,destination:`before`in e?{kind:`before`,nodeId:e.before}:`after`in e?{kind:`after`,nodeId:e.after}:{kind:`parent`,parentId:e.parentId,...e.index!==void 0&&{index:e.index}}}))),{moves:r,affectedParents:i,...a}=n;t.output.result({...n,moves:r,affectedParents:i,apply:a})})},xn=(e,t)=>{yn(e,t),bn(e,t)},Sn=262144,Cn=e=>{let t=B(e,Sn,`--html`);if(Buffer.byteLength(t,`utf8`)>Sn)throw new d(`BAD_REQUEST`,`--html exceeds 262144 bytes.`,`Write one visual group at a time, as taught by canvas guide.`);return t},wn=new Set([`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`]),Tn=async(e,n)=>{if(![`insert-children`,`replace`].includes(n.mode))throw new d(`BAD_REQUEST`,`--mode must be insert-children or replace.`,`Choose one of the two documented modes.`);if(![`none`,`render`].includes(n.review))throw new d(`BAD_REQUEST`,`--review must be none or render.`,`Choose one of the documented review modes.`);I(e,n.clientToken,!0);let r=n.mode===`replace`?`replace`:`insert-children`,i=t(n.canvas),a=F(n.baseVersion);e.output.result(await e.invocation.invoke({capability:R(e.catalog(),`canvas.writeHtml`),arguments:{canvasId:i.canvasId,...i.nodeIds.length>0&&{selectionNodeIds:[...i.nodeIds]},targetNodeId:n.targetNodeId,mode:r,html:Cn(n.html),...n.idPrefix!==void 0&&{idPrefix:n.idPrefix},baseVersion:a,review:n.review,renderOutputPath:n.output??null,overwriteRender:n.force===!0,renderScale:P(ct,n.scale,`--scale`),renderTimeoutMs:P(st,n.timeoutMs,`--timeout-ms`)},clientToken:n.clientToken??null}))},En=(e,t)=>{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(`--review <mode>`,`none to return after commitment; render to include review pixels.`,`render`).option(`--id-prefix <prefix>`,`Fresh namespace for a new import/replacement; reuse only for an identical retry.`).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`,`
13
+ `).action(async e=>{let n=B(e.edits,ae,`--edits`);t.output.result(await F(t,e,n))})},rn=(e,t)=>{nn(e,t),Qt(e,t),$t(e,t),en(e,t),tn(e,t)},an=new Set([`flex-grow`,`flex-shrink`,`order`,`aspect-ratio`]),V=e=>e===`start`||e===`end`?`flex-${e}`:e,H=e=>{let t=`${String(e.ratio*100)}%`,n=e.offset??0;return n===0?t:`calc(${t} ${n<0?`-`:`+`} ${String(Math.abs(n))}px)`},on=(e,t)=>{let n=e[t],r=e[t===`min`?`minParent`:`maxParent`];if(r===void 0)return n;let i=H(r);return n===void 0?i:`${t===`min`?`max`:`min`}(${String(n)}px, ${i})`},sn=(e,t,n)=>{if(t===void 0)return{};if(t.mode===`fixed`)return{[e]:t.value};let r={};for(let n of[`min`,`max`]){let i=on(t,n);i!==void 0&&(r[`${n}-${e}`]=i)}if(t.mode===`hug`)return{[e]:`max-content`,...r};let i=t.offset??0,a=i===0?`100%`:`calc(100% + ${String(i)}px)`;return{[e]:n&&i===0?`auto`:a,...r}},cn=(e,t)=>{let n=e.box;if(n===void 0)return{};let i=a(e),o=e.layout?.position??u(e,`position`),s=o===void 0||[`absolute`,`fixed`].includes(o),c=e=>(e===`horizontal`?[`left`,`right`,`inset`,`inset-inline`,`inset-inline-start`,`inset-inline-end`]:[`top`,`bottom`,`inset`,`inset-block`,`inset-block-start`,`inset-block-end`]).some(e=>i[e]!==void 0),l=n=>r(e,n,t).some(t=>i[t]!==void 0||e.additionalStyles?.declarations.some(e=>e.property.toLowerCase()===t)===!0);return{...i[`box-sizing`]===void 0&&{"box-sizing":`border-box`},...s&&i.position===void 0&&{position:`absolute`},...s&&!c(`horizontal`)&&{left:n.x},...s&&!c(`vertical`)&&{top:n.y},...s&&e.layout?.horizontal===void 0&&!l(`horizontal`)&&{width:n.width},...s&&e.layout?.vertical===void 0&&!l(`vertical`)&&{height:n.height}}},ln=e=>{if(e.gridColumns!==void 0)return`repeat(${String(e.gridColumns)}, minmax(0, 1fr))`;if(e.gridAutoRepeat!==void 0)return`repeat(${e.gridAutoRepeat.mode}, minmax(${String(e.gridAutoRepeat.minimum)}px, 1fr))`},un=e=>{let t=e.layout,n=t?.container,r=t?.clipContent===void 0?{}:{overflow:t.clipContent?`hidden`:`visible`};if(n===void 0)return r;let i=ln(n),a=n.rowGap??n.gap,o=n.columnGap??n.gap;return{...r,...u(e,`display`)===void 0&&{display:i===void 0?`flex`:`grid`},...i!==void 0&&{"grid-template-columns":i},...n.direction!==void 0&&{"flex-direction":n.direction},...n.wrap!==void 0&&{"flex-wrap":n.wrap},...n.alignItems!==void 0&&{"align-items":V(n.alignItems)},...n.alignContent!==void 0&&{"align-content":V(n.alignContent)},...n.justifyContent!==void 0&&{"justify-content":V(n.justifyContent)},...a!==void 0&&{"row-gap":a},...o!==void 0&&{"column-gap":o},...Object.fromEntries(Object.entries(n.padding??{}).map(([e,t])=>[`padding-${e}`,t]))}},dn=(e,t)=>{let n=e.layout??{},r=n=>t!==void 0&&u(e,n)===void 0,i=n.flexBasis??(t?.mode===`fill`?0:`auto`);return{...(r(`flex-basis`)||n.flexBasis!==void 0)&&{"flex-basis":typeof i==`object`?H(i):i},...(r(`flex-grow`)||n.flexGrow!==void 0)&&{"flex-grow":n.flexGrow??+(t?.mode===`fill`)},...(r(`flex-shrink`)||n.flexShrink!==void 0)&&{"flex-shrink":n.flexShrink??+(t?.mode===`fill`)},...n.flowOffset!==void 0&&{left:n.flowOffset.x,top:n.flowOffset.y},...n.order!==void 0&&{order:n.order},...Object.fromEntries(Object.entries(n.margin??{}).map(([e,t])=>[`margin-${e}`,t]))}},fn=e=>{let t=[...e.rotation===void 0||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(` `)}},pn=(e,t)=>e.alignSelf===void 0||e.alignSelf===`auto`?t?.mode===`fill`?`stretch`:void 0:V(e.alignSelf),mn=(e,t)=>{if(t===void 0)return{};let n=e.layout?.[t],r=t===`horizontal`?`min-width`:`min-height`;return n?.mode!==`fill`||n.min!==void 0||n.minParent!==void 0||a(e)[r]!==void 0?{}:{[r]:0}},hn=(e,t)=>{let n=e.layout;if(n===void 0)return{};let r=t?.relationships[e.id]?.parentId,i=te(r===void 0?void 0:t?.nodes[r],t),a=n.position??u(e,`position`),o=a===`flow`||a!==`absolute`&&a!==`fixed`&&(a!==void 0||e.box===void 0),s=i===`horizontal`?n.horizontal:n.vertical,c=i===`horizontal`?n.vertical:n.horizontal,l=pn(n,c);return{...n.position!==void 0&&{position:o?`relative`:`absolute`},...sn(`width`,n.horizontal,o&&(i===`horizontal`||l===`stretch`)),...sn(`height`,n.vertical,o&&(i===`vertical`||l===`stretch`)),...o&&i!==void 0&&dn(e,s),...o&&l!==void 0&&{"align-self":l},...o&&mn(e,i),...l===`stretch`&&c?.mode===`hug`&&i!==void 0&&{[i===`horizontal`?`height`:`width`]:`auto`},...n.aspectRatio!==void 0&&{"aspect-ratio":n.aspectRatio},...fn(n)}},gn=(e,t)=>Object.fromEntries(Object.entries({...cn(e,t),...ye(e,{...hn(e,t),...un(e)})}).map(([e,t])=>[e,typeof t==`number`&&!an.has(e)?`${String(t)}px`: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})`},_n=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})`},vn=e=>e?.flatMap(e=>{let t=W(e);return t===null?[]:[t]})??[],yn=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}}},bn=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}}},xn=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(_n),r=e.backdropFilters?.filter(e=>e.visible).map(_n);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=vn(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(` `)},...yn(e.border),...bn(e.outline),...xn(e)}},Cn=(e,t)=>{let n={},r=a(e),i=String(r[`font-family`]??`sans-serif`).split(`,`).map(e=>e.trim().replaceAll(/^(?:"|')|(?:"|')$/gu,``));if(t.family!==void 0||t.fallbackFamilies!==void 0){let[e=`sans-serif`,...r]=i;n[`font-family`]=lt({family:t.family??e,fallbackFamilies:t.fallbackFamilies??r})}return n},wn=e=>{let t={};return e.size!==void 0&&(t[`font-size`]=`${String(e.size)}px`),e.weight!==void 0&&(t[`font-weight`]=e.weight),e.style!==void 0&&(t[`font-style`]=e.style),(e.variations!==void 0||e.opticalSize!==void 0)&&(t[`font-variation-settings`]=ut({...e.weight!==void 0&&{weight:e.weight},...e.variations!==void 0&&{variations:e.variations},...e.opticalSize!==void 0&&{opticalSize:e.opticalSize}})),e.opticalSize!==void 0&&(t[`font-optical-sizing`]=e.opticalSize.mode===`auto`?`auto`:`none`),e.features!==void 0&&(t[`font-feature-settings`]=dt(e.features)),Object.assign(t,pt(e)),t},Tn=e=>{let t={};return e.align!==void 0&&(t[`text-align`]=e.align),e.transform!==void 0&&(t[`text-transform`]=e.transform),Object.assign(t,at(e.direction)),e.paragraphIndent!==void 0&&(t[`text-indent`]=`${String(e.paragraphIndent)}px each-line`),e.hangingPunctuation!==void 0&&(t[`hanging-punctuation`]=`none`),t},En=e=>{let t={};return e.verticalAlign!==void 0&&e.verticalAlign!==`top`&&(t.display=`flex`,t[`flex-direction`]=`column`,t[`justify-content`]=e.verticalAlign===`middle`?`center`:`flex-end`),e.verticalTrim!==void 0&&(t[`text-box-trim`]=e.verticalTrim===`cap-height`?`trim-both`:`none`,t[`text-box-edge`]=`cap alphabetic`),t},Dn=e=>{let t={};return e.decoration!==void 0&&Object.assign(t,mt(e.decoration)),e.wrapping!==void 0&&(t[`white-space`]=e.wrapping===`wrap`?`normal`:e.wrapping),e.wrapStyle!==void 0&&(t[`text-wrap-style`]=e.wrapStyle),t},On=e=>{let t=e.typography??{};return{...Cn(e,t),...wn(t),...Tn(t),...En(t),...Dn(t)}},kn=(e,t)=>({...Object.fromEntries(Object.entries(a(e)).filter(([t])=>e.layout?.clipContent===void 0||![`overflow`,`overflow-x`,`overflow-y`].includes(t))),...On(e),...Sn(e.appearance),...gn(e,t),...e.visible===!1&&{display:`none`}}),An=(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,t)=>{let n=e.nodes[t];if(n===void 0)throw new l(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`);return n},Mn=(e,t)=>{let n=e.props?.[t];return typeof n==`string`?n:``},Nn=e=>`{${JSON.stringify(e)}}`,G=(e,t)=>e===void 0?[]:[t(e)],Pn=(e,t)=>{let n=` `.repeat(t),r=`${n}${Nn(e.text)}`;return e.sourcePath===void 0?r:`${n}<span data-source-path=${JSON.stringify(e.sourcePath)}>${Nn(e.text)}</span>`},Fn=(e,t)=>{let n=` `.repeat(t),r=G(e.sourcePath,e=>`data-source-path=${JSON.stringify(e)}`).join(``);return`${n}<br data-text-break="${e.soft===!0?`line`:`paragraph`}"${r===``?``:` ${r}`} />`},In=(e,t)=>{let n=` `.repeat(t),r=[...G(e.sourcePath,e=>`data-source-path=${JSON.stringify(e)}`),...G(e.href,e=>`href={${JSON.stringify(e)}}`),...G(e.href,()=>`rel="noreferrer" target="_blank"`),...G(Object.keys(e.styles).length===0?void 0:e.styles,e=>`style={${JSON.stringify(e)}}`),...G(e.textStyle,e=>`data-text-style={${JSON.stringify(e)}}`),...G(e.paragraph,e=>`data-text-paragraph={${JSON.stringify(e)}}`),...G(e.fills,e=>`data-text-fills={${JSON.stringify(e)}}`),...G(e.paragraphSpacing,e=>`data-paragraph-spacing=${JSON.stringify(e)}`),...G(e.paragraphIndent,e=>`data-paragraph-indent=${JSON.stringify(e)}`),...G(e.listSpacing,e=>`data-list-spacing=${JSON.stringify(e)}`),...G(e.hangingPunctuation,e=>`data-hanging-punctuation=${JSON.stringify(e)}`),...G(e.verticalTrim,e=>`data-vertical-trim=${JSON.stringify(e)}`),...G(e.wrapStyle,e=>`data-wrap-style=${JSON.stringify(e)}`)],i=e.href===void 0?`span`:`a`,a=e.children.map(e=>Ln(e,t+1));return[`${n}<${i}${r.length===0?``:` ${r.join(` `)}`}>`,...a,`${n}</${i}>`].join(`
14
+ `)},Ln=(e,t)=>e.kind===`text`?Pn(e,t):e.kind===`break`?Fn(e,t):In(e,t),Rn=(e,t)=>Ce(e).map(e=>Ln(e,t)).join(`
15
+ `),zn=(e,t,n,r)=>{let i=jn(e,t),a=` `.repeat(n),o=[`data-node-id=${JSON.stringify(i.id)}`,`data-name=${JSON.stringify(i.label)}`,`style={${JSON.stringify(kn(i,e))}}`];if(i.locked===!0&&o.push(`data-locked="true"`),i.component===`image`)return`${a}<img ${o.join(` `)} alt=${JSON.stringify(Mn(i,`alt`))} src=${JSON.stringify(Mn(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`?Rn(i,n+1):``,l=(n>=r?[]:An(e,t)).map(t=>zn(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(`
16
+ `)},Bn=(e,t,n)=>zn(e,t,0,n),Vn=(e,t)=>t.map(t=>{let n=jn(e,t);return{nodeId:t,name:n.label,component:n.component,box:n.box,css:kn(n,e),layout:n.layout,appearance:n.appearance,typography:n.typography}}),Hn={topic:`canvas-agent-authoring`,workflow:[`Keep the complete selection link as --canvas; only selected nodes and descendants are in scope.`,`Unknown state: canvas inspect. When nodeCount=0, use target root and its version to create a populated screen using write-html --review none. No blank pre-render or empty shell.`,`Multiple screens: publish each populated screen before authoring the next so users see progress. Prepare only what that screen needs; do not prepare the whole set before the first write.`,`Existing content: read only missing subtree structure or ids. Reuse useful context and product styles.`,`Batch related text, style, rename, duplicate and move changes with canvas edit --edits. Existing focused commands also work.`,`Use the version from the latest successful read or write as --base-version. After a conflict, reread and recompute the requested edit.`,`Render the affected screen when ready for review and inspect the PNG. Repeat after changes or a concrete discrepancy.`],html:{modes:[`insert-children`,`replace`],rules:[`Use inline concrete CSS; flex, padding and gap. Avoid margin, grid, tables and inline layout.`,`Give screen rows, cards and buttons explicit dimensions; avoid relying on implicit stretch. Use block frames for colored badges.`,`Name meaningful groups with layer-name; include content and structure together.`,`Styled text controls become frames with editable text children.`,`Scripts, event handlers, embedded documents, executable URLs and CSS imports are rejected.`]},completion:[`Natural hierarchy with the fewest useful editable primitives.`,`The committed version and affected ids match the request.`,`Inspect the final PNG for hierarchy, alignment, clipping and overflow.`,`Keep text, layout and appearance editable in the ordinary inspector.`]},Un=async(e,t)=>{let n=g.parse(await e.remote.query(`canvas.document.get`,{canvasId:t}));return{held:n,document:v.parse(n.document)}},Wn=(e,n)=>{e.command(`guide`).description(`Agent design workflow.`).action(()=>{n.output.result(Hn)}),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 r=t(e.canvas),a=r.canvasId,{held:o,document:s}=await Un(n,a);i(r,s,[e.nodeId]),n.output.result({canvasId:a,version:o.version,nodeId:e.nodeId,jsx:Bn(s,e.nodeId,M(Ft,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 r=t(e.canvas),a=r.canvasId,{held:o,document:s}=await Un(n,a),c=B(e.nodeIds,Pt,`--node-ids`);i(r,s,c),n.output.result({canvasId:a,version:o.version,nodes:Vn(s,c),warning:`These are authored CSS instructions, not measured browser dimensions. Use canvas render as the pixel authority.`})})},Gn=(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=>{let n=await F(t,e,B(e.nodes,Mt,`--nodes`).map(e=>({kind:`duplicate`,nodeIds:[e.id],...e.parentId!==void 0&&{parentId:e.parentId}})),e.idPrefix),{duplicatedNodes:r,...i}=n;t.output.result({...n,duplicatedNodes:r,apply:i})})},Kn=(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=>{let n=await F(t,e,B(e.moves,Nt,`--moves`).map(e=>({kind:`move`,nodeId:e.nodeId,destination:`before`in e?{kind:`before`,nodeId:e.before}:`after`in e?{kind:`after`,nodeId:e.after}:{kind:`parent`,parentId:e.parentId,...e.index!==void 0&&{index:e.index}}}))),{moves:r,affectedParents:i,...a}=n;t.output.result({...n,moves:r,affectedParents:i,apply:a})})},qn=(e,t)=>{Gn(e,t),Kn(e,t)},Jn=262144,Yn=e=>{let t=z(e,Jn,`--html`);if(Buffer.byteLength(t,`utf8`)>Jn)throw new l(`BAD_REQUEST`,`--html exceeds 262144 bytes.`,`Write one visual group at a time, as taught by canvas guide.`);return t},Xn=new Set([`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`]),Zn=async(e,n)=>{if(![`insert-children`,`replace`].includes(n.mode))throw new l(`BAD_REQUEST`,`--mode must be insert-children or replace.`,`Choose one of the two documented modes.`);if(![`none`,`render`].includes(n.review))throw new l(`BAD_REQUEST`,`--review must be none or render.`,`Choose one of the documented review modes.`);P(e,n.clientToken,!0);let r=n.mode===`replace`?`replace`:`insert-children`,i=t(n.canvas),a=N(n.baseVersion);e.output.result(await e.invocation.invoke({capability:I(e.catalog(),`canvas.writeHtml`),arguments:{canvasId:i.canvasId,...i.nodeIds.length>0&&{selectionNodeIds:[...i.nodeIds]},targetNodeId:n.targetNodeId,mode:r,html:Yn(n.html),...n.idPrefix!==void 0&&{idPrefix:n.idPrefix},baseVersion:a,review:n.review,renderOutputPath:n.output??null,overwriteRender:n.force===!0,renderScale:M(Tt,n.scale,`--scale`),renderTimeoutMs:M(wt,n.timeoutMs,`--timeout-ms`)},clientToken:n.clientToken??null}))},Qn=(e,t)=>{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(`--review <mode>`,`none to return after commitment; render to include review pixels.`,`render`).option(`--id-prefix <prefix>`,`Fresh namespace for a new import/replacement; reuse only for an identical retry.`).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`,`
15
17
  Write one visual group at a time. Use --review none for a committed receipt, then render its version and inspect the PNG. Use flex, padding and gap; use targeted commands for later edits.
16
- `).action(async e=>Tn(t,e))},Dn=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),On=(e,t)=>typeof t==`number`&&!wn.has(e)?`${String(t)}px`:String(t),kn=e=>Object.entries(e).filter(([,e])=>e!==null).map(([e,t])=>{let n=Dn(e);return`${n}:${On(n,t??``)}`}).join(`;`).replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`),An=e=>e.length===0?0:Math.max(...e.map(e=>e.x+e.width))+80,jn=(e,t)=>{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 n=V(e.styles,dt,`--styles`);if(n.width===void 0||n.height===void 0)throw new d(`BAD_REQUEST`,`--styles must include width and height.`,`Use explicit whole-pixel dimensions such as 1440px and 900px.`);I(t,e.clientToken,!0);let r=h(e.canvas),i=F(e.baseVersion),a=await C(t,r,i),o=Object.entries(a.relationships).flatMap(([e,t])=>{let n=a.nodes[e]?.box;return n!==void 0&&t.parentId===`root`?[n]:[]}),s={display:`flex`,flexDirection:`column`,left:An(o),top:0,...n,position:`absolute`},c=e.name.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`);t.output.result(await we(t.remote,t.render).execute({canvasId:r,targetNodeId:`root`,mode:`insert-children`,html:`<div layer-name="${c}" data-enhance-kind="frame" style="${kn(s)}"></div>`,idPrefix:`artboard_${t.mutationKey.current(`canvas.render.importSource`,{canvasId:r})}`,baseVersion:i,renderClientToken:t.mutationKey.current(`canvas.render.create`,{purpose:`create-artboard-review`}),renderOutputPath:e.output??null,overwriteRender:e.force===!0,renderScale:1,renderTimeoutMs:12e4}))})},Mn=(e,t)=>{En(e,t),jn(e,t)},Nn=(e,t)=>{vn(e,t),Mn(e,t),Vt(e,t),xn(e,t),Ft(e,t)},Pn=e=>{let n=e.getOptionValue(`canvas`),r=e.getOptionValue(`canvasId`);if(n!==void 0&&r!==void 0)throw new d(`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 d(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);return{reference:t(i),url:i}},Fn=(e,t)=>{let n=e.getOptionValue(`nodeId`)??(t.nodeIds.length===1?t.nodeIds[0]:void 0);if(typeof n!=`string`||n===``)throw new d(`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 n},In=async(e,t,n,i)=>{let a=v.parse(await t.remote.query(`canvas.document.get`,{canvasId:n.canvasId})),s=r.parse(a.document),c=ee(n,s),l=Object.values(s.nodes).filter(e=>c.has(e.id)).map(e=>({...e,kind:e.component,parentId:s.relationships[e.id]?.parentId??null,children:Object.entries(s.relationships).filter(([,t])=>t.parentId===e.id).map(([e])=>e)})),u={canvasId:n.canvasId,version:a.version,source:`selection-link`,selectedNodeIds:n.nodeIds,next:[`Keep this selection link as --canvas for every edit: ${i}`,`Edit only these nodes or their descendants; other canvas content is outside the request.`]};if(e.name()===`node`){let t=Fn(e,n);return o(n,s,[t]),{...u,node:l.find(e=>e.id===t)}}return{...u,nodes:l}},Ln=(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}=Pn(r),a=e.nodeIds.length>0?await In(r,t,e,i):await t.remote.query(`canvas.${n}`,{canvasId:e.canvasId,...n===`node`&&{nodeId:Fn(r,e)}});t.output.result(a)}))}},Rn=w.coerce.number().int().positive(),zn=w.coerce.number().int().nonnegative(),Bn=w.coerce.number().min(me).max(4),q=(e,t,n,r=`canvas render`)=>{let i=e.safeParse(t);if(!i.success)throw new d(`BAD_REQUEST`,`${n} is invalid.`,`Run 'enhance ${r} --help'.`);return i.data},Vn=e=>{if(e===void 0)return null;try{let t=b.safeParse(JSON.parse(e));if(t.success)return t.data}catch{}throw new d(`BAD_REQUEST`,`--bounds must be a finite positive world rectangle.`,`Pass JSON such as '{"x":0,"y":0,"width":800,"height":600}'.`)},Hn=(e,t)=>e===void 0?t===null?{kind:`content`}:{kind:`bounds`,bounds:t}:{kind:`node`,nodeId:e},Un=e=>{if(!(typeof e!=`string`||!e.startsWith(`rec_`)))return w.uuid().safeParse(e.slice(4)).data},Wn=(e,t)=>{let n=w.uuid().nullable().safeParse(t??null);if(!n.success)throw new d(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact render.`);return e.mutationKey.select(n.data,!1),e.mutationKey.current(`canvas.render.create`,{})},Gn=async(e,n)=>{let i=t(e.canvas??``);if(i.nodeIds.length===0)return e.nodeId;let a=e.nodeId??(i.nodeIds.length===1?i.nodeIds[0]:void 0);if(a===void 0||e.bounds!==void 0)throw new d(`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 s=v.parse(await n.remote.query(`canvas.document.get`,{canvasId:i.canvasId}));return o(i,r.parse(s.document),[a]),a},Kn=async(e,n)=>{if(e.canvas===void 0)throw new d(`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 d(`BAD_REQUEST`,`--node-id and --bounds cannot be combined.`,`Choose one focused target, or omit both to render all authored content.`);let r=await Gn(e,n);if(r===void 0&&e.atMs!==void 0)throw new d(`BAD_REQUEST`,`--at-ms requires --node-id.`,"Render the stable recording node returned by `enhance canvas tree`.");let i=e.atMs===void 0?null:Un(r);if(i===void 0&&e.atMs!==void 0)throw new d(`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.");Wn(n,e.clientToken);let a=await n.invocation.invoke({capability:R(n.catalog(),`canvas.render`),arguments:{canvasId:t(e.canvas).canvasId,expectedVersion:e.expectedVersion===void 0?null:q(Rn,e.expectedVersion,`--expected-version`),target:Hn(r,Vn(e.bounds)),sourceState:i==null?null:{kind:`recording`,recordingId:i,atMs:q(zn,e.atMs??``,`--at-ms`)},scale:q(Bn,e.scale,`--scale`),outputPath:e.output??null,overwrite:e.force===!0,timeoutMs:q(Rn,e.timeoutMs,`--timeout-ms`)},clientToken:e.clientToken??null});n.output.result(a)},qn=(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`,`
18
+ `).action(async e=>Zn(t,e))},$n=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),er=(e,t)=>typeof t==`number`&&!Xn.has(e)?`${String(t)}px`:String(t),tr=e=>Object.entries(e).filter(([,e])=>e!==null).map(([e,t])=>{let n=$n(e);return`${n}:${er(n,t??``)}`}).join(`;`).replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`),nr=e=>e.length===0?0:Math.max(...e.map(e=>e.x+e.width))+80,rr=(e,t)=>{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 n=B(e.styles,Ot,`--styles`);if(n.width===void 0||n.height===void 0)throw new l(`BAD_REQUEST`,`--styles must include width and height.`,`Use explicit whole-pixel dimensions such as 1440px and 900px.`);P(t,e.clientToken,!0);let r=p(e.canvas),i=N(e.baseVersion),a=await b(t,r,i),o=Object.entries(a.relationships).flatMap(([e,t])=>{let n=a.nodes[e]?.box;return n!==void 0&&t.parentId===`root`?[n]:[]}),s={display:`flex`,flexDirection:`column`,left:nr(o),top:0,...n,position:`absolute`},c=e.name.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`);t.output.result(await Oe(t.remote,t.render).execute({canvasId:r,targetNodeId:`root`,mode:`insert-children`,html:`<div layer-name="${c}" data-enhance-kind="frame" style="${tr(s)}"></div>`,idPrefix:`artboard_${t.mutationKey.current(`canvas.render.importSource`,{canvasId:r})}`,baseVersion:i,renderClientToken:t.mutationKey.current(`canvas.render.create`,{purpose:`create-artboard-review`}),renderOutputPath:e.output??null,overwriteRender:e.force===!0,renderScale:1,renderTimeoutMs:12e4}))})},ir=(e,t)=>{Qn(e,t),rr(e,t)},ar=(e,t)=>{Wn(e,t),ir(e,t),rn(e,t),qn(e,t),Zt(e,t)},or=e=>{let n=e.getOptionValue(`canvas`),r=e.getOptionValue(`canvasId`);if(n!==void 0&&r!==void 0)throw new l(`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 l(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);return{reference:t(i),url:i}},sr=(e,t)=>{let n=e.getOptionValue(`nodeId`)??(t.nodeIds.length===1?t.nodeIds[0]:void 0);if(typeof n!=`string`||n===``)throw new l(`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 n},cr=async(e,t,n,r)=>{let a=g.parse(await t.remote.query(`canvas.document.get`,{canvasId:n.canvasId})),o=v.parse(a.document),s=ee(n,o),c=Object.values(o.nodes).filter(e=>s.has(e.id)).map(e=>({...e,kind:e.component,parentId:o.relationships[e.id]?.parentId??null,children:Object.entries(o.relationships).filter(([,t])=>t.parentId===e.id).map(([e])=>e)})),l={canvasId:n.canvasId,version:a.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=sr(e,n);return i(n,o,[t]),{...l,node:c.find(e=>e.id===t)}}return{...l,nodes:c}},lr=(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}=or(r),a=e.nodeIds.length>0?await cr(r,t,e,i):await t.remote.query(`canvas.${n}`,{canvasId:e.canvasId,...n===`node`&&{nodeId:sr(r,e)}});t.output.result(a)}))}},ur=x.coerce.number().int().positive(),dr=x.coerce.number().int().nonnegative(),fr=x.coerce.number().min(he).max(4),K=(e,t,n,r=`canvas render`)=>{let i=e.safeParse(t);if(!i.success)throw new l(`BAD_REQUEST`,`${n} is invalid.`,`Run 'enhance ${r} --help'.`);return i.data},pr=e=>{if(e===void 0)return null;try{let t=Te.safeParse(JSON.parse(e));if(t.success)return t.data}catch{}throw new l(`BAD_REQUEST`,`--bounds must be a finite positive world rectangle.`,`Pass JSON such as '{"x":0,"y":0,"width":800,"height":600}'.`)},mr=(e,t)=>e===void 0?t===null?{kind:`content`}:{kind:`bounds`,bounds:t}:{kind:`node`,nodeId:e},hr=e=>{if(!(typeof e!=`string`||!e.startsWith(`rec_`)))return x.uuid().safeParse(e.slice(4)).data},gr=(e,t)=>{let n=x.uuid().nullable().safeParse(t??null);if(!n.success)throw new l(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact render.`);return e.mutationKey.select(n.data,!1),e.mutationKey.current(`canvas.render.create`,{})},_r=async(e,n)=>{let r=t(e.canvas??``);if(r.nodeIds.length===0)return e.nodeId;let a=e.nodeId??(r.nodeIds.length===1?r.nodeIds[0]:void 0);if(a===void 0||e.bounds!==void 0)throw new l(`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 o=g.parse(await n.remote.query(`canvas.document.get`,{canvasId:r.canvasId}));return i(r,v.parse(o.document),[a]),a},vr=async(e,n)=>{if(e.canvas===void 0)throw new l(`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 l(`BAD_REQUEST`,`--node-id and --bounds cannot be combined.`,`Choose one focused target, or omit both to render all authored content.`);let r=await _r(e,n);if(r===void 0&&e.atMs!==void 0)throw new l(`BAD_REQUEST`,`--at-ms requires --node-id.`,"Render the stable recording node returned by `enhance canvas tree`.");let i=e.atMs===void 0?null:hr(r);if(i===void 0&&e.atMs!==void 0)throw new l(`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.");gr(n,e.clientToken);let a=await n.invocation.invoke({capability:I(n.catalog(),`canvas.render`),arguments:{canvasId:t(e.canvas).canvasId,expectedVersion:e.expectedVersion===void 0?null:K(ur,e.expectedVersion,`--expected-version`),target:mr(r,pr(e.bounds)),sourceState:i==null?null:{kind:`recording`,recordingId:i,atMs:K(dr,e.atMs??``,`--at-ms`)},scale:K(fr,e.scale,`--scale`),outputPath:e.output??null,overwrite:e.force===!0,timeoutMs:K(ur,e.timeoutMs,`--timeout-ms`)},clientToken:e.clientToken??null});n.output.result(a)},yr=(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`,`
17
19
  For transcript-led selection, inspect nearby --at-ms renders and reject transitions or duplicate states before running recording snapshot.
18
- `).action(async e=>Kn(e,t))},Jn=(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=je(t.remote,Ne(t.configDirectory),t.now,t.output.result);kt(n,t),Nn(n,{...t,render:i}),Ln(n,t),qn(r,t)},Yn={"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":`Read canvas URL, structure, and next steps.`,"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 text-style-library":`Discover and publish text styles.`,"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.`},Xn=(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)},Zn=()=>({exit:e=>{throw new y(e)}}),Qn={"canvas text-style-library":`Find, read, and publish reusable text styles across canvases.`,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.`},$n=new Set([`canvas.invites.accept`,`canvas.invites.preview`,`organisation.invites.accept`,`organisation.invites.preview`]),er=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`]),tr=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`]),nr=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,J=e=>{let t=nr(Reflect.get(e,`__trpcCli`)),n=t===null?void 0:t.path;return typeof n==`string`?n:null},rr=(e,t,n,r)=>{let i=t.long,a=J(e)??r.join(` `),o=a===``||i===void 0?void 0:p[`${a} ${i}`];if(o!==void 0)return o;if(i!==void 0&&p[i]!==void 0)return p[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},ir=(e,t,n)=>{let r=Zn();e.exitOverride(e=>r.exit(e.exitCode)),e.configureOutput({writeOut:e=>t.output.logger.info?.(e),writeErr:e=>t.output.logger.error?.(e)}),e.showHelpAfterError(!1).showSuggestionAfterError(!1);let i=[],a=[];for(let t of e.options){let r=J(e)??n.join(` `);tr.has(`${r} ${t.long??``}`)&&a.push({flag:t.long??``,name:t.attributeName()});let o=er.has(`${r} ${t.long??``}`),s=Xn(t,o);o&&i.push({name:t.attributeName(),matches:s}),t.description=rr(e,t,t.description,n)}i.length>0&&e.hook(`preAction`,e=>{for(let t of i)t.matches(e.getOptionValue(t.name))&&e.setOptionValueWithSource(t.name,null,`cli`)}),a.length>0&&e.hook(`preAction`,e=>{if(e.getOptionValueSource(`json`)===`cli`)return;let t=a.find(({name:t})=>e.getOptionValueSource(t)!==`cli`);if(t!==void 0)throw new d(`BAD_REQUEST`,`${t.flag} is required unless --json supplies the complete input.`,`Pass ${t.flag} explicitly, including false or null when that is the intended value.`)})},ar=(e,t,n,r)=>{(n!==null&&r.mutationPaths.has(n)||t[0]===`fixture`)&&(e.options.every(e=>e.long!==`--client-token`)&&e.option(`--client-token <uuid>`,p[`--client-token`]),e.hook(`preAction`,e=>{let n=e.getOptionValue(`clientToken`),i=w.uuid().nullable().safeParse(n??null);if(!i.success)throw new d(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact command.`);r.mutationKey.select(i.data,t[0]===`fixture`)}))},or=(e,t,n)=>{n===null||!$n.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 it(typeof n==`string`?n:void 0,`enhance ${t.join(` `)}`);e.setOptionValueWithSource(`token`,r,`cli`)}))},sr=(e,t,n,r)=>{let i=Qn[t.join(` `)];i===void 0?n!==null&&e.description(pe[n]??r.get(n)??`Run the ${n} API operation.`):e.description(i);let a=Yn[t.join(` `)]??(n===null?void 0:Yn[n]);a!==void 0&&e.summary(a)},cr=(e,t,n=[])=>{ir(e,t,n);for(let r of e.commands){let e=[...n,r.name()],i=J(r);ar(r,e,i,t),sr(r,e,i,t.descriptions),or(r,e,i),cr(r,t,e)}},lr=ve().excludedProcedures,ur=new Set([`canvas thumbnail`,`canvas font-catalog`,`telemetry`]),dr=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},fr=(e,t=[])=>{let n=e.commands.filter(e=>{let n=dr(e),r=[...t,e.name()].join(` `);return!ur.has(r)&&(n===null||!lr.has(n))});Reflect.set(e,`commands`,n);for(let e of n)fr(e,[...t,e.name()])},pr=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},mr=(e,t=[])=>e.commands.filter(e=>e.name()!==`help`).flatMap(e=>{let n=[...t,e.name()],r=pr(e);return[{path:n.join(` `),procedure:r,description:e.description(),kind:r===null?e.commands.length>0?`namespace`:`utility`:`derived`,helpCharacters:e.helpInformation().length},...mr(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=_e(e);t.result({items:e.map(e=>r.describe(e.id)),truncated:!1});return}if(r.capabilities){t.result({items:Fe(n()),truncated:!1});return}let i=r.namespace?.trim(),a=mr(e).filter(e=>i===void 0||e.path===i||e.path.startsWith(`${i} `));t.result({items:a,truncated:!1})})},gr=(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:R(n(),`comment.attention`),arguments:{canvasId:h(e)},clientToken:null}))})},_r=(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:T.argv[1]??`enhance`,version:n,api:e,credential:{path:r.path,present:t!==null}})})},vr=e=>w.coerce.number().int().positive().parse(e),yr=w.record(w.string(),w.unknown()),br=(e,t)=>{let n=yr.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},xr=async e=>{let t=(await Xe(e,`utf8`)).split(`
19
- `).filter(e=>e.trim()!==``).map(e=>JSON.parse(e)),n=t.map(e=>yr.safeParse(e).data?.timestamp).find(e=>typeof e==`number`&&Number.isFinite(e));return t.map(e=>({atMs:br(e,n??0),event:e}))},Sr=async e=>({clientToken:e.clientToken??k(),body:await Xe(e.file),route:e.route??null,pageTitle:e.pageTitle??O.basename(e.file),viewport:{width:e.width,height:e.height},provenance:null}),Y=e=>e.option(`--width <pixels>`,`Captured viewport width.`,vr,1440).option(`--height <pixels>`,`Captured viewport height.`,vr,900),Cr=(e,t,n)=>{Y(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 Sr(e)))})},wr=(e,t,n)=>{Y(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 xr(e.file),sourceUrl:e.sourceUrl,pageTitle:e.pageTitle??null,viewport:{width:e.width,height:e.height},...e.canvasId!==void 0&&{canvasId:e.canvasId}}))})},Tr=(e,t,n)=>{Y(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 Sr({file:t,width:e.width,height:e.height}));n.result(await t({organisationName:e.organisationName,canvasTitle:e.canvasTitle,screens:r}))})},Er=(e,t,n)=>{let r=e.command(`fixture`).description(`Build deterministic product fixtures.`);Cr(r,t.screen,n),wr(r,t.recording,n),Tr(r,t.world,n)},Dr=e=>w.coerce.number().parse(e),Or=e=>w.coerce.number().positive().parse(e),kr=e=>w.coerce.number().int().positive().parse(e),Ar=(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.`,kr).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.`,Dr,48).option(`--y <pixels>`,`Canvas y coordinate.`,Dr,48).option(`--width <pixels>`,`Prototype viewport width.`,Or,1440).option(`--height <pixels>`,`Prototype viewport height.`,Or,900).action(async e=>{let i=e.clientToken??k();r.result(await t.invoke({capability:R(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}))})},jr=(e,t,n)=>{let r=(n?w.coerce.number().int().positive():w.coerce.number().int().nonnegative()).safeParse(e);if(!r.success)throw new d(`BAD_REQUEST`,`${t} is invalid.`,`Run 'enhance recording snapshot --help'.`);return r.data},Mr=(e,t)=>{let n=e.commands.find(e=>e.name()===`recording`);if(n===void 0)throw TypeError(`the API router did not supply recording commands`);n.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`,`
20
+ `).action(async e=>vr(e,t))},br=(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=Fe(t.remote,Le(t.configDirectory),t.now,t.output.result);Kt(n,t),ar(n,{...t,render:i}),lr(n,t),yr(r,t)},xr={"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":`Read canvas URL, structure, and next steps.`,"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 text-style-library":`Discover and publish text styles.`,"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.`},Sr=(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)},Cr=()=>({exit:e=>{throw new _(e)}}),wr={"canvas text-style-library":`Find, read, and publish reusable text styles across canvases.`,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.`},Tr=new Set([`canvas.invites.accept`,`canvas.invites.preview`,`organisation.invites.accept`,`organisation.invites.preview`]),Er=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`]),Dr=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`]),Or=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,q=e=>{let t=Or(Reflect.get(e,`__trpcCli`)),n=t===null?void 0:t.path;return typeof n==`string`?n:null},kr=(e,t,n,r)=>{let i=t.long,a=q(e)??r.join(` `),o=a===``||i===void 0?void 0:d[`${a} ${i}`];if(o!==void 0)return o;if(i!==void 0&&d[i]!==void 0)return d[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},Ar=(e,t,n)=>{let r=Cr();e.exitOverride(e=>r.exit(e.exitCode)),e.configureOutput({writeOut:e=>t.output.logger.info?.(e),writeErr:e=>t.output.logger.error?.(e)}),e.showHelpAfterError(!1).showSuggestionAfterError(!1);let i=[],a=[];for(let t of e.options){let r=q(e)??n.join(` `);Dr.has(`${r} ${t.long??``}`)&&a.push({flag:t.long??``,name:t.attributeName()});let o=Er.has(`${r} ${t.long??``}`),s=Sr(t,o);o&&i.push({name:t.attributeName(),matches:s}),t.description=kr(e,t,t.description,n)}i.length>0&&e.hook(`preAction`,e=>{for(let t of i)t.matches(e.getOptionValue(t.name))&&e.setOptionValueWithSource(t.name,null,`cli`)}),a.length>0&&e.hook(`preAction`,e=>{if(e.getOptionValueSource(`json`)===`cli`)return;let t=a.find(({name:t})=>e.getOptionValueSource(t)!==`cli`);if(t!==void 0)throw new l(`BAD_REQUEST`,`${t.flag} is required unless --json supplies the complete input.`,`Pass ${t.flag} explicitly, including false or null when that is the intended value.`)})},jr=(e,t,n,r)=>{(n!==null&&r.mutationPaths.has(n)||t[0]===`fixture`)&&(e.options.every(e=>e.long!==`--client-token`)&&e.option(`--client-token <uuid>`,d[`--client-token`]),e.hook(`preAction`,e=>{let n=e.getOptionValue(`clientToken`),i=x.uuid().nullable().safeParse(n??null);if(!i.success)throw new l(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact command.`);r.mutationKey.select(i.data,t[0]===`fixture`)}))},Mr=(e,t,n)=>{n===null||!Tr.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 xt(typeof n==`string`?n:void 0,`enhance ${t.join(` `)}`);e.setOptionValueWithSource(`token`,r,`cli`)}))},Nr=(e,t,n,r)=>{let i=wr[t.join(` `)];i===void 0?n!==null&&e.description(me[n]??r.get(n)??`Run the ${n} API operation.`):e.description(i);let a=xr[t.join(` `)]??(n===null?void 0:xr[n]);a!==void 0&&e.summary(a)},Pr=(e,t,n=[])=>{Ar(e,t,n);for(let r of e.commands){let e=[...n,r.name()],i=q(r);jr(r,e,i,t),Nr(r,e,i,t.descriptions),Mr(r,e,i),Pr(r,t,e)}},Fr=Se().excludedProcedures,Ir=new Set([`canvas thumbnail`,`canvas font-catalog`,`telemetry`]),Lr=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},Rr=(e,t=[])=>{let n=e.commands.filter(e=>{let n=Lr(e),r=[...t,e.name()].join(` `);return!Ir.has(r)&&(n===null||!Fr.has(n))});Reflect.set(e,`commands`,n);for(let e of n)Rr(e,[...t,e.name()])},zr=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},Br=(e,t=[])=>e.commands.filter(e=>e.name()!==`help`).flatMap(e=>{let n=[...t,e.name()],r=zr(e);return[{path:n.join(` `),procedure:r,description:e.description(),kind:r===null?e.commands.length>0?`namespace`:`utility`:`derived`,helpCharacters:e.helpInformation().length},...Br(e,n)]}),Vr=(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=ce(n()),r=be(e);t.result({items:e.map(e=>r.describe(e.id)),truncated:!1});return}if(r.capabilities){t.result({items:ze(n()),truncated:!1});return}let i=r.namespace?.trim(),a=Br(e).filter(e=>i===void 0||e.path===i||e.path.startsWith(`${i} `));t.result({items:a,truncated:!1})})},Hr=(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:I(n(),`comment.attention`),arguments:{canvasId:p(e)},clientToken:null}))})},Ur=(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:S.argv[1]??`enhance`,version:n,api:e,credential:{path:r.path,present:t!==null}})})},Wr=e=>x.coerce.number().int().positive().parse(e),Gr=x.record(x.string(),x.unknown()),Kr=(e,t)=>{let n=Gr.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},qr=async e=>{let t=(await et(e,`utf8`)).split(`
21
+ `).filter(e=>e.trim()!==``).map(e=>JSON.parse(e)),n=t.map(e=>Gr.safeParse(e).data?.timestamp).find(e=>typeof e==`number`&&Number.isFinite(e));return t.map(e=>({atMs:Kr(e,n??0),event:e}))},Jr=async e=>({clientToken:e.clientToken??E(),body:await et(e.file),route:e.route??null,pageTitle:e.pageTitle??T.basename(e.file),viewport:{width:e.width,height:e.height},provenance:null}),J=e=>e.option(`--width <pixels>`,`Captured viewport width.`,Wr,1440).option(`--height <pixels>`,`Captured viewport height.`,Wr,900),Yr=(e,t,n)=>{J(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 Jr(e)))})},Xr=(e,t,n)=>{J(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 qr(e.file),sourceUrl:e.sourceUrl,pageTitle:e.pageTitle??null,viewport:{width:e.width,height:e.height},...e.canvasId!==void 0&&{canvasId:e.canvasId}}))})},Zr=(e,t,n)=>{J(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 Jr({file:t,width:e.width,height:e.height}));n.result(await t({organisationName:e.organisationName,canvasTitle:e.canvasTitle,screens:r}))})},Qr=(e,t,n)=>{let r=e.command(`fixture`).description(`Build deterministic product fixtures.`);Yr(r,t.screen,n),Xr(r,t.recording,n),Zr(r,t.world,n)},$r=e=>x.coerce.number().parse(e),ei=e=>x.coerce.number().positive().parse(e),ti=e=>x.coerce.number().int().positive().parse(e),ni=(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.`,ti).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.`,$r,48).option(`--y <pixels>`,`Canvas y coordinate.`,$r,48).option(`--width <pixels>`,`Prototype viewport width.`,ei,1440).option(`--height <pixels>`,`Prototype viewport height.`,ei,900).action(async e=>{let i=e.clientToken??E();r.result(await t.invoke({capability:I(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}))})},ri=(e,t,n)=>{let r=(n?x.coerce.number().int().positive():x.coerce.number().int().nonnegative()).safeParse(e);if(!r.success)throw new l(`BAD_REQUEST`,`${t} is invalid.`,`Run 'enhance recording snapshot --help'.`);return r.data},ii=(e,t)=>{let n=e.commands.find(e=>e.name()===`recording`);if(n===void 0)throw TypeError(`the API router did not supply recording commands`);n.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`,`
20
22
  Preview first: canvas render --node-id rec_<recording-uuid> --at-ms <integer>, then inspect its PNG. This command persists the accepted moment.
21
- `).action(async e=>{let n=w.uuid().nullable().safeParse(e.clientToken??null),r=w.uuid().safeParse(e.recordingId);if(!n.success||!r.success)throw new d(`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.");t.output.result(await t.invocation.invoke({capability:R(t.catalog(),`recording.snapshot`),arguments:{canvasId:h(e.canvas),recordingId:r.data,atMs:jr(e.atMs,`--at-ms`,!1),timeoutMs:jr(e.timeoutMs,`--timeout-ms`,!0)},clientToken:n.data}))})},Nr=(e,t,n)=>{if(e!==`canvas.document.save`||typeof n!=`object`||!n||!(`outcome`in n)||n.outcome!==`conflict`)return n;throw new d(`CONFLICT`,`The canvas document changed before this save landed.`,`Run 'enhance canvas document get --canvas-id ${typeof t==`object`&&t&&`canvasId`in t&&typeof t.canvasId==`string`?t.canvasId:`<canvas-id>`}', merge your change into that document, then retry with its version.`)},Pr=(e,t)=>Ze(e,e=>({[e]:{query:async n=>t.query(e,n),mutate:async n=>Nr(e,n,await t.mutate(e,n))}})),Fr=(e,t)=>{let n=e.commands.find(e=>e.name()===`transcript`);if(n===void 0)throw TypeError(`the API router did not supply transcript commands`);n.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 n=w.uuid().safeParse(e.recordingId);if(!n.success)throw new d(`BAD_REQUEST`,`--recording-id must be a UUID.`,"Use the recording id returned by `enhance recording list`.");t.output.result(await t.invocation.invoke({capability:R(t.catalog(),`transcript.read`),arguments:{canvasId:h(e.canvas),recordingId:n.data},clientToken:null}))})},Ir={jsonInput:`auto`,prompts:!1,logger:`ndjson`,errorMapping:`stable-exit-codes`},Lr=e=>{let t=e.state;return{logger:e.output.logger,prompts:Ir.prompts,process:Zn(),formatError:e=>{let n=_(e,t.pendingParserMessage);return t.exitCode=oe(n,!1,e),t.pendingParserMessage=null,JSON.stringify(n)}}},Rr=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,zr=e=>{let t=Rr(e),n=t===null?void 0:t.description;return typeof n==`string`&&n!==``?n:null},Br=e=>{let t=Re({router:e});return{descriptions:new Map(t.flatMap(([e,t])=>{let n=zr(t.meta);return n===null?[]:[[e,n]]})),mutationPaths:new Set(t.flatMap(([e,t])=>t.type===`mutation`?[e]:[]))}},Vr=()=>{let e=null;return()=>(e??=le(),e)},Hr=(e,t,n)=>{let r=nt(t.remote),i=Ae({remote:t.remote,mutationKey:t.mutationKey,configDirectory:t.configDirectory,now:()=>new Date,progress:t.output.result});ot(e,Oe(t.credentials,t.remote,Ce(t.remote)),t.output),gr(e,i,n,t.output),_r(e,{version:t.version,credentials:t.credentials,remote:t.remote,output:t.output}),Er(e,{screen:r,recording:tt(t.remote),world:rt(t.remote,r)},t.output),hr(e,t.output,n),Jn(e,{remote:t.remote,mutationKey:t.mutationKey,invocation:i,catalog:n,output:t.output,configDirectory:t.configDirectory,now:()=>new Date}),Mr(e,{invocation:i,catalog:n,output:t.output}),Ar(e,i,n,t.output),Fr(e,{invocation:i,catalog:n,output:t.output})},Ur=e=>{let t=fe(),n=Vr(),{descriptions:r,mutationPaths:i}=Br(t),a=Le({router:Pr(t,e.remote),name:e.commandName,version:e.version,description:`Operate Enhance as the authenticated person.`,jsonInput:Ir.jsonInput}),o=Lr(e),s=a.buildProgram(o);if(!(s instanceof Ie))throw TypeError(`trpc-cli did not return a Commander program`);fr(s),Hr(s,e,n),cr(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 y))throw t;if(t.requestedCode!==0&&c.pendingParserMessage!==null){let n=_(t,c.pendingParserMessage);c.exitCode=oe(n,!0),c.pendingParserMessage=null,e.output.failure(n)}throw t}}}},Wr=e=>T.exit(e),Gr=36e5,X=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Kr=e=>{if(Array.isArray(e))return e.map(e=>JSON.stringify(e));if(!X(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(X(e)?{...e,truncated:n}:{value:e,truncated:n}))},qr=e=>{let t=`${e.join(`
22
- `)}\n`;if(!(t.length>25e3||e.some(e=>e.length>2e3))){T.stdout.write(t);return}let n=Ye(`sha256`).update(t).digest(`hex`).slice(0,16),r=O.join(Be(),`enhance-${n}.ndjson`);D(r,t,{mode:384}),T.stdout.write(`${JSON.stringify({path:r,characters:t.length,records:e.length})}\n`)},Jr=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}},Z=e=>typeof e==`string`?Jr(e):Array.isArray(e)?e.some(e=>Z(e)):X(e)?Object.values(e).some(e=>Z(e)):!1,Q=e=>{Ge(e,{recursive:!0,mode:448}),He(e,448)},Yr=e=>{if(!Ue(e))return;let t=Date.now()-Gr,n=qe(e,{withFileTypes:!0});for(let r of n){if(!r.isFile()||!r.name.startsWith(`result-`))continue;let n=O.join(e,r.name);We(n).mtimeMs<t&&Je(n)}},$=e=>({...e,sensitive:!0,cleanup:`unlink-after-use`,deleteAfter:new Date(Date.now()+Gr).toISOString()}),Xr=(e,t)=>{let n=Kr(e),r=`${n.join(`
23
- `)}\n`;Q(t);let i=O.join(t,`result-${k()}.ndjson`);D(i,r,{mode:384,flag:`wx`}),T.stdout.write(`${JSON.stringify($({path:i,characters:r.length,records:n.length,reason:`signed-url`}))}\n`)},Zr=e=>X(e)?typeof e.token==`string`?{field:`token`,value:e.token}:typeof e.acceptToken==`string`?{field:`acceptToken`,value:e.acceptToken}:null:null,Qr=(e,t,n)=>{let r=`${t.value}\n`;Q(n);let i=O.join(n,`result-${k()}.token`);D(i,r,{mode:384,flag:`wx`});let a=Object.fromEntries(Object.entries(e).filter(([e])=>e!==t.field));T.stdout.write(`${JSON.stringify({...a,secret:$({path:i,field:t.field,characters:r.length})})}\n`)},$r=e=>e.includes(`Usage:`)||e.includes(`Options:`)||e.includes(`Commands:`),ei=ne.omit({fields:!0}).extend({remediation:w.string(),fields:w.array(w.object({path:w.string(),message:w.string()})).optional()}),ti=e=>{try{let t=JSON.parse(e),n=ei.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}},ni=(e,t)=>{if(typeof e==`string`&&$r(e)){T.stdout.write(e);return}let n=Zr(e);if(n!==null&&X(e)){Qr(e,n,t);return}if(Z(e)){Xr(e,t);return}let r=he(e);if(r!==null){let e=null;if(r.detail!==null){Q(t);let n=O.join(t,`result-${k()}.ndjson`),i=`${JSON.stringify(r.detail)}\n`;D(n,i,{mode:384,flag:`wx`}),e=$({path:n,characters:i.length,records:1})}T.stdout.write(`${JSON.stringify({...r.value,...e!==null&&{detail:e}})}\n`);return}qr(Kr(e))},ri=e=>{T.stderr.write(`${JSON.stringify(e)}\n`)},ii=(e,t,n=`enhance`)=>{let r=e,i=O.join(t,`sensitive`);return Yr(i),{result:e=>{ni(g(e,n),i)},failure:e=>{ri(xe(e,n))},logger:{info:(...e)=>{ni(g(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(g(e.map(String).join(``),n)),i=ti(t);i===null?r.pendingParserMessage=t:ri(i)}}}};(async()=>{let e={exitCode:1,pendingParserMessage:null},t=ii(e,S.configDirectory,S.commandName),n=Me(S.configDirectory),r=Pe(),i=Ur({version:`0.1.20-dev.sha-e63643fbee08`,credentials:n,remote:ke(S.apiUrl,n,r),mutationKey:r,output:t,state:e,configDirectory:S.configDirectory,commandName:S.commandName});try{await i.run()}catch(n){n instanceof y&&Wr(n.requestedCode===0?0:e.exitCode),t.failure(_(n,null)),Wr(1)}})();export{};
23
+ `).action(async e=>{let n=x.uuid().nullable().safeParse(e.clientToken??null),r=x.uuid().safeParse(e.recordingId);if(!n.success||!r.success)throw new l(`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.");t.output.result(await t.invocation.invoke({capability:I(t.catalog(),`recording.snapshot`),arguments:{canvasId:p(e.canvas),recordingId:r.data,atMs:ri(e.atMs,`--at-ms`,!1),timeoutMs:ri(e.timeoutMs,`--timeout-ms`,!0)},clientToken:n.data}))})},ai=(e,t,n)=>{if(e!==`canvas.document.save`||typeof n!=`object`||!n||!(`outcome`in n)||n.outcome!==`conflict`)return n;throw new l(`CONFLICT`,`The canvas document changed before this save landed.`,`Run 'enhance canvas document get --canvas-id ${typeof t==`object`&&t&&`canvasId`in t&&typeof t.canvasId==`string`?t.canvasId:`<canvas-id>`}', merge your change into that document, then retry with its version.`)},oi=(e,t)=>tt(e,e=>({[e]:{query:async n=>t.query(e,n),mutate:async n=>ai(e,n,await t.mutate(e,n))}})),si=(e,t)=>{let n=e.commands.find(e=>e.name()===`transcript`);if(n===void 0)throw TypeError(`the API router did not supply transcript commands`);n.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 n=x.uuid().safeParse(e.recordingId);if(!n.success)throw new l(`BAD_REQUEST`,`--recording-id must be a UUID.`,"Use the recording id returned by `enhance recording list`.");t.output.result(await t.invocation.invoke({capability:I(t.catalog(),`transcript.read`),arguments:{canvasId:p(e.canvas),recordingId:n.data},clientToken:null}))})},ci={jsonInput:`auto`,prompts:!1,logger:`ndjson`,errorMapping:`stable-exit-codes`},li=e=>{let t=e.state;return{logger:e.output.logger,prompts:ci.prompts,process:Cr(),formatError:e=>{let n=h(e,t.pendingParserMessage);return t.exitCode=oe(n,!1,e),t.pendingParserMessage=null,JSON.stringify(n)}}},ui=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,di=e=>{let t=ui(e),n=t===null?void 0:t.description;return typeof n==`string`&&n!==``?n:null},fi=e=>{let t=He({router:e});return{descriptions:new Map(t.flatMap(([e,t])=>{let n=di(t.meta);return n===null?[]:[[e,n]]})),mutationPaths:new Set(t.flatMap(([e,t])=>t.type===`mutation`?[e]:[]))}},pi=()=>{let e=null;return()=>(e??=ue(),e)},mi=(e,t,n)=>{let r=yt(t.remote),i=Pe({remote:t.remote,mutationKey:t.mutationKey,configDirectory:t.configDirectory,now:()=>new Date,progress:t.output.result});Ct(e,Me(t.credentials,t.remote,De(t.remote)),t.output),Hr(e,i,n,t.output),Ur(e,{version:t.version,credentials:t.credentials,remote:t.remote,output:t.output}),Qr(e,{screen:r,recording:vt(t.remote),world:bt(t.remote,r)},t.output),Vr(e,t.output,n),br(e,{remote:t.remote,mutationKey:t.mutationKey,invocation:i,catalog:n,output:t.output,configDirectory:t.configDirectory,now:()=>new Date}),ii(e,{invocation:i,catalog:n,output:t.output}),ni(e,i,n,t.output),si(e,{invocation:i,catalog:n,output:t.output})},hi=e=>{let t=fe(),n=pi(),{descriptions:r,mutationPaths:i}=fi(t),a=Ve({router:oi(t,e.remote),name:e.commandName,version:e.version,description:`Operate Enhance as the authenticated person.`,jsonInput:ci.jsonInput}),o=li(e),s=a.buildProgram(o);if(!(s instanceof Be))throw TypeError(`trpc-cli did not return a Commander program`);Rr(s),mi(s,e,n),Pr(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 _))throw t;if(t.requestedCode!==0&&c.pendingParserMessage!==null){let n=h(t,c.pendingParserMessage);c.exitCode=oe(n,!0),c.pendingParserMessage=null,e.output.failure(n)}throw t}}}},gi=e=>S.exit(e),_i=36e5,Y=e=>typeof e==`object`&&!!e&&!Array.isArray(e),vi=e=>{if(Array.isArray(e))return e.map(e=>JSON.stringify(e));if(!Y(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(Y(e)?{...e,truncated:n}:{value:e,truncated:n}))},yi=e=>{let t=`${e.join(`
24
+ `)}\n`;if(!(t.length>25e3||e.some(e=>e.length>2e3))){S.stdout.write(t);return}let n=$e(`sha256`).update(t).digest(`hex`).slice(0,16),r=T.join(We(),`enhance-${n}.ndjson`);w(r,t,{mode:384}),S.stdout.write(`${JSON.stringify({path:r,characters:t.length,records:e.length})}\n`)},bi=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}},X=e=>typeof e==`string`?bi(e):Array.isArray(e)?e.some(e=>X(e)):Y(e)?Object.values(e).some(e=>X(e)):!1,Z=e=>{Ye(e,{recursive:!0,mode:448}),Ke(e,448)},xi=e=>{if(!qe(e))return;let t=Date.now()-_i,n=Xe(e,{withFileTypes:!0});for(let r of n){if(!r.isFile()||!r.name.startsWith(`result-`))continue;let n=T.join(e,r.name);Je(n).mtimeMs<t&&Qe(n)}},Q=e=>({...e,sensitive:!0,cleanup:`unlink-after-use`,deleteAfter:new Date(Date.now()+_i).toISOString()}),Si=(e,t)=>{let n=vi(e),r=`${n.join(`
25
+ `)}\n`;Z(t);let i=T.join(t,`result-${E()}.ndjson`);w(i,r,{mode:384,flag:`wx`}),S.stdout.write(`${JSON.stringify(Q({path:i,characters:r.length,records:n.length,reason:`signed-url`}))}\n`)},Ci=e=>Y(e)?typeof e.token==`string`?{field:`token`,value:e.token}:typeof e.acceptToken==`string`?{field:`acceptToken`,value:e.acceptToken}:null:null,wi=(e,t,n)=>{let r=`${t.value}\n`;Z(n);let i=T.join(n,`result-${E()}.token`);w(i,r,{mode:384,flag:`wx`});let a=Object.fromEntries(Object.entries(e).filter(([e])=>e!==t.field));S.stdout.write(`${JSON.stringify({...a,secret:Q({path:i,field:t.field,characters:r.length})})}\n`)},Ti=e=>e.includes(`Usage:`)||e.includes(`Options:`)||e.includes(`Commands:`),Ei=ne.omit({fields:!0}).extend({remediation:x.string(),fields:x.array(x.object({path:x.string(),message:x.string()})).optional()}),Di=e=>{try{let t=JSON.parse(e),n=Ei.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}},$=(e,t)=>{if(typeof e==`string`&&Ti(e)){S.stdout.write(e);return}let n=Ci(e);if(n!==null&&Y(e)){wi(e,n,t);return}if(X(e)){Si(e,t);return}let r=ge(e);if(r!==null){let e=null;if(r.detail!==null){Z(t);let n=T.join(t,`result-${E()}.ndjson`),i=`${JSON.stringify(r.detail)}\n`;w(n,i,{mode:384,flag:`wx`}),e=Q({path:n,characters:i.length,records:1})}S.stdout.write(`${JSON.stringify({...r.value,...e!==null&&{detail:e}})}\n`);return}yi(vi(e))},Oi=e=>{S.stderr.write(`${JSON.stringify(e)}\n`)},ki=(e,t,n=`enhance`)=>{let r=e,i=T.join(t,`sensitive`);return xi(i),{result:e=>{$(m(e,n),i)},failure:e=>{Oi(we(e,n))},logger:{info:(...e)=>{$(m(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(m(e.map(String).join(``),n)),i=Di(t);i===null?r.pendingParserMessage=t:Oi(i)}}}};(async()=>{let e={exitCode:1,pendingParserMessage:null},t=ki(e,y.configDirectory,y.commandName),n=Ie(y.configDirectory),r=Re(),i=hi({version:`0.1.20-dev.sha-20969365248e`,credentials:n,remote:Ne(y.apiUrl,n,r),mutationKey:r,output:t,state:e,configDirectory:y.configDirectory,commandName:y.commandName});try{await i.run()}catch(n){n instanceof _&&gi(n.requestedCode===0?0:e.exitCode),t.failure(h(n,null)),gi(1)}})();export{};
package/dist/mcp-main.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{d as e,m as t,o as n}from"./cli-output-identity.lib-BxOq1eK4.mjs";import{a as r,i,m as a,n as o,o as s,r as c,t as l}from"./mutation-key.adapter-Cl4fSIbD.mjs";import{t as u}from"./mcp-server.adapter-CNtErk6p.mjs";import{z as d}from"zod";import f from"node:process";import{serveStdio as p}from"@modelcontextprotocol/server/stdio";const m=d.object({openBrowser:d.boolean()}),h=(e,t)=>{let i=a(e,t,r(t)),o=null,s=null;return{login:async e=>{if(o!==null)return o.ready;let t=m.parse(e),r=new AbortController,a=Promise.withResolvers();s=null;let c=(async()=>{try{await i.loginWithBrowser({label:`Agent plugin`,openBrowser:t.openBrowser,signal:r.signal,onReady:e=>{s={authenticated:!1,status:`waiting_for_browser`,url:e},a.resolve(s)}}),s=null}catch(e){s={authenticated:!1,status:`failed`,error:n(e,null)},a.reject(e)}finally{o=null}})();return o={controller:r,ready:a.promise,completion:c},a.promise},status:async()=>s===null?await e.read()===null?{authenticated:!1}:i.status():s,logout:async()=>(o?.controller.abort(),await o?.completion,s=null,i.logout())}},g=new Set([`auth.login`,`auth.logout`,`auth.status`,`doctor`]),_=async e=>{switch(e.capability){case`auth.login`:return e.auth.login(e.arguments);case`auth.logout`:return e.auth.logout();case`auth.status`:return e.auth.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`)}},v=(e,t,n,r)=>{let i=o(e,t,l()),a=h(t,i);return{invoke:async c=>{if(g.has(c.capability.id))return _({capability:c.capability.id,arguments:c.arguments,credentials:t,remote:i,version:r,auth:a});let u=l();return s({remote:o(e,t,u),mutationKey:u,configDirectory:n}).invoke(c)}}},y=d.object({authenticated:d.literal(!1)}),b=d.object({authenticated:d.literal(!1),status:d.literal(`waiting_for_browser`),url:d.url()}),x=d.object({authenticated:d.literal(!1),status:d.literal(`failed`),error:d.object({code:d.string(),message:d.string(),remediation:d.string()})}),S=d.object({authenticated:d.literal(!0),personId:d.uuid(),displayName:d.string().min(1),tokenId:d.uuid(),tokenLabel:d.string().min(1),expiresAt:d.iso.datetime().nullable()}),C=d.object({openBrowser:d.boolean().default(!0).describe(`Open the system browser for human sign-in; return its URL immediately.`)}),w=d.strictObject({}),T=d.union([b,x,y,S]),E=d.object({loggedOut:d.boolean()}),D=d.object({status:d.enum([`ok`,`degraded`]),runtimeVersion:d.string().min(1),api:d.object({reachable:d.boolean(),status:d.number().int().nullable(),error:d.string().optional()}),credential:d.object({present:d.boolean()})}),O=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}]}),k=e=>t({...e,source:`composite`,idempotency:e.operation===`query`?`none`:`single`,execution:{kind:`composite`,procedures:[]},meta:{description:e.guide.summary},policy:{exposure:`mcp-transport`,reason:`The local MCP runtime owns its own authentication and installation diagnostics.`,owner:`mcp`},cliPath:null,inputExample:e.guide.examples[0]?.input,outputExample:e.guide.examples[0]?.output}),A=[k({id:`auth.login`,operation:`mutation`,effect:`external`,inputSchema:C,outputSchema:b,guide:O({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:`Returns waiting_for_browser and the exact sign-in URL immediately. Show this URL to the person if their browser restores another page. Consent continues in the background; auth.status reports completion or a failure.`,next:[`Show the sign-in URL, then check auth.status after the person finishes. Only report success after authenticated is true and a canvas read succeeds.`],exampleInput:{openBrowser:!0},exampleOutput:{authenticated:!1,status:`waiting_for_browser`,url:`https://app.example.test/oauth/authorize?client_id=client_enhance_cli`}})}),k({id:`auth.logout`,operation:`mutation`,effect:`delete`,inputSchema:w,outputSchema:E,guide:O({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}})}),k({id:`auth.status`,operation:`query`,effect:`read`,inputSchema:w,outputSchema:T,guide:O({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, a pending sign-in URL, a sign-in failure, or authenticated false; never a credential value.`,next:[`While waiting_for_browser, show the URL and let the person finish. After failure, report the error before retrying auth.login. Continue the workflow only when authenticated is true.`],exampleInput:{},exampleOutput:{authenticated:!1}})}),k({id:`doctor`,operation:`query`,effect:`read`,inputSchema:w,outputSchema:D,guide:O({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.20`,api:{reachable:!0,status:200},credential:{present:!0}}})})].toSorted((e,t)=>e.id.localeCompare(t.id)),j=()=>A,M=c(i.configDirectory),N=v(i.apiUrl,M,i.configDirectory,`0.1.20-dev.sha-e63643fbee08`),P=[...e(),...j()];p(()=>u({version:`0.1.20-dev.sha-e63643fbee08`,name:i.mcpServiceName,commandName:i.commandName,invocation:N,catalog:P,exposures:[`shared`,`mcp-transport`]}),{legacy:`serve`,onerror:()=>f.stderr.write(`${i.mcpServiceName} transport failure\n`)});export{};
2
+ import{d as e,m as t,o as n}from"./cli-output-identity.lib-DZVeJQIS.mjs";import{a as r,i,m as a,n as o,o as s,r as c,t as l}from"./mutation-key.adapter-DAuPDkh5.mjs";import{t as u}from"./mcp-server.adapter-DMJ1epwa.mjs";import{z as d}from"zod";import f from"node:process";import{serveStdio as p}from"@modelcontextprotocol/server/stdio";const m=d.object({openBrowser:d.boolean()}),h=(e,t)=>{let i=a(e,t,r(t)),o=null,s=null;return{login:async e=>{if(o!==null)return o.ready;let t=m.parse(e),r=new AbortController,a=Promise.withResolvers();s=null;let c=(async()=>{try{await i.loginWithBrowser({label:`Agent plugin`,openBrowser:t.openBrowser,signal:r.signal,onReady:e=>{s={authenticated:!1,status:`waiting_for_browser`,url:e},a.resolve(s)}}),s=null}catch(e){s={authenticated:!1,status:`failed`,error:n(e,null)},a.reject(e)}finally{o=null}})();return o={controller:r,ready:a.promise,completion:c},a.promise},status:async()=>s===null?await e.read()===null?{authenticated:!1}:i.status():s,logout:async()=>(o?.controller.abort(),await o?.completion,s=null,i.logout())}},g=new Set([`auth.login`,`auth.logout`,`auth.status`,`doctor`]),_=async e=>{switch(e.capability){case`auth.login`:return e.auth.login(e.arguments);case`auth.logout`:return e.auth.logout();case`auth.status`:return e.auth.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`)}},v=(e,t,n,r)=>{let i=o(e,t,l()),a=h(t,i);return{invoke:async c=>{if(g.has(c.capability.id))return _({capability:c.capability.id,arguments:c.arguments,credentials:t,remote:i,version:r,auth:a});let u=l();return s({remote:o(e,t,u),mutationKey:u,configDirectory:n}).invoke(c)}}},y=d.object({authenticated:d.literal(!1)}),b=d.object({authenticated:d.literal(!1),status:d.literal(`waiting_for_browser`),url:d.url()}),x=d.object({authenticated:d.literal(!1),status:d.literal(`failed`),error:d.object({code:d.string(),message:d.string(),remediation:d.string()})}),S=d.object({authenticated:d.literal(!0),personId:d.uuid(),displayName:d.string().min(1),tokenId:d.uuid(),tokenLabel:d.string().min(1),expiresAt:d.iso.datetime().nullable()}),C=d.object({openBrowser:d.boolean().default(!0).describe(`Open the system browser for human sign-in; return its URL immediately.`)}),w=d.strictObject({}),T=d.union([b,x,y,S]),E=d.object({loggedOut:d.boolean()}),D=d.object({status:d.enum([`ok`,`degraded`]),runtimeVersion:d.string().min(1),api:d.object({reachable:d.boolean(),status:d.number().int().nullable(),error:d.string().optional()}),credential:d.object({present:d.boolean()})}),O=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}]}),k=e=>t({...e,source:`composite`,idempotency:e.operation===`query`?`none`:`single`,execution:{kind:`composite`,procedures:[]},meta:{description:e.guide.summary},policy:{exposure:`mcp-transport`,reason:`The local MCP runtime owns its own authentication and installation diagnostics.`,owner:`mcp`},cliPath:null,inputExample:e.guide.examples[0]?.input,outputExample:e.guide.examples[0]?.output}),A=[k({id:`auth.login`,operation:`mutation`,effect:`external`,inputSchema:C,outputSchema:b,guide:O({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:`Returns waiting_for_browser and the exact sign-in URL immediately. Show this URL to the person if their browser restores another page. Consent continues in the background; auth.status reports completion or a failure.`,next:[`Show the sign-in URL, then check auth.status after the person finishes. Only report success after authenticated is true and a canvas read succeeds.`],exampleInput:{openBrowser:!0},exampleOutput:{authenticated:!1,status:`waiting_for_browser`,url:`https://app.example.test/oauth/authorize?client_id=client_enhance_cli`}})}),k({id:`auth.logout`,operation:`mutation`,effect:`delete`,inputSchema:w,outputSchema:E,guide:O({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}})}),k({id:`auth.status`,operation:`query`,effect:`read`,inputSchema:w,outputSchema:T,guide:O({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, a pending sign-in URL, a sign-in failure, or authenticated false; never a credential value.`,next:[`While waiting_for_browser, show the URL and let the person finish. After failure, report the error before retrying auth.login. Continue the workflow only when authenticated is true.`],exampleInput:{},exampleOutput:{authenticated:!1}})}),k({id:`doctor`,operation:`query`,effect:`read`,inputSchema:w,outputSchema:D,guide:O({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.20`,api:{reachable:!0,status:200},credential:{present:!0}}})})].toSorted((e,t)=>e.id.localeCompare(t.id)),j=()=>A,M=c(i.configDirectory),N=v(i.apiUrl,M,i.configDirectory,`0.1.20-dev.sha-20969365248e`),P=[...e(),...j()];p(()=>u({version:`0.1.20-dev.sha-20969365248e`,name:i.mcpServiceName,commandName:i.commandName,invocation:N,catalog:P,exposures:[`shared`,`mcp-transport`]}),{legacy:`serve`,onerror:()=>f.stderr.write(`${i.mcpServiceName} transport failure\n`)});export{};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import{A as e,E as t,M as n,_t as r,d as i,i as a,l as o,n as s,o as c,r as l,s as u,st as d,t as f,vt as p,w as ee,wt as m,y as h}from"./cli-output-identity.lib-DZVeJQIS.mjs";import{z as g}from"zod";import{createHash as _,randomUUID as v}from"node:crypto";import{readFile as y,rm as b}from"node:fs/promises";import{McpServer as x}from"@modelcontextprotocol/server";const S=g.object({ok:g.literal(!1),error:g.object({code:g.string(),message:g.string(),remediation:g.string(),fields:g.array(g.object({path:g.string(),message:g.string()})).optional()})}),C=g.object({uri:g.string(),mimeType:g.string(),bytes:g.number().int().nonnegative()}),te=g.object({ok:g.literal(!0),artifact:C}),w=g.object({id:g.string(),operation:g.enum([`query`,`mutation`]),effect:g.enum([`read`,`write`,`delete`,`external`]),idempotency:g.enum([`none`,`single`,`composite`]),summary:g.string(),useWhen:g.string(),preconditions:g.array(g.string()),inputSchema:g.unknown(),exampleInput:g.unknown(),output:g.array(g.object({name:g.string(),required:g.boolean(),meaning:g.string()})),result:g.string(),recovery:g.array(g.string()),next:g.array(g.string()),schemaDigest:g.string(),guidanceDigest:g.string(),behaviorDigest:g.string()}),T=w.pick({id:!0,operation:!0,effect:!0,summary:!0,useWhen:!0}),E=g.union([g.object({ok:g.literal(!0),result:g.unknown(),artifact:C.optional(),detail:C.optional()}),te,S]),D=g.union([g.object({ok:g.literal(!0),result:g.object({matches:g.array(T),totalMatches:g.number().int().nonnegative(),truncated:g.boolean(),bestContract:w.optional(),detailRequired:g.object({capability:g.string()}).optional()})}),S]),O=g.union([g.object({ok:g.literal(!0),result:w}),S]),k=g.uuid().optional().describe(`Reuse only when retrying this exact mutation.`),A=h.pick({baseVersion:!0,targetNodeId:!0,html:!0,idPrefix:!0}).extend({canvas:g.string().min(1).describe(`Canvas UUID or complete canvas/selection URL. Preserve a supplied selection URL.`),mode:g.enum([`insert-children`,`replace`]).default(`insert-children`),clientToken:k}),j=ee.extend({clientToken:k}),M=g.object({canvas:g.string().min(1),expectedVersion:g.number().int().positive().describe(`Version returned by the latest successful read or write.`),target:p.default({kind:`content`}),sourceState:r.nullable().default(null),scale:g.number().min(.1).max(4).default(1)}),N=async(e,t,n,r=null)=>{let i=e.catalog.find(e=>e.id===t);if(i===void 0)throw TypeError(`Missing canvas capability ${t}`);return e.invocation.invoke({capability:i,arguments:n,clientToken:r})},P=async(r,i)=>{let a=e(i.canvas);if(a.nodeIds.length===0)return{canvasId:a.canvasId,target:i.target};let o=i.target.kind===`node`?i.target.nodeId:i.target.kind===`content`&&a.nodeIds.length===1?a.nodeIds[0]:void 0;if(o===void 0)throw new n(`BAD_REQUEST`,`A selection link requires one selected node to render.`,`Choose a node target inside the selection; bounds or whole-canvas renders can include unrelated content.`);let s=d.parse(await N(r,`canvas.document.get`,{canvasId:a.canvasId}));if(s.version!==i.expectedVersion)throw new n(`CONFLICT`,`The canvas changed before rendering.`,`Read the selected subtree and render its current version.`);return t(a,m.parse(s.document),[o]),{canvasId:a.canvasId,target:{kind:`node`,nodeId:o}}},F=async(e,t,n)=>{try{return await t.results.success(e,await n(),t.delivery)}catch(e){return t.results.failure(e)}},I=(t,n)=>{n.catalog.some(e=>e.id===`canvas.writeHtml`)&&t.registerTool(`canvas_write_html`,{title:`Design editable canvas content`,description:`Create a populated screen or visual group from safe HTML/CSS. For multiple screens, publish the first populated screen before authoring the next, then publish each subsequent screen separately so the user can see and steer progress. Prepare only what that screen needs; do not prepare the whole set before the first write. Returns the committed version and root node without an extra read or render. If starting state is unknown, call capability_query with {"capability":"canvas.inspect","input":{"canvasId":"<UUID from canvas URL>"}}. When nodeCount is 0, use targetNodeId "root" and the returned version. Use flex, padding, gap, concrete inline CSS and layer-name. Give important rows/cards/buttons explicit dimensions; avoid implicit stretch, margins, grid, tables and inline badge backgrounds. Include real content, not an empty shell. Reuse a returned version for subsequent edits; read a targeted subtree only when its ids or structure are unknown. Use canvas_edit for small changes, then canvas_render once at a useful review point. The schema here is executable; no search or describe is required.`,inputSchema:A,outputSchema:E,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},async({canvas:r,clientToken:i,...a})=>F(t,n,async()=>{let t=e(r);return N(n,`canvas.writeHtml`,{...a,canvasId:t.canvasId,...t.nodeIds.length>0&&{selectionNodeIds:t.nodeIds},review:`none`,renderOutputPath:null,overwriteRender:!1,renderScale:1,renderTimeoutMs:12e4},i??null)}))},L=(e,t)=>{t.catalog.some(e=>e.id===`canvas.edit`)&&e.registerTool(`canvas_edit`,{title:`Edit existing canvas content`,description:`Apply text, styles, rename, duplicate or move edits together in one atomic mutation. Use ids from the input version and the latest successful read or write version; no intermediate read is required just to advance a version. Keep the complete selection URL. Read only the missing subtree when ids are unknown. Returns a compact committed receipt; render after the requested changes are complete.`,inputSchema:j,outputSchema:E,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},async({clientToken:n,...r})=>F(e,t,async()=>N(t,`canvas.edit`,r,n??null)))},R=(e,t)=>{t.catalog.some(e=>e.id===`canvas.render`)&&e.registerTool(`canvas_render`,{title:`Review canvas pixels`,description:`Render the version returned by a successful read or write and inspect its native PNG. Target the affected screen/node; a blank canvas does not need a pre-render. For a selection link use one node inside the selection. Review after a meaningful visual change, and repeat only after further changes or a real discrepancy.`,inputSchema:M,outputSchema:E,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async n=>F(e,t,async()=>N(t,`canvas.render`,{...await P(t,n),expectedVersion:n.expectedVersion,sourceState:n.sourceState,scale:n.scale,outputPath:null,overwrite:!1,timeoutMs:12e4})))},z=e=>({register:t=>{I(t,e),L(t,e),R(t,e)}}),B=e=>e.replaceAll(/\s+/gu,` `).trim(),V=e=>{let t=`${e.id} [${e.effect}] — `,n=B(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=>V(e)),r=_(`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}},U=(e,t,n=`enhance`)=>{let r=H(e,t),i=String(s(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:g.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:i}]}))}}},ne=g.object({capability:g.string().min(1).describe(`Exact capability id returned by capability_search or capability_catalogue.`)}),W=(e,t)=>({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:ne,outputSchema:O,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},({capability:r})=>{let i=e.describe(r);return i===null?t.failure(new n(`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.`})):t.inline(i)})}}),G=/(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu,K=/[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu,q=e=>JSON.stringify(e),J=(e,t=``)=>typeof e==`string`?K.test(e)||G.test(t)&&!t.endsWith(`Id`):Array.isArray(e)?e.some(e=>J(e,t)):typeof e!=`object`||!e?!1:Reflect.get(e,`sensitive`)===!0||Object.entries(e).some(([e,t])=>J(t,e)),Y=async(e,t,n)=>{let r=await y(t.path),i=v(),a=`enhance://artifact/${i}`;if(n===`embedded`&&t.cleanup===`unlink-after-use`)try{await b(t.path,{force:!0})}catch{}return n===`linked`&&e.registerResource(`artifact-${i}`,a,{title:`Enhance artifact`,mimeType:t.contentType},e=>({contents:[{uri:e.href,mimeType:t.contentType,blob:r.toString(`base64`)}]})),{metadata:l.omit({path:!0,sensitive:!0,cleanup:!0,deleteAfter:!0}).parse(t),artifact:{uri:a,mimeType:t.contentType,bytes:r.byteLength},image:{type:`image`,data:r.toString(`base64`),mimeType:t.contentType}}},X=(e,t,n)=>{let r=v(),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:q(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:q(o)},{type:`resource_link`,name:`Protected Enhance result`,uri:i,mimeType:`application/json`}],structuredContent:o}},Z=e=>new n(`BAD_REQUEST`,`Input validation error.`,`Correct the rejected fields using this tool’s schema, then retry. Describe the exact capability only if its contract is unknown.`,Object.fromEntries(e.issues.map(e=>[e.path.length===0?`input`:e.path.join(`.`),e.message]))),re=async(e,t,n)=>{let r=l.safeParse(t);if(r.success){let t=await Y(e,r.data,n);return{value:t.metadata,detail:null,attachment:t}}let i=a(t);if(i===null)return{value:t,detail:null,attachment:null};let o=i.detail??i.value,s=l.safeParse(o.review);if(!s.success)return{...i,attachment:null};try{let t=await Y(e,s.data,n),r={...o,review:{...t.metadata,artifact:t.artifact}},i=a(r);return{value:i?.value??r,detail:i?.detail??null,attachment:t}}catch{let e={...o,review:{state:`unavailable`,mutationCommitted:!0,requestedVersion:o.version,retry:{tool:`canvas_render`,arguments:{canvas:o.canvasId,expectedVersion:o.version,target:s.data.target}}},next:[`Retry the render of the committed version; do not replay the write.`]},t=a(e);return{value:t?.value??e,detail:t?.detail??null,attachment:null}}},ie=(e,t)=>{let n={ok:!0,result:s(e,t)};return{content:[{type:`text`,text:q(n)}],structuredContent:n}},ae=(e,t=`enhance`)=>({success:async(e,n,r)=>{let i=s(n,t),a=await re(e,i,r),o=a.attachment,c=q(a.value);if(J(a.value)||o===null&&a.detail===null&&Buffer.byteLength(c)>2e4)return X(e,c,r);let l=a.detail===null?null:X(e,q(a.detail),r),u={ok:!0,result:a.value,...o!==null&&{artifact:o.artifact},...l!==null&&{detail:l.structuredContent.artifact}};return{content:[{type:`text`,text:q(u)},...o===null?[]:[o.image],...l?.content.filter(e=>e.type!==`text`)??[]],structuredContent:u}},inline:e=>ie(e,t),failure:n=>{let r=f(c(n instanceof g.ZodError?Z(n):n,null),t),i={ok:!1,error:r.code===`UNAUTHORIZED`?{...r,remediation:e}:r};return{content:[{type:`text`,text:q(i)}],structuredContent:i,isError:!0}}}),oe=g.object({query:g.string().trim().min(1).max(200).describe(`Plain-language task, domain, or exact capability id to discover.`),operation:g.enum([`any`,`query`,`mutation`]).default(`any`).describe(`Filter dispatch, not effect. Omit if unknown; render uses mutation.`),limit:g.number().int().min(1).max(10).default(5).describe(`Maximum contracts to return.`)}),se=g.object({capability:g.string().min(1).describe(`Exact query id from an available complete contract.`),input:g.record(g.string(),g.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`)}),Q=g.object({capability:g.string().min(1).describe(`Exact mutation id from an available complete contract.`),input:g.record(g.string(),g.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`),clientToken:g.uuid().optional().describe(`Stable UUID reused only when retrying this exact mutation input.`)}),$=(e,t,r)=>{let i=e.find(e=>e.id===t);if(i===void 0)throw new n(`BAD_REQUEST`,`Unknown shared capability: ${t}.`,`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 e=i.operation===`query`?`capability_query`:`capability_mutate`;throw new n(`BAD_REQUEST`,`${t} is a ${i.operation}, not a ${r}.`,`Call ${e} with the same capability and input.`,{capability:`Use ${e} for this capability.`})}return i},ce=(e,t,n,r)=>{e.registerTool(`capability_search`,{title:`Discover Enhance capabilities`,description:`Search the Enhance capability catalogue for a specific likely action. Returns relevant summaries and a complete bestContract when it fits. Invoke from that contract directly; call capability_describe only when detailRequired is returned or a different match is needed.`,inputSchema:oe,outputSchema:D,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})))},le=(e,t,n,r)=>{e.registerTool(`capability_query`,{title:`Run a discovered Enhance query`,description:`Run one read-only capability using an available complete contract. Search or describe only when the contract is missing.`,inputSchema:se,outputSchema:E,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:$(t,i,`query`),arguments:a,clientToken:null}),r.delivery)}catch(e){return r.results.failure(e)}})},ue=(e,t,n,r)=>{e.registerTool(`capability_mutate`,{title:`Run a discovered Enhance mutation`,description:`Run one state-changing capability using an available complete contract. Respect its preconditions and reuse clientToken only when retrying the identical mutation.`,inputSchema:Q,outputSchema:E,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},_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:$(t,i,`mutation`),arguments:a,clientToken:o??null}),r.delivery)}catch(e){return r.results.failure(e)}})},de=e=>{let t=new x({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 show the returned sign-in URL and let the person complete browser sign-in. If their browser restores a canvas or another page, direct them to this exact URL. A waiting_for_browser result is pending, not authenticated. Verify auth.status and a read such as canvas.list before reporting setup complete.`}}),n=u(e.catalog??i(),e.exposures??[`shared`]),r=o(n),a=e.delivery??`linked`,s=ae(e.exposures?.includes(`mcp-transport`)===!0?`Call capability_mutate with capability auth.login and input {"openBrowser":true}. Show the returned sign-in URL, 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);U(n,e.version,e.commandName).register(t),ce(t,n,r,s),W(r,s).register(t);let c={delivery:a,results:s};return le(t,n,e.invocation,c),ue(t,n,e.invocation,c),z({catalog:n,invocation:e.invocation,...c}).register(t),t};export{de as t};
package/dist/mcp.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{c as e,d as t}from"./cli-output-identity.lib-BxOq1eK4.mjs";import{t as n}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{t as r}from"./mcp-server.adapter-CNtErk6p.mjs";export{t as createCapabilityCatalogAdapter,r as createEnhanceMcpServer,n as toCapabilityInventory,e as toSharedCapabilities};
2
+ import{c as e,d as t}from"./cli-output-identity.lib-DZVeJQIS.mjs";import{t as n}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{t as r}from"./mcp-server.adapter-DMJ1epwa.mjs";export{t as createCapabilityCatalogAdapter,r as createEnhanceMcpServer,n as toCapabilityInventory,e as toSharedCapabilities};