@enhance-eng/enhance-dev 0.1.18-dev.sha-79a2e409834c → 0.1.18-dev.sha-d6d6e366d86b
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{cli-output-identity.lib-C113YU0a.mjs → cli-output-identity.lib-B2oX7yo7.mjs} +2 -2
- package/dist/main.mjs +2 -2
- package/dist/mcp-main.mjs +1 -1
- package/dist/{mcp-server.adapter-FRGhzXG0.mjs → mcp-server.adapter-Ck8xzBdS.mjs} +1 -1
- package/dist/mcp.mjs +1 -1
- package/dist/{mutation-key.adapter-NyunzVOl.mjs → mutation-key.adapter-Cfg2rJZp.mjs} +1 -1
- package/package.json +1 -1
package/dist/main.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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,at as se,c as ce,ct as le,d as ue,dt as p,et as de,f as fe,ft as pe,g as me,h as m,ht as he,i as ge,it as _e,j as h,k as g,l as ve,n as _,o as v,p as ye,rt as be,t as xe,u as y,vt as b,wt as x,z as Se}from"./cli-output-identity.lib-
|
|
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,at as se,c as ce,ct as le,d as ue,dt as p,et as de,f as fe,ft as pe,g as me,h as m,ht as he,i as ge,it as _e,j as h,k as g,l as ve,n as _,o as v,p as ye,rt as be,t as xe,u as y,vt as b,wt as x,z as Se}from"./cli-output-identity.lib-B2oX7yo7.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-Cfg2rJZp.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
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 h(`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 h(`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=p.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=pe.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 h(`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 h?e:new h(`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(le).min(1).max(se),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, setBox, setLabel, setVisibility, setLocked, setConstraints, setStyles, setAppearance, setLayout, patchTypography, setTypography, patchAdditionalStyles, setAdditionalStyles, setProps, setParentage, move, remove.`,`Example:`,` enhance canvas apply --canvas <url-or-id> --base-version 3 --operations '[{"op":"insertText","nodeId":"txt_summary","parentId":"root","text":"Checkout needs an address.","box":{"x":120,"y":594,"width":720,"height":80},"styles":{"font-size":24}}]'`].join(`
|
|
4
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=_e.safeParse(e.phase);if(!n.success)throw new d(`BAD_REQUEST`,`--phase is invalid.`,`Use reading, writing, creating, deleting, or rendering.`);let r=g(e.canvas),i=be.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(be.parse(await t.remote.mutate(`canvas.realtime.activity.renew`,{canvasId:g(e.canvas),activityId:lt.parse(e.activityId),phase:_e.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(g(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`,`
|
|
5
5
|
Edit shapes (combine related edits in one array):
|
|
@@ -20,4 +20,4 @@ For transcript-led selection, inspect nearby --at-ms renders and reject transiti
|
|
|
20
20
|
Preview first: canvas render --node-id rec_<recording-uuid> --at-ms <integer>, then inspect its PNG. This command persists the accepted moment.
|
|
21
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:g(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:g(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=v(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??=ue(),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=v(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
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=ge(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(_(e,n),i)},failure:e=>{ri(xe(e,n))},logger:{info:(...e)=>{ni(_(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(_(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.18-dev.sha-
|
|
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=ge(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(_(e,n),i)},failure:e=>{ri(xe(e,n))},logger:{info:(...e)=>{ni(_(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(_(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.18-dev.sha-d6d6e366d86b`,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(v(n,null)),Wr(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-
|
|
2
|
+
import{d as e,m as t,o as n}from"./cli-output-identity.lib-B2oX7yo7.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-Cfg2rJZp.mjs";import{t as u}from"./mcp-server.adapter-Ck8xzBdS.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.18`,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.18-dev.sha-d6d6e366d86b`),P=[...e(),...j()];p(()=>u({version:`0.1.18-dev.sha-d6d6e366d86b`,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{};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{A as e,Ct as t,E as n,M as r,_t as i,d as a,dt as o,gt as s,i as c,l,n as u,o as d,r as f,s as p,t as m,w as h,y as ee}from"./cli-output-identity.lib-
|
|
2
|
+
import{A as e,Ct as t,E as n,M as r,_t as i,d as a,dt as o,gt as s,i as c,l,n as u,o as d,r as f,s as p,t as m,w as h,y as ee}from"./cli-output-identity.lib-B2oX7yo7.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=ee.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=h.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:i.default({kind:`content`}),sourceState:s.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(i,a)=>{let s=e(a.canvas);if(s.nodeIds.length===0)return{canvasId:s.canvasId,target:a.target};let c=a.target.kind===`node`?a.target.nodeId:a.target.kind===`content`&&s.nodeIds.length===1?s.nodeIds[0]:void 0;if(c===void 0)throw new r(`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 l=o.parse(await N(i,`canvas.document.get`,{canvasId:s.canvasId}));if(l.version!==a.expectedVersion)throw new r(`CONFLICT`,`The canvas changed before rendering.`,`Read the selected subtree and render its current version.`);return n(s,t.parse(l.document),[c]),{canvasId:s.canvasId,target:{kind:`node`,nodeId:c}}},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(),ne=e=>{let t=`${e.id} [${e.effect}] — `,n=B(e.guide.summary),r=180-t.length;return`${t}${n.slice(0,r)}`},V=(e,t)=>{let n=e.toSorted((e,t)=>e.id.localeCompare(t.id)).map(e=>ne(e)),r=_(`sha256`).update(n.join(`
|
|
3
3
|
`)).digest(`hex`),i=[`Enhance MCP ${t} — ${String(n.length)} capabilities — sha256:${r}`,...n].join(`
|
|
4
4
|
`);if(Buffer.byteLength(i)>24576)throw RangeError(`the complete capability catalogue exceeds 24 KiB`);return{digest:r,text:i}},H=(e,t,n=`enhance`)=>{let r=V(e,t),i=String(u(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}]}))}}},U=g.object({capability:g.string().min(1).describe(`Exact capability id returned by capability_search or capability_catalogue.`)}),W=(e,t)=>({register:n=>{n.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:U,outputSchema:O,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},({capability:n})=>{let i=e.describe(n);return i===null?t.failure(new r(`BAD_REQUEST`,`Unknown shared capability: ${n}.`,`Call capability_search or capability_catalogue and use an exact id from its results.`,{capability:`No shared capability has this id.`})):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:f.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 r(`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=f.safeParse(t);if(r.success){let t=await Y(e,r.data,n);return{value:t.metadata,detail:null,attachment:t}}let i=c(t);if(i===null)return{value:t,detail:null,attachment:null};let a=i.detail??i.value,o=f.safeParse(a.review);if(!o.success)return{...i,attachment:null};try{let t=await Y(e,o.data,n),r={...a,review:{...t.metadata,artifact:t.artifact}},i=c(r);return{value:i?.value??r,detail:i?.detail??null,attachment:t}}catch{let e={...a,review:{state:`unavailable`,mutationCommitted:!0,requestedVersion:a.version,retry:{tool:`canvas_render`,arguments:{canvas:a.canvasId,expectedVersion:a.version,target:o.data.target}}},next:[`Retry the render of the committed version; do not replay the write.`]},t=c(e);return{value:t?.value??e,detail:t?.detail??null,attachment:null}}},ie=(e,t)=>{let n={ok:!0,result:u(e,t)};return{content:[{type:`text`,text:q(n)}],structuredContent:n}},ae=(e,t=`enhance`)=>({success:async(e,n,r)=>{let i=u(n,t),a=await re(e,i,r),o=a.attachment,s=q(a.value);if(J(a.value)||o===null&&a.detail===null&&Buffer.byteLength(s)>2e4)return X(e,s,r);let c=a.detail===null?null:X(e,q(a.detail),r),l={ok:!0,result:a.value,...o!==null&&{artifact:o.artifact},...c!==null&&{detail:c.structuredContent.artifact}};return{content:[{type:`text`,text:q(l)},...o===null?[]:[o.image],...c?.content.filter(e=>e.type!==`text`)??[]],structuredContent:l}},inline:e=>ie(e,t),failure:n=>{let r=m(d(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,n)=>{let i=e.find(e=>e.id===t);if(i===void 0)throw new r(`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!==n){let e=i.operation===`query`?`capability_query`:`capability_mutate`;throw new r(`BAD_REQUEST`,`${t} is a ${i.operation}, not a ${n}.`,`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=p(e.catalog??a(),e.exposures??[`shared`]),r=l(n),i=e.delivery??`linked`,o=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);H(n,e.version,e.commandName).register(t),ce(t,n,r,o),W(r,o).register(t);let s={delivery:i,results:o};return le(t,n,e.invocation,s),ue(t,n,e.invocation,s),z({catalog:n,invocation:e.invocation,...s}).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-
|
|
2
|
+
import{c as e,d as t}from"./cli-output-identity.lib-B2oX7yo7.mjs";import{t as n}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{t as r}from"./mcp-server.adapter-Ck8xzBdS.mjs";export{t as createCapabilityCatalogAdapter,r as createEnhanceMcpServer,n as toCapabilityInventory,e as toSharedCapabilities};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{A as e,B as t,C as n,Ct as r,D as i,E as a,Et as o,G as s,H as c,J as l,K as u,M as d,N as f,S as ee,St as te,U as ne,V as re,W as ie,X as ae,Y as oe,Z as se,_ as ce,b as le,bt as ue,dt as de,j as fe,kt as pe,lt as p,mt as me,nt as m,ot as he,pt as ge,q as _e,rt as ve,st as h,tt as ye,ut as be,v as xe,w as Se,x as Ce,xt as we,y as Te,yt as Ee}from"./cli-output-identity.lib-C113YU0a.mjs";import{z as g}from"zod";import{homedir as De,tmpdir as Oe}from"node:os";import _ from"node:process";import{generateKeyBetween as ke,generateNKeysBetween as Ae}from"fractional-indexing";import{chmodSync as je,createReadStream as Me,createWriteStream as Ne,mkdirSync as Pe,writeFileSync as Fe}from"node:fs";import v from"node:path";import{createHash as y,randomBytes as Ie,randomUUID as b}from"node:crypto";import{setTimeout as Le}from"node:timers/promises";import{chmod as Re,mkdir as ze,mkdtemp as Be,readFile as Ve,realpath as He,rename as Ue,rm as We,stat as Ge,unlink as Ke,writeFile as qe}from"node:fs/promises";import{Readable as Je,Transform as Ye}from"node:stream";import{pipeline as Xe}from"node:stream/promises";import{ZipFile as Ze}from"yazl";import{createTRPCUntypedClient as Qe,httpLink as $e}from"@trpc/client";import{spawn as et}from"node:child_process";import{createServer as tt}from"node:http";const nt=(e,t)=>{let n=new Set(t),r=[],i=new Map,a=r;for(let t of e)n.has(t.id)&&(a=[],i.set(t.id,a)),a.push(t);return[...r,...t.flatMap(e=>i.get(e)??[])]},x=(e,t)=>{let n=new Set(t.clear),r=new Map((e?.declarations??[]).filter(e=>!n.has(e.id)).map(e=>[e.id,e])),i=t.set??[];for(let e of i)r.set(e.id,e);let a=Array.from(r,([,e])=>e);return a.length===0&&(t.empty===`remove`||e===void 0&&t.empty!==`keep`)?null:{declarations:t.order===void 0?a:nt(a,t.order)}},rt=(e,t)=>{let n=new Map(e?.declarations.map(e=>[e.id,e])),r=t?.declarations??[],i=new Set(r.map(e=>e.id)),a=Array.from(n,([e])=>e).filter(e=>!i.has(e)),o=r.filter(e=>{let t=n.get(e.id);return t?.property!==e.property||t.value!==e.value||t.enabled!==e.enabled}),s={...a.length>0&&{clear:a},...o.length>0&&{set:o}},c=x(e,s),l=r.map(e=>e.id),u=JSON.stringify(c?.declarations.map(e=>e.id)??[])!==JSON.stringify(l),d=t===void 0&&e!==void 0?`remove`:e===void 0&&t!==void 0&&r.length===0?`keep`:void 0;return d===void 0&&!u&&o.length===0&&a.length===0?null:{...s,...u&&{order:l},...d!==void 0&&{empty:d}}},it=/^enh_[\w-]{43}$/,S=e=>{let t=oe.parse(e);if(t.authentication.kind!==`agent`||t.person===null)throw new d(`UNAUTHORIZED`,`The credential is missing, expired, revoked, or invalid.`,`Run 'enhance auth login' and complete authentication in the browser.`);return{authenticated:!0,personId:t.person.id,displayName:t.person.displayName,tokenId:t.authentication.tokenId,tokenLabel:t.authentication.tokenLabel,expiresAt:t.authentication.expiresAt}},at=(e,t,n)=>({loginWithToken:async n=>{if(!it.test(n))throw new d(`BAD_REQUEST`,`Agent tokens begin with enh_ and contain 32 base64url bytes.`,`Pass a manual token from Settings to 'enhance auth login' through stdin.`);let r=S(await t.queryWithToken(`person.me`,{},n));return await e.write(n),r},loginWithBrowser:async r=>{let i=ae.parse(await t.authenticationConfig());if(i.method===`token`)throw new d(`BAD_REQUEST`,`Browser authentication is not configured for this Enhance environment.`,`Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.`);let a=await n.authorize({issuer:i.issuer,clientId:i.clientId,scope:i.scope,openBrowser:r.openBrowser,onReady:r.onReady,...r.signal!==void 0&&{signal:r.signal}});r.signal?.throwIfAborted();let o=se.parse(await t.mutateWithToken(`person.createAgentToken`,{label:r.label,expiresAt:null},a)),s=S(await t.queryWithToken(`person.me`,{},o.token));return r.signal?.throwIfAborted(),await e.write(o.token),s},status:async()=>{if(await e.read()===null)throw new d(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return S(await t.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),ot=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),st=e=>{if(e.byteLength<24||ot.some((t,n)=>e[n]!==t))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{width:t.getUint32(16),height:t.getUint32(20)}},ct=async(e,t)=>{let n=we.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid render download response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");let r=await e.download(n.data.download.url),i=st(r);if(i===null||r.byteLength!==t.result.bytes||i.width!==t.result.width||i.height!==t.result.height)throw new d(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return r},lt=[`canvas.render.create`,`canvas.render.get`],C=e=>new d(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),ut=e=>{let t=e.failure;if(t===null)return C(`render job`);let n=t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,r=t.reason===`VERSION_CHANGED`?`Run 'enhance canvas inspect --canvas ${e.canvasId}', then render its returned version.`:t.reason===`TARGET_NOT_FOUND`?`Run 'enhance canvas tree --canvas ${e.canvasId}' and choose a current node id.`:t.retryable?"Retry the render. If it repeats, run `enhance doctor` and report the job id.":`Change the target or scale using the failure details, then retry.`;return new d(n,t.message,r,{jobId:e.id,reason:t.reason,phase:t.phase})},dt=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),ft=async(e,t)=>{let n=te.safeParse(await e.query(lt[1],{jobId:t}));if(!n.success)throw C(`render status`);return n.data.job},pt=async(e,t)=>{let n=Date.now(),r=0,i=``,a=t.initial;for(;a.state===`queued`||a.state===`running`;){let o=Date.now(),s=`${a.state}:${a.phase}`;if((s!==i||o-r>=5e3)&&(t.progress({event:`render.progress`,jobId:a.id,state:a.state,phase:a.phase,elapsedMs:o-n,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),r=o,i=s),o>=t.deadline)throw new d(`INTERNAL`,`Render ${a.id} did not finish before the local timeout.`,`Retry the exact command with --client-token ${t.retryClientToken} and a larger --timeout-ms. If the render remains unavailable, run \`enhance doctor\` and report the job id.`,{jobId:a.id,phase:a.phase});await dt(250),a=await ft(e,a.id)}if(a.state!==`succeeded`)throw ut(a);return a},mt=e=>{let t=`enhance canvas inspect --canvas ${e.canvasId}`;return e.result.sourceState===void 0?e.target.kind===`node`?[t,`enhance canvas node --canvas ${e.canvasId} --node-id ${e.target.nodeId}`]:[t]:[`Inspect the PNG at path before persisting this moment.`,`enhance recording snapshot --canvas ${e.canvasId} --recording-id ${e.result.sourceState.recordingId} --at-ms ${String(e.result.sourceState.settledAtMs)}`,t]},ht=(e,t)=>({jobId:e.id,canvasId:e.canvasId,requestedVersion:e.requestedVersion,loadedVersion:e.result.loadedVersion,target:e.target,sourceState:e.result.sourceState??null,bounds:e.result.bounds,width:e.result.width,height:e.result.height,scale:e.result.scale,contentType:e.result.contentType,bytes:e.result.bytes,warnings:e.result.warnings,path:t.path,sensitive:!0,cleanup:t.temporary?`unlink-after-use`:`caller-owned`,...t.deleteAfter!==null&&{deleteAfter:t.deleteAfter.toISOString()},next:mt(e)}),gt=async(e,t)=>{let n=Ee.safeParse(await e.remote.mutate(lt[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,format:`png`}));if(!n.success)throw C(`render creation`);let r=await pt(e.remote,{initial:n.data.job,deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress}),i=await ct(e.remote,r),a=e.files.write({body:i,outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()});return ht(r,a)},_t=(e,t,n,r=()=>null)=>({execute:async i=>gt({remote:e,files:t,now:n,progress:r},i)}),w={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},T=async e=>{try{return await e(),!0}catch{return!1}},vt=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await T(async()=>e.mutate(w.renew,{...i,nodeIds:[...i.nodeIds],activityId:n})),o=!1)},c=setInterval(()=>void s(),r);return{activityId:n,update:async e=>{a||(i={...i,...e},await s())},finish:async()=>{a||(a=!0,clearInterval(c),await T(async()=>e.mutate(w.end,{canvasId:i.canvasId,activityId:n})))}}},E=e=>({begin:async t=>{try{let n=ve.safeParse(await e.mutate(w.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?vt(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>T(async()=>e.mutate(w.end,{canvasId:t,activityId:n}))}),yt=new Set([`insertPrototype`,`insertText`,`setBox`]),bt=e=>yt.has(e.op),xt=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,St=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],Ct=e=>[...new Set(e.operations.flatMap(e=>St(e)))].slice(0,100),wt=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:bt(e)?e.box==="default"?null:e.box:null,Tt=e=>{let t=e[0];if(t===void 0)return null;let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}},Et=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:4}),r=h.safeParse(n);if(!r.success)throw new d(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data},D=e=>({execute:async(t,n)=>{if(n?.activity===!1)return Et(e,t);let r=await E(e).begin({canvasId:t.canvasId,phase:xt(t),nodeIds:Ct(t),bounds:Tt(t.operations.flatMap(e=>{let t=wt(e);return t===null?[]:[t]}))});try{return await Et(e,t)}finally{await r?.finish()}}}),O=async(e,t,n)=>{let i=de.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:t}));if(!i.success)throw new d(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(i.data.version!==n)throw new d(`CONFLICT`,`Canvas version ${String(i.data.version)} no longer matches --base-version ${String(n)}.`,`An earlier identical request may already have committed. Do not repeat it with a new client token. Inspect the intended scope with 'enhance canvas tree --canvas <the original canvas or selection link>' and reconcile against version ${String(i.data.version)} before submitting a new edit.`);let a=r.safeParse(i.data.document);if(a.success)return a.data;throw new d(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},k=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),A=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),j=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new d(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Dt=(e,t)=>{let n=new Set,r=t=>{for(let i of k(e,t))n.add(i),r(i)};return r(t),n},M=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},Ot=e=>{let t=0;return n=>(t+=1,`${M(e)}_${M(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},N=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of k(e,t))r(n)};return r(t),n},kt=(e,t,n)=>Object.fromEntries(N(e,t).map(t=>[t,n(j(e,t).label)])),At=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=j(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let ee=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??ee}}},jt=e=>{let{document:t,input:n,inputIndex:r,nextId:i}=e,a=j(t,n.id);if(n.id===`root`)throw new d(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let o=t.relationships[n.id];if(o===void 0)throw new d(`BAD_REQUEST`,`Canvas node ${n.id} is detached.`,`Choose a reachable node from canvas tree.`);let s=n.parentId??o.parentId;if(!A(t.nodes[s]))throw new d(`BAD_REQUEST`,`Canvas node ${s} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let c=kt(t,n.id,i),l={document:t,rootId:n.id,parentId:s,inputIndex:r,sourceSortKey:o.sortKey,map:c},u=N(t,n.id).map(e=>At(l,e)),f=c[n.id];if(f===void 0)throw Error(`Missing duplicate root id for ${n.id}`);return{operations:u,summary:{sourceId:n.id,newId:f,name:a.label,component:a.component,descendantIdMap:Object.fromEntries(Object.entries(c).filter(([e])=>e!==n.id))}}},Mt=(e,t,n)=>{if(t.length===0)throw new d(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let r=Ot(n),i=t.map((t,n)=>jt({document:e,input:t,inputIndex:n,nextId:r}));return{operations:i.flatMap(e=>e.operations),duplicatedNodes:i.map(e=>e.summary)}},Nt=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,k(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),Pt=(e,t)=>{let n=(t.children.get(e.parentId)??[]).filter(t=>t!==e.nodeId);return{parentId:e.parentId,index:Math.max(0,Math.min(e.index??n.length,n.length))}},Ft=(e,t)=>{let n=`before`in e?e.before:e.after;if(n===e.nodeId||t.document.nodes[n]===void 0)throw new d(`BAD_REQUEST`,`Sibling ${n} is not a valid move target.`,`Choose another current sibling node.`);let r=t.parentOf.get(n);if(r===void 0)throw new d(`BAD_REQUEST`,`Sibling ${n} is detached.`,`Choose a reachable sibling from canvas tree.`);let i=(t.children.get(r)??[]).filter(t=>t!==e.nodeId).indexOf(n);return{parentId:r,index:`before`in e?i:i+1}},It=(e,t)=>`parentId`in e?Pt(e,t):Ft(e,t),Lt=(e,t,n)=>{if(e.nodeId===`root`||n.document.nodes[e.nodeId]===void 0)throw new d(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Dt(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!A(n.document.nodes[t.parentId]))throw new d(`BAD_REQUEST`,`Canvas node ${t.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},Rt=(e,t,n)=>{let r=n.parentOf.get(e.nodeId);r!==void 0&&(n.children.set(r,(n.children.get(r)??[]).filter(t=>t!==e.nodeId)),n.affected.add(r));let i=[...n.children.get(t.parentId)??[]],a=[],o={...n.document.relationships},s=e=>{let t=i[e];return t===void 0?null:o[t]?.sortKey??null},c=null;try{let e=s(t.index-1),n=s(t.index),r=ke(e,n);(e===null||e.localeCompare(r)<0)&&(n===null||r.localeCompare(n)<0)&&(c=r)}catch{c=null}if(c===null){let n=[...i];n.splice(t.index,0,e.nodeId);let r=Ae(null,null,n.length).toSorted((e,t)=>e.localeCompare(t));for(let[e,i]of n.entries()){let n=r[e];if(n===void 0)throw Error(`Missing generated move sort key.`);let s={parentId:t.parentId,sortKey:n};o[i]=s,a.push({op:`setParentage`,nodeId:i,parentage:s})}}else{let n={parentId:t.parentId,sortKey:c};o[e.nodeId]=n,a.push({op:`setParentage`,nodeId:e.nodeId,parentage:n})}return i.splice(t.index,0,e.nodeId),n.children.set(t.parentId,i),n.parentOf.set(e.nodeId,t.parentId),n.affected.add(t.parentId),{operations:a,document:{...n.document,relationships:o}}},zt=(e,t)=>{if(t.length===0)throw new d(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=Nt(e),r=[];return{operations:t.flatMap(e=>{let t=It(e,n);Lt(e,t,n),r.push({nodeId:e.nodeId,...t});let i=Rt(e,t,n);return n.document=i.document,i.operations}),moves:r,affectedParents:Array.from(n.affected,e=>({parentId:e,children:[...n.children.get(e)??[]]}))}},Bt=(e,t)=>{let n=m(new Set(Object.keys(t))).filter(t=>e.typography?.[t]!==void 0);return n.length===0?null:{op:`patchTypography`,nodeId:e.id,typography:{clear:n}}},Vt=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),Ht=(e,t)=>{let n=new Map((e.additionalStyles?.declarations??[]).map(e=>[e.id,e]));for(let[e,r]of Object.entries(t)){let t=Array.from(n,([,e])=>e).filter(t=>t.property.toLowerCase()===e);for(let e of t)n.delete(e.id);if(r===null||p.safeParse({[e]:r}).success)continue;let i=t[0]?.id??`css-${e}`.slice(0,190),a=i;for(let e=1;n.has(a);e+=1)a=`${i}-${String(e)}`;let o=pe.safeParse({id:a,property:e,value:String(r),enabled:!0});if(!o.success)throw new d(`BAD_REQUEST`,`Style ${e} is not safe CSS.`,`Use a valid CSS property without imports, expressions, or executable URLs.`);n.set(a,o.data)}let r=[];for(let e of n.values()){if(r.length===128)throw new d(`BAD_REQUEST`,`Too many additional CSS declarations.`,`Remove unused declarations before adding more; no styles were changed.`);r.push(e)}let i=r.length===0&&e.additionalStyles===void 0?void 0:{declarations:r},a=rt(e.additionalStyles,i);return a===null?null:{op:`patchAdditionalStyles`,nodeId:e.id,additionalStyles:a}},Ut=(e,t,n,r)=>{let i=new Set(Object.keys(r)),a=r=>[...o(t,r,e),...o(n,r,e)],s=be(t.layout??{},i,{horizontal:a(`horizontal`),vertical:a(`vertical`)});for(let[e,t]of[[`width`,`horizontal`],[`height`,`vertical`]]){let n=r[e];(n===`fill`||n===`hug`)&&(s[t]={mode:n})}return JSON.stringify(s)===JSON.stringify(t.layout??{})?null:{op:`setLayout`,nodeId:t.id,layout:Object.keys(s).length===0?`default`:s}},Wt=(e,t,n)=>{let r={...n};for(let[i,a]of[[`width`,`horizontal`],[`height`,`vertical`]])if(n[i]===`fill`||n[i]===`hug`){r[i]=null;for(let n of o(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},Gt=(e,t,n)=>{let r=Wt(e,t,n),i=Ht(t,r),a=Object.fromEntries(Object.entries(r).filter(([e,t])=>p.safeParse({[e]:t}).success)),o={...t,styles:{...t.styles},...i!==null&&{additionalStyles:x(t.additionalStyles,i.additionalStyles)??void 0}};for(let[e,t]of Object.entries(a))t===null?Reflect.deleteProperty(o.styles,e):o.styles[e]=t;let s=Ut(e,t,o,n),c=Bt(t,r),l=(t.component===`text`?[`color`]:[`background`,`background-color`,`background-image`]).some(e=>Object.hasOwn(r,e))&&t.appearance?.fills!==void 0?[{op:`setAppearance`,nodeId:t.id,appearance:{clear:[`fills`]}}]:[];return[...Object.keys(a).length>0?[{op:`setStyles`,nodeId:t.id,styles:p.parse(a)}]:[],...l,...c===null?[]:[c],...s===null?[]:[s],...i===null?[]:[i]]},Kt=e=>{let t=new Map;for(let n of e)for(let e of n.nodeIds){let r=t.get(e)??{};for(let[e,t]of Object.entries(n.styles)){let n=Vt(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},qt=(e,t)=>{let n=[...Kt(t)].flatMap(([t,n])=>{let r=e.nodes[t];if(r===void 0)throw new d(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use current stable node ids.`);return Gt(e,r,n)});if(n.length===0)throw new d(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return n},Jt=(e,t)=>{let n={...e.styles};for(let[e,r]of Object.entries(t.styles))r==null?Reflect.deleteProperty(n,e):n[e]=r;let r=t.clear??[];for(let e of r)Reflect.deleteProperty(n,e);let i=ye(e.typography,{clear:[...m(new Set([...Object.keys(t.styles),...r]))]});return P({...e,styles:n},`typography`,i??`default`)},Yt=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`patchTypography`,`setLayout`,`setAdditionalStyles`,`patchAdditionalStyles`,`setParentage`]),Xt=e=>Yt.has(e.op),P=(e,t,n)=>{let r={...e};return n==="default"?Reflect.deleteProperty(r,t):Reflect.set(r,t,n),r},Zt=(e,t)=>{switch(t.op){case`setText`:if(e.component!==`text`)throw new d(`BAD_REQUEST`,`Canvas node ${e.id} is not editable text.`,`Use the text node id from canvas tree.`);return{...e,props:{...e.props,text:t.text}};case`setLabel`:return{...e,label:t.label,labelOrigin:`user`};case`setStyles`:return Jt(e,t);case`setAppearance`:{let n={...e.appearance},r=t.appearance.clear??[];for(let e of r)Reflect.deleteProperty(n,e);let i={...e,appearance:n};return Object.keys(n).length===0&&Reflect.deleteProperty(i,`appearance`),i}case`patchTypography`:return P(e,`typography`,ye(e.typography,t.typography)??`default`);case`setTypography`:return P(e,`typography`,t.typography);case`setLayout`:return P(e,`layout`,t.layout);case`patchAdditionalStyles`:{let n=x(e.additionalStyles,t.additionalStyles);return P(e,`additionalStyles`,n??`default`)}case`setAdditionalStyles`:return P(e,`additionalStyles`,t.additionalStyles)}},Qt=(e,t)=>{if(!Xt(t))throw Error(`Unexpected focused edit operation: ${t.op}`);if(t.op===`insertNode`){if(e.nodes[t.node.id]!==void 0)throw new d(`BAD_REQUEST`,`Duplicate id ${t.node.id} already exists.`,`Use a new client token for a new duplication.`);return{...e,nodes:{...e.nodes,[t.node.id]:t.node},relationships:{...e.relationships,[t.node.id]:t.parentage}}}let n=j(e,t.nodeId);return t.op===`setParentage`?{...e,relationships:{...e.relationships,[n.id]:t.parentage}}:{...e,nodes:{...e.nodes,[n.id]:Zt(n,t)}}},$t=e=>{let{nodeId:t,destination:n}=e;switch(n.kind){case`before`:return{nodeId:t,before:n.nodeId};case`after`:return{nodeId:t,after:n.nodeId};case`parent`:return{nodeId:t,parentId:n.parentId,...n.index!==void 0&&{index:n.index}}}},en=(e,t,n,r)=>{switch(e.kind){case`set_text`:return[{op:`setText`,nodeId:e.nodeId,text:e.text}];case`rename`:return[{op:`setLabel`,nodeId:e.nodeId,label:e.name,labelOrigin:`user`}];case`set_styles`:return qt(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=Mt(t.scene,e.nodeIds.map(t=>({id:t,...e.parentId!==void 0&&{parentId:e.parentId}})),i);return t.duplicatedNodes.push(...a.duplicatedNodes),a.operations}case`move`:{let n=zt(t.scene,[$t(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},tn=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=en(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=Qt(r.scene,e);r.operations.push(...t)}return{operations:r.operations,duplicatedNodes:r.duplicatedNodes,moves:r.moves,affectedParents:[...r.affectedParents].map(e=>({parentId:e,children:k(r.scene,e)}))}},F=e=>{switch(e.kind){case`set_text`:case`rename`:return[e.nodeId];case`set_styles`:return e.nodeIds;case`duplicate`:return[...e.nodeIds,...e.parentId===void 0?[]:[e.parentId]];case`move`:return[e.nodeId,e.destination.kind===`parent`?e.destination.parentId:e.destination.nodeId]}},nn=(e,t)=>e.kind===`duplicate`?[...e.nodeIds,...e.parentId===void 0||e.nodeIds.every(n=>t.relationships[n]?.parentId===e.parentId)?[]:[e.parentId]]:e.kind===`move`&&e.destination.kind===`parent`&&t.relationships[e.nodeId]?.parentId===e.destination.parentId?[e.nodeId]:F(e),rn=(e,t)=>{if(e.edits.length===0||e.edits.length>1e3)throw new d(`BAD_REQUEST`,`The edit batch exceeds the canonical operation limit.`,`Split larger changes into bounded batches.`);let n=new Set(e.edits.flatMap(e=>F(e)));if(n.size>1e3)throw new d(`BAD_REQUEST`,`A batch may target at most 1,000 nodes.`,`Split the edit into smaller batches.`);for(let e of n)j(t,e);let r={canvasId:e.canvasId,nodeIds:e.nodeIds??[]};for(let n of e.edits)a(r,t,nn(n,t))},I=e=>({execute:async t=>{let n=await O({remote:e},t.canvasId,t.baseVersion);rn(t,n);let r=tn(n,t.edits,t.idPrefix??`copy_${t.mutationId.replaceAll(`-`,``)}`);i({canvasId:t.canvasId,nodeIds:t.nodeIds??[]},n,r.operations.filter(e=>`nodeId`in e&&n.nodes[e.nodeId]!==void 0));let a=he.safeParse({canvasId:t.canvasId,mutationId:t.mutationId,documentFormatVersion:4,baseVersion:t.baseVersion,operations:r.operations});if(!a.success)throw new d(`BAD_REQUEST`,`The edit exceeds canonical canvas limits.`,a.error.issues[0]?.message??`Reduce the edit batch.`);let o=h.parse(await D(e).execute(a.data));return{...o,next:[`Reuse version ${String(o.version)} as baseVersion for the next edit; no extra read is required.`,`Render the affected screen at version ${String(o.version)} when ready for visual review.`],...r.duplicatedNodes.length>0&&{duplicatedNodes:r.duplicatedNodes},...r.moves.length>0&&{moves:r.moves,affectedParents:r.affectedParents}}}}),L=`canvas.render.getImport`,R=e=>new d(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),an=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),on=e=>{let t=e.failure;return new d(t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`CONVERSION_FAILED`?`BAD_REQUEST`:`INTERNAL`,t.message,t.retryable?"Retry the exact write. If it repeats, run `enhance doctor` and report the job id.":`Inspect the current canvas tree and correct the HTML or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},sn=async(e,t)=>{let n=me.safeParse(await e.query(L,{jobId:t}));if(!n.success)throw R(`HTML import status`);return n.data.job},cn=async(e,t,n)=>{let r=Date.now()+n,i=t;for(;i.state===`queued`||i.state===`running`;){if(Date.now()>=r)return i;await an(250),i=await sn(e,i.id)}if(i.state!==`succeeded`)throw on(i);return i},ln=async(e,t)=>{let n=ge.safeParse(await e.mutate(`canvas.render.importSource`,{canvasId:t.canvasId,expectedVersion:t.baseVersion,source:{kind:`html`,html:t.html,label:`Agent-authored HTML`,...t.idPrefix!==void 0&&{idPrefix:t.idPrefix}},destination:{kind:t.mode,targetNodeId:t.targetNodeId}}));if(!n.success)throw R(`HTML import creation`);return cn(e,n.data.job,t.renderTimeoutMs)},un=(e,t,n)=>({state:`failed`,mutationCommitted:!0,requestedVersion:n,...e instanceof d?{code:e.code,message:e.message,remediation:e.remediation,...e.fields!==void 0&&{fields:e.fields}}:{code:`INTERNAL`,message:`The post-write review render failed.`,remediation:`Render the committed version and affected area again; do not replay the write.`},next:[`enhance canvas render --canvas ${t.canvasId} --expected-version ${String(n)}`,`Do not replay the committed write with a new mutation id.`]}),dn=async(e,t,n)=>{try{return await e.execute({canvasId:t.canvasId,expectedVersion:n.result.version,target:{kind:`node`,nodeId:n.result.rootNodeId},sourceState:null,scale:t.renderScale,outputPath:t.renderOutputPath,overwrite:t.overwriteRender,timeoutMs:t.renderTimeoutMs,retryClientToken:t.renderClientToken})}catch(e){return un(e,t,n.result.version)}},fn=async(e,t)=>{let n=await O({remote:e},t.canvasId,t.result.version);return t.result.insertedNodeIds.map(e=>{let t=n.nodes[e];return{id:e,name:t?.label??``,component:t?.component??``}})},z=(e,t)=>({canvasId:e.canvasId,mutationCommitted:!0,jobId:t.id,mutationId:t.result.mutationId,rootNodeId:t.result.rootNodeId,mode:e.mode,targetNodeId:e.targetNodeId,previousVersion:t.result.previousVersion,version:t.result.version,insertedNodeIds:t.result.insertedNodeIds,removedNodeIds:t.result.removedNodeIds,affected:{inserted:t.result.insertedNodeIds.length,changed:0,removed:t.result.removedNodeIds.length},affectedBounds:t.result.affectedBounds}),pn=e=>({state:`pending`,canvasId:e.canvasId,jobId:e.id,phase:e.phase,status:{tool:`capability_query`,arguments:{capability:L,input:{jobId:e.id}}},next:[`Read the existing import status; do not start another import.`]}),B=(e,t)=>({execute:async n=>{if(n.selectionNodeIds!==void 0&&n.selectionNodeIds.length>0){let t=await O({remote:e},n.canvasId,n.baseVersion);a({canvasId:n.canvasId,nodeIds:n.selectionNodeIds},t,[n.targetNodeId])}let r=await E(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await ln(e,n);if(i.state!==`succeeded`)return pn(i);if(n.review===`none`)return z(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await dn(t,n,i),o=[];try{o=await fn(e,i)}catch{o=[]}return{...z(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),V=(e,t,n)=>{try{Fe(e,t,{flag:n?`w`:`wx`,mode:384}),je(e,384)}catch(t){let n=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new d(n,n===`CONFLICT`?`Refusing to replace ${e}.`:`Could not write ${e}.`,n===`CONFLICT`?`Choose another --output path or pass --force deliberately.`:`Create the parent directory and verify it is writable, then retry.`)}},H=e=>({write:t=>{if(t.outputPath!==null){let e=v.resolve(t.outputPath);return V(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=v.join(e,`sensitive`);Pe(n,{recursive:!0,mode:448}),je(n,448);let r=v.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return V(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),U=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`,`prototype.attach`],W=e=>new d(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),mn=async(e,t)=>{let n=Date.now()+3e5,r=50;for(;Date.now()<n;){let n=s.safeParse(await e.query(U[3],t));if(!n.success)throw W(`status`);if(n.data.state===`ready`||n.data.state===`failed`)return n.data;if(n.data.state===`abandoned`)throw new d(`NOT_FOUND`,`Prototype deployment ${t.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);await Le(r),r=Math.min(r*2,1e3)}throw Error(`prototype ingestion is still running`)},hn=async(e,t,n,r)=>{let i=c.safeParse(await e.mutate(U[1],{canvasId:t.canvasId,...t.prototypeId!==null&&{prototypeId:t.prototypeId},clientToken:t.clientToken,nodeId:t.nodeId,title:t.title,entryPath:n.manifest.entryPath,artifact:n.identity,box:t.box}));if(!i.success)throw W(`artifact creation`);if(r(i.data.deploymentId),i.data.state===`uploading`&&await e.upload({url:i.data.upload.url,headers:i.data.upload.headers,body:n.open()}),(i.data.state===`uploading`||i.data.state===`queued`)&&!l.safeParse(await e.mutate(U[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId})).success)throw W(`artifact submission`);return i.data},gn=e=>{if(e.state!==`failed`)return;let{failure:t}=e;throw new d(`BAD_REQUEST`,t.message,`Fix the build and publish it with a new client token.`,t.path===void 0?void 0:{path:t.path})},_n=async(e,t,n)=>{let r=ie.safeParse(await e.query(U[0],{}));if(!r.success)throw W(`capabilities`);let i=await t.package({directory:n.directory,entryPath:n.entryPath,limits:r.data.limits}),a={deploymentId:null};try{let t=await hn(e,n,i,e=>{a.deploymentId=e}),r=await mn(e,{canvasId:n.canvasId,deploymentId:t.deploymentId});gn(r);let o=re.safeParse(await e.mutate(U[4],{canvasId:n.canvasId,deploymentId:t.deploymentId,baseVersion:n.baseVersion}));if(!o.success)throw W(`attachment`);return{...o.data,fileCount:r.fileCount,totalBytes:r.totalBytes,alreadyExists:t.alreadyExists,next:[o.data.openUrl,`enhance canvas render --canvas ${n.canvasId} --node-id ${o.data.nodeId} --expected-version ${String(o.data.version)}`]}}catch(e){throw e instanceof d&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||a.deploymentId===null?e:new fe(`Prototype deployment ${a.deploymentId} was created, but publishing did not complete.`,`Retry 'enhance prototype publish' with the same --client-token ${n.clientToken}.`)}finally{await i.dispose()}},vn=(e,t)=>({execute:async n=>_n(e,t,n)}),yn=[`transcript.get`],bn=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),xn=e=>({execute:async t=>{let n=f.safeParse(await e.query(yn[0],t));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid transcript response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return n.data.state===`ready`?{...n.data,guidance:`Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.`,next:bn(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),Sn=[`canvas.render.get`,`canvas.render.snapshot`],Cn=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),wn=e=>new d(e.failure?.reason===`VERSION_CHANGED`?`CONFLICT`:e.failure?.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:e.failure?.reason===`TARGET_INVALID`||e.failure?.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,e.failure?.message??`The snapshot job ended without a result.`,`Run 'enhance canvas tree --canvas ${e.canvasId}' and retry the exact snapshot if its recording node still exists.`,{jobId:e.id,phase:e.phase}),Tn=async(e,t)=>{let n=te.safeParse(await e.query(Sn[0],{jobId:t}));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return n.data.job},En=async(e,t,n,r)=>{let i=Date.now()+n.timeoutMs,a=Date.now(),o=t,s=0,c=``;for(;o.state===`queued`||o.state===`running`;){let t=Date.now(),l=`${o.state}:${o.phase}`;if((l!==c||t-s>=5e3)&&(r({event:`snapshot.progress`,jobId:o.id,state:o.state,phase:o.phase,elapsedMs:t-a,timeoutMs:n.timeoutMs,retryClientToken:n.retryClientToken}),s=t,c=l),t>=i)throw new d(`INTERNAL`,`Snapshot ${o.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${n.retryClientToken} and a larger --timeout-ms.`,{jobId:o.id,phase:o.phase});await Cn(),o=await Tn(e,o.id)}if(o.state!==`succeeded`||o.result.snapshot===void 0)throw wn(o);return{...o,result:{...o.result,snapshot:o.result.snapshot}}},Dn=async(e,t,n)=>{let r=ue.safeParse(await e.mutate(Sn[1],{canvasId:n.canvasId,recordingId:n.recordingId,atMs:n.atMs}));if(!r.success)throw new d(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");let i=await En(e,r.data.job,n,t),a=i.result.snapshot;return{jobId:i.id,canvasId:i.canvasId,...a,warnings:i.result.warnings,retryClientToken:n.retryClientToken,next:[`enhance canvas node --canvas ${i.canvasId} --node-id ${a.screenNodeId}`,`enhance canvas render --canvas ${i.canvasId} --node-id ${a.screenNodeId} --expected-version ${String(a.version)}`]}},On=(e,t)=>({execute:async n=>Dn(e,t,n)}),kn=new Date(`1980-01-01T00:00:00.000Z`),An=33188,jn=(e,t)=>new d(`BAD_REQUEST`,e,t),Mn=(e,t)=>{let n=y(`sha256`),r=0;return new Ye({transform:(e,t,i)=>{r+=e.byteLength,n.update(e),i(null,e)},flush:i=>{if(r!==e.bytes){i(Error(`prototype file ${e.path} changed while it was packaged`));return}t({path:e.path,contentType:e.contentType,bytes:r,sha256:n.digest(`hex`)}),i()}})},Nn=e=>{let n=u.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),r=Buffer.from(JSON.stringify(n),`utf8`);if(r.byteLength>e.limits.manifestBytes)throw jn(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(r,t,{mtime:kn,mode:An,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),n},Pn=async e=>{let t=new Ze,n=y(`sha256`),r=new Ye({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=Xe(t.outputStream,r,Ne(e.artifactPath));t.on(`error`,e=>r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)));let s=n=>{i.set(n.path,n),a.manifest===null&&i.size===e.files.length&&(a.manifest=Nn({zip:t,completed:i,...e}))};for(let n of e.files)t.addReadStreamLazy(n.path,{size:n.bytes,mtime:kn,mode:An,compress:!0,forceDosTimestamp:!0},e=>{e(null,Me(n.absolutePath).pipe(Mn(n,s)))});if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let c=await Ge(e.artifactPath);if(c.size>e.limits.artifactBytes)throw jn(`The packaged prototype artifact is too large.`,`This environment accepts ${String(e.limits.artifactBytes)} compressed bytes.`);return{manifest:a.manifest,bytes:c.size,sha256:n.digest(`hex`)}},Fn={".avif":`image/avif`,".css":`text/css; charset=utf-8`,".gif":`image/gif`,".html":`text/html; charset=utf-8`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".map":`application/json; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".mp3":`audio/mpeg`,".mp4":`video/mp4`,".ogg":`audio/ogg`,".otf":`font/otf`,".png":`image/png`,".svg":`image/svg+xml`,".ttf":`font/ttf`,".txt":`text/plain; charset=utf-8`,".wasm":`application/wasm`,".webm":`video/webm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`,".xml":`application/xml`},In=e=>Fn[v.extname(e).toLowerCase()]??`application/octet-stream`,Ln=async e=>{try{return await Ge(e)}catch{return null}},Rn=e=>Buffer.byteLength(e,`utf8`),G=(e,t)=>new d(`BAD_REQUEST`,e,t),zn=(e,t)=>{if(!_e.safeParse(e).success)throw G(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(Rn(e)>t.pathBytes)throw G(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},Bn=async(e,t,n,r)=>{let i=await He(t);if(n.has(i))throw G(`Cannot package the circular directory link at ${t}.`,`Pass a directory tree that can be read once from top to bottom.`);let a=new Set(n).add(i),{readdir:o}=await import(`node:fs/promises`),s=await o(t,{withFileTypes:!0}),c=[],l=s.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of l){let i=v.join(t,n.name),o=await Ln(i);if(o?.isDirectory()===!0){c.push(...await Bn(e,i,a,r));continue}if(o?.isFile()!==!0)throw G(`Cannot read ${i} as a prototype file.`,`Pass a directory containing only regular files and directory links.`);let s=v.relative(e,i).split(v.sep).join(`/`).normalize(`NFC`);zn(s,r),c.push({absolutePath:i,path:s,bytes:Number(o.size),contentType:In(i)})}return c},Vn=(e,t,n)=>{if(e.length===0)throw G(`The prototype build is empty.`,`Build the app before publishing it.`);if(e.length>n.fileCount)throw G(`The prototype has ${String(e.length)} files.`,`This environment currently accepts ${String(n.fileCount)} files per deployment.`);let r=new Set,i=0;for(let t of e){let e=ne(t.path);if(r.has(e))throw G(`The prototype path ${t.path} collides by case or Unicode normalization.`,`Rename one of the colliding files so the build is portable.`);if(r.add(e),t.bytes>n.fileBytes)throw G(`The prototype file ${t.path} is too large.`,`This environment accepts ${String(n.fileBytes)} bytes in one runtime file.`);if(i+=t.bytes,i>n.expandedBytes)throw G(`The prototype build is too large.`,`This environment accepts ${String(n.expandedBytes)} expanded bytes.`)}let a=e.find(e=>e.path===t);if(a===void 0)throw G(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw G(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},Hn=async e=>{let t=v.resolve(e.directory),n=await Ln(t);if(n===null)throw new d(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!n.isDirectory())throw G(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let r=e.entryPath.split(v.sep).join(`/`).normalize(`NFC`);zn(r,e.limits);let i=await Bn(t,t,new Set,e.limits);Vn(i,r,e.limits);let a=await Be(v.join(Oe(),`enhance-prototype-artifact-`)),o=v.join(a,`artifact.zip`);try{let t=await Pn({artifactPath:o,files:i,entryPath:r,limits:e.limits});return{identity:{protocolVersion:1,format:`zip`,bytes:t.bytes,sha256:t.sha256,fileCount:t.manifest.files.length,expandedBytes:t.manifest.files.reduce((e,t)=>e+t.bytes,0)},manifest:t.manifest,open:()=>Me(o),dispose:async()=>We(a,{recursive:!0})}}catch(e){throw await We(a,{recursive:!0}),e}},Un=()=>({package:Hn}),K=e=>_t(e.remote,H(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Wn=async(e,t)=>{let n=ce.parse(t);return D(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Gn=async(e,t,n)=>{let r=xe.parse(t);return K(e).execute({...r,retryClientToken:n})},Kn=async(e,t)=>{let n=Te.parse(t);return B(e.remote,K(e)).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},qn=async(e,t)=>{let n=le.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},Jn=async(e,t,n)=>{let r=Ce.parse(t);return vn(e.remote,Un()).execute({...r,clientToken:n})},Yn=async(e,t,n)=>{let r=ee.parse(t);return On(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},Xn=async(e,t)=>{let r=n.parse(t);return xn(e.remote).execute(r)},Zn=async(t,n,r,i)=>{switch(n){case`canvas.edit`:{let n=Se.parse(r),i=e(n.canvas);return I(t.remote).execute({canvasId:i.canvasId,nodeIds:i.nodeIds,baseVersion:n.baseVersion,edits:n.edits,mutationId:t.mutationKey.current(`canvas.applyOperations`,n)})}case`canvas.apply`:return Wn(t,r);case`canvas.render`:return Gn(t,r,i);case`canvas.writeHtml`:return Kn(t,r);case`comment.attention`:return qn(t,r);case`prototype.publish`:return Jn(t,r,i);case`recording.snapshot`:return Yn(t,r,i);case`transcript.read`:return Xn(t,r);default:throw TypeError(`${n} has no composite execution`)}},Qn=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??b();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Zn(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),$n=`/callback`,er=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),tr=e=>{let t=_.platform===`darwin`?{executable:`open`,arguments:[e]}:_.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=et(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},nr=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==$n){n.writeHead(404).end();return}if(r.searchParams.get(`state`)!==e.state){n.writeHead(400).end(`The OAuth state did not match. Return to the terminal and retry.`);return}let i=r.searchParams.get(`error`),a=r.searchParams.get(`code`);if(i!==null||a===null||a===``){n.writeHead(400).end(`Enhance authentication was not approved.`),e.completion.reject(Error(i??`the authorization response carried no code`));return}n.writeHead(200,{"content-type":`text/html; charset=utf-8`}).end(`<!doctype html><meta charset="utf-8"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>`),e.completion.resolve(a)},rr=e=>{let t=er(e.issuer,`oauth/authorize`);return t.search=new URLSearchParams({response_type:`code`,client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,code_challenge:e.challenge,code_challenge_method:`S256`}).toString(),t.href},ir=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=tt((n,r)=>{nr({state:e.state,completion:t},n,r)});await new Promise((e,t)=>{n.once(`error`,t),n.listen(0,`127.0.0.1`,e)});let r=n.address();if(r===null||typeof r==`string`)throw n.close(),Error(`the OAuth callback listener has no TCP port`);let i=`http://127.0.0.1:${String(r.port)}${$n}`,a=rr({...e,redirectUri:i}),o=()=>{t.reject(Error(`browser authorization cancelled`))};e.signal?.addEventListener(`abort`,o,{once:!0});let s=setTimeout(()=>{t.reject(Error(`browser authorization timed out`))},12e4);try{return e.signal?.throwIfAborted(),e.onReady(a),e.openBrowser&&tr(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},ar=e=>({authorize:async t=>{try{let n=Ie(32).toString(`base64url`),r=y(`sha256`).update(n).digest(`base64url`),i=Ie(32).toString(`base64url`),a=await ir({...t,challenge:r,state:i});return await e.exchangeOauthCode({issuer:t.issuer,clientId:t.clientId,code:a.code,redirectUri:a.redirectUri,verifier:n})}catch(e){throw new d(`UNAUTHORIZED`,e instanceof Error?`Browser authentication failed: ${e.message}.`:`Browser authentication failed.`,`Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.`)}}}),q=e=>e===void 0||e===``?void 0:e,or=((e,t,n)=>{let r=q(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=q(e.ENHANCE3_API_URL),a=v.join(t,`.config`,n.configDirectoryName),o=q(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&i!==n.apiUrl)throw TypeError(`Enhance development cannot use ${i}`);if(o!==void 0&&v.resolve(o)!==v.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}})(_.env,De(),{apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`}),sr=g.object({token:g.string().startsWith(`enh_`)}),cr=e=>{let t=v.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await Ve(t,`utf8`));return sr.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await ze(e,{recursive:!0,mode:448}),await Re(e,448);let r=v.join(e,`credentials.${String(_.pid)}.tmp`);await qe(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await Ue(r,t),await Re(t,384)},remove:async()=>{try{return await Ke(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},lr=g.object({access_token:g.string().min(1)}),ur=g.object({code:g.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),J=`Check network access and proxy settings for this API, then run enhance doctor again.`,Y=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,dr=e=>{let t=ur.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?dr(e.cause):e instanceof Error?e.name:`Network request failed`},X=(e,t)=>new d(`INTERNAL`,`${Y(e)} answered HTTP ${String(t)}.`,J),Z=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new d(`INTERNAL`,`Could not reach ${Y(e)}: ${dr(t)}.`,J)}},fr=async(e,t)=>{let n=await Z(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw X(e,n.status);return n},Q=(e,t,n=null)=>Qe({links:[$e({url:`${e}/trpc`,fetch:async(e,t)=>fr(e,{...t,signal:t?.signal??null}),headers:{...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),pr=async e=>{let t=await fetch(e);if(!t.ok)throw new d(t.status===404||t.status===403?`NOT_FOUND`:`INTERNAL`,`Render download answered HTTP ${String(t.status)}.`,`The result may have expired. Request a new render.`);return new Uint8Array(await t.arrayBuffer())},mr=async e=>{let t=await Z(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new d(`BAD_REQUEST`,`This Enhance API does not support browser authentication.`,`Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.`):new d(`INTERNAL`,`${Y(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,J);return t.json()},hr=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await Z(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw X(e,n.status);return n.json()},gr=async e=>{let t=await Z(new URL(`oauth/token`,e.issuer.endsWith(`/`)?e.issuer:`${e.issuer}/`),{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`authorization_code`,client_id:e.clientId,code:e.code,redirect_uri:e.redirectUri,code_verifier:e.verifier})});if(!t.ok)throw new d(`INTERNAL`,`${Y(e.issuer)} token exchange answered HTTP ${String(t.status)}`,J);return lr.parse(await t.json()).access_token},_r=async e=>{try{let t=await Z(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:X(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${Y(e)}.`}}},vr=(e,t,n)=>{let r=e.replace(/\/$/,``);return{authenticationConfig:async()=>mr(r),oauthMetadata:hr,exchangeOauthCode:gr,query:async(e,n)=>Q(r,await t.read()).query(e,n),queryWithToken:async(e,t,n)=>Q(r,n).query(e,t),mutate:async(e,i)=>Q(r,await t.read(),n.current(e,i)).mutation(e,i),mutateWithToken:async(e,t,n)=>Q(r,n).mutation(e,t),download:pr,upload:async e=>{let t=!(e.body instanceof Uint8Array),n=t?Je.toWeb(e.body):e.body,r={method:`PUT`,headers:e.headers,body:n,...t&&{duplex:`half`}},i=await fetch(e.url,r);if(!i.ok)throw new d(`INTERNAL`,`Signed upload answered HTTP ${String(i.status)}.`,`Retry the fixture command with the same source file.`);let a=i.headers.get(`etag`);if(a===null||a===``)throw new d(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return a.replaceAll(`"`,``)},health:async()=>_r(r)}},$=e=>Array.isArray(e)?e.map(e=>$(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,$(t)])),yr=(e,t,n)=>y(`sha256`).update(`${e}\0${t}\0${JSON.stringify($(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),br=()=>{let e=b(),t=!1;return{current:(n,r)=>t?yr(e,n,r):e,select:(n,r)=>{e=n??b(),t=r}}};export{ar as a,B as c,D as d,E as f,or as i,I as l,at as m,vr as n,Qn as o,_t as p,cr as r,H as s,br as t,O as u};
|
|
2
|
+
import{A as e,B as t,C as n,Ct as r,D as i,E as a,Et as o,G as s,H as c,J as l,K as u,M as d,N as f,S as ee,St as te,U as ne,V as re,W as ie,X as ae,Y as oe,Z as se,_ as ce,b as le,bt as ue,dt as de,j as fe,kt as pe,lt as p,mt as me,nt as m,ot as he,pt as ge,q as _e,rt as ve,st as h,tt as ye,ut as be,v as xe,w as Se,x as Ce,xt as we,y as Te,yt as Ee}from"./cli-output-identity.lib-B2oX7yo7.mjs";import{z as g}from"zod";import{homedir as De,tmpdir as Oe}from"node:os";import _ from"node:process";import{generateKeyBetween as ke,generateNKeysBetween as Ae}from"fractional-indexing";import{chmodSync as je,createReadStream as Me,createWriteStream as Ne,mkdirSync as Pe,writeFileSync as Fe}from"node:fs";import v from"node:path";import{createHash as y,randomBytes as Ie,randomUUID as b}from"node:crypto";import{setTimeout as Le}from"node:timers/promises";import{chmod as Re,mkdir as ze,mkdtemp as Be,readFile as Ve,realpath as He,rename as Ue,rm as We,stat as Ge,unlink as Ke,writeFile as qe}from"node:fs/promises";import{Readable as Je,Transform as Ye}from"node:stream";import{pipeline as Xe}from"node:stream/promises";import{ZipFile as Ze}from"yazl";import{createTRPCUntypedClient as Qe,httpLink as $e}from"@trpc/client";import{spawn as et}from"node:child_process";import{createServer as tt}from"node:http";const nt=(e,t)=>{let n=new Set(t),r=[],i=new Map,a=r;for(let t of e)n.has(t.id)&&(a=[],i.set(t.id,a)),a.push(t);return[...r,...t.flatMap(e=>i.get(e)??[])]},x=(e,t)=>{let n=new Set(t.clear),r=new Map((e?.declarations??[]).filter(e=>!n.has(e.id)).map(e=>[e.id,e])),i=t.set??[];for(let e of i)r.set(e.id,e);let a=Array.from(r,([,e])=>e);return a.length===0&&(t.empty===`remove`||e===void 0&&t.empty!==`keep`)?null:{declarations:t.order===void 0?a:nt(a,t.order)}},rt=(e,t)=>{let n=new Map(e?.declarations.map(e=>[e.id,e])),r=t?.declarations??[],i=new Set(r.map(e=>e.id)),a=Array.from(n,([e])=>e).filter(e=>!i.has(e)),o=r.filter(e=>{let t=n.get(e.id);return t?.property!==e.property||t.value!==e.value||t.enabled!==e.enabled}),s={...a.length>0&&{clear:a},...o.length>0&&{set:o}},c=x(e,s),l=r.map(e=>e.id),u=JSON.stringify(c?.declarations.map(e=>e.id)??[])!==JSON.stringify(l),d=t===void 0&&e!==void 0?`remove`:e===void 0&&t!==void 0&&r.length===0?`keep`:void 0;return d===void 0&&!u&&o.length===0&&a.length===0?null:{...s,...u&&{order:l},...d!==void 0&&{empty:d}}},it=/^enh_[\w-]{43}$/,S=e=>{let t=oe.parse(e);if(t.authentication.kind!==`agent`||t.person===null)throw new d(`UNAUTHORIZED`,`The credential is missing, expired, revoked, or invalid.`,`Run 'enhance auth login' and complete authentication in the browser.`);return{authenticated:!0,personId:t.person.id,displayName:t.person.displayName,tokenId:t.authentication.tokenId,tokenLabel:t.authentication.tokenLabel,expiresAt:t.authentication.expiresAt}},at=(e,t,n)=>({loginWithToken:async n=>{if(!it.test(n))throw new d(`BAD_REQUEST`,`Agent tokens begin with enh_ and contain 32 base64url bytes.`,`Pass a manual token from Settings to 'enhance auth login' through stdin.`);let r=S(await t.queryWithToken(`person.me`,{},n));return await e.write(n),r},loginWithBrowser:async r=>{let i=ae.parse(await t.authenticationConfig());if(i.method===`token`)throw new d(`BAD_REQUEST`,`Browser authentication is not configured for this Enhance environment.`,`Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.`);let a=await n.authorize({issuer:i.issuer,clientId:i.clientId,scope:i.scope,openBrowser:r.openBrowser,onReady:r.onReady,...r.signal!==void 0&&{signal:r.signal}});r.signal?.throwIfAborted();let o=se.parse(await t.mutateWithToken(`person.createAgentToken`,{label:r.label,expiresAt:null},a)),s=S(await t.queryWithToken(`person.me`,{},o.token));return r.signal?.throwIfAborted(),await e.write(o.token),s},status:async()=>{if(await e.read()===null)throw new d(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return S(await t.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),ot=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),st=e=>{if(e.byteLength<24||ot.some((t,n)=>e[n]!==t))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{width:t.getUint32(16),height:t.getUint32(20)}},ct=async(e,t)=>{let n=we.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid render download response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");let r=await e.download(n.data.download.url),i=st(r);if(i===null||r.byteLength!==t.result.bytes||i.width!==t.result.width||i.height!==t.result.height)throw new d(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return r},lt=[`canvas.render.create`,`canvas.render.get`],C=e=>new d(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),ut=e=>{let t=e.failure;if(t===null)return C(`render job`);let n=t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,r=t.reason===`VERSION_CHANGED`?`Run 'enhance canvas inspect --canvas ${e.canvasId}', then render its returned version.`:t.reason===`TARGET_NOT_FOUND`?`Run 'enhance canvas tree --canvas ${e.canvasId}' and choose a current node id.`:t.retryable?"Retry the render. If it repeats, run `enhance doctor` and report the job id.":`Change the target or scale using the failure details, then retry.`;return new d(n,t.message,r,{jobId:e.id,reason:t.reason,phase:t.phase})},dt=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),ft=async(e,t)=>{let n=te.safeParse(await e.query(lt[1],{jobId:t}));if(!n.success)throw C(`render status`);return n.data.job},pt=async(e,t)=>{let n=Date.now(),r=0,i=``,a=t.initial;for(;a.state===`queued`||a.state===`running`;){let o=Date.now(),s=`${a.state}:${a.phase}`;if((s!==i||o-r>=5e3)&&(t.progress({event:`render.progress`,jobId:a.id,state:a.state,phase:a.phase,elapsedMs:o-n,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),r=o,i=s),o>=t.deadline)throw new d(`INTERNAL`,`Render ${a.id} did not finish before the local timeout.`,`Retry the exact command with --client-token ${t.retryClientToken} and a larger --timeout-ms. If the render remains unavailable, run \`enhance doctor\` and report the job id.`,{jobId:a.id,phase:a.phase});await dt(250),a=await ft(e,a.id)}if(a.state!==`succeeded`)throw ut(a);return a},mt=e=>{let t=`enhance canvas inspect --canvas ${e.canvasId}`;return e.result.sourceState===void 0?e.target.kind===`node`?[t,`enhance canvas node --canvas ${e.canvasId} --node-id ${e.target.nodeId}`]:[t]:[`Inspect the PNG at path before persisting this moment.`,`enhance recording snapshot --canvas ${e.canvasId} --recording-id ${e.result.sourceState.recordingId} --at-ms ${String(e.result.sourceState.settledAtMs)}`,t]},ht=(e,t)=>({jobId:e.id,canvasId:e.canvasId,requestedVersion:e.requestedVersion,loadedVersion:e.result.loadedVersion,target:e.target,sourceState:e.result.sourceState??null,bounds:e.result.bounds,width:e.result.width,height:e.result.height,scale:e.result.scale,contentType:e.result.contentType,bytes:e.result.bytes,warnings:e.result.warnings,path:t.path,sensitive:!0,cleanup:t.temporary?`unlink-after-use`:`caller-owned`,...t.deleteAfter!==null&&{deleteAfter:t.deleteAfter.toISOString()},next:mt(e)}),gt=async(e,t)=>{let n=Ee.safeParse(await e.remote.mutate(lt[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,format:`png`}));if(!n.success)throw C(`render creation`);let r=await pt(e.remote,{initial:n.data.job,deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress}),i=await ct(e.remote,r),a=e.files.write({body:i,outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()});return ht(r,a)},_t=(e,t,n,r=()=>null)=>({execute:async i=>gt({remote:e,files:t,now:n,progress:r},i)}),w={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},T=async e=>{try{return await e(),!0}catch{return!1}},vt=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await T(async()=>e.mutate(w.renew,{...i,nodeIds:[...i.nodeIds],activityId:n})),o=!1)},c=setInterval(()=>void s(),r);return{activityId:n,update:async e=>{a||(i={...i,...e},await s())},finish:async()=>{a||(a=!0,clearInterval(c),await T(async()=>e.mutate(w.end,{canvasId:i.canvasId,activityId:n})))}}},E=e=>({begin:async t=>{try{let n=ve.safeParse(await e.mutate(w.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?vt(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>T(async()=>e.mutate(w.end,{canvasId:t,activityId:n}))}),yt=new Set([`insertPrototype`,`insertText`,`setBox`]),bt=e=>yt.has(e.op),xt=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,St=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],Ct=e=>[...new Set(e.operations.flatMap(e=>St(e)))].slice(0,100),wt=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:bt(e)?e.box==="default"?null:e.box:null,Tt=e=>{let t=e[0];if(t===void 0)return null;let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}},Et=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:4}),r=h.safeParse(n);if(!r.success)throw new d(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data},D=e=>({execute:async(t,n)=>{if(n?.activity===!1)return Et(e,t);let r=await E(e).begin({canvasId:t.canvasId,phase:xt(t),nodeIds:Ct(t),bounds:Tt(t.operations.flatMap(e=>{let t=wt(e);return t===null?[]:[t]}))});try{return await Et(e,t)}finally{await r?.finish()}}}),O=async(e,t,n)=>{let i=de.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:t}));if(!i.success)throw new d(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(i.data.version!==n)throw new d(`CONFLICT`,`Canvas version ${String(i.data.version)} no longer matches --base-version ${String(n)}.`,`An earlier identical request may already have committed. Do not repeat it with a new client token. Inspect the intended scope with 'enhance canvas tree --canvas <the original canvas or selection link>' and reconcile against version ${String(i.data.version)} before submitting a new edit.`);let a=r.safeParse(i.data.document);if(a.success)return a.data;throw new d(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},k=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),A=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),j=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new d(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Dt=(e,t)=>{let n=new Set,r=t=>{for(let i of k(e,t))n.add(i),r(i)};return r(t),n},M=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},Ot=e=>{let t=0;return n=>(t+=1,`${M(e)}_${M(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},N=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of k(e,t))r(n)};return r(t),n},kt=(e,t,n)=>Object.fromEntries(N(e,t).map(t=>[t,n(j(e,t).label)])),At=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=j(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let ee=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??ee}}},jt=e=>{let{document:t,input:n,inputIndex:r,nextId:i}=e,a=j(t,n.id);if(n.id===`root`)throw new d(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let o=t.relationships[n.id];if(o===void 0)throw new d(`BAD_REQUEST`,`Canvas node ${n.id} is detached.`,`Choose a reachable node from canvas tree.`);let s=n.parentId??o.parentId;if(!A(t.nodes[s]))throw new d(`BAD_REQUEST`,`Canvas node ${s} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let c=kt(t,n.id,i),l={document:t,rootId:n.id,parentId:s,inputIndex:r,sourceSortKey:o.sortKey,map:c},u=N(t,n.id).map(e=>At(l,e)),f=c[n.id];if(f===void 0)throw Error(`Missing duplicate root id for ${n.id}`);return{operations:u,summary:{sourceId:n.id,newId:f,name:a.label,component:a.component,descendantIdMap:Object.fromEntries(Object.entries(c).filter(([e])=>e!==n.id))}}},Mt=(e,t,n)=>{if(t.length===0)throw new d(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let r=Ot(n),i=t.map((t,n)=>jt({document:e,input:t,inputIndex:n,nextId:r}));return{operations:i.flatMap(e=>e.operations),duplicatedNodes:i.map(e=>e.summary)}},Nt=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,k(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),Pt=(e,t)=>{let n=(t.children.get(e.parentId)??[]).filter(t=>t!==e.nodeId);return{parentId:e.parentId,index:Math.max(0,Math.min(e.index??n.length,n.length))}},Ft=(e,t)=>{let n=`before`in e?e.before:e.after;if(n===e.nodeId||t.document.nodes[n]===void 0)throw new d(`BAD_REQUEST`,`Sibling ${n} is not a valid move target.`,`Choose another current sibling node.`);let r=t.parentOf.get(n);if(r===void 0)throw new d(`BAD_REQUEST`,`Sibling ${n} is detached.`,`Choose a reachable sibling from canvas tree.`);let i=(t.children.get(r)??[]).filter(t=>t!==e.nodeId).indexOf(n);return{parentId:r,index:`before`in e?i:i+1}},It=(e,t)=>`parentId`in e?Pt(e,t):Ft(e,t),Lt=(e,t,n)=>{if(e.nodeId===`root`||n.document.nodes[e.nodeId]===void 0)throw new d(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Dt(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!A(n.document.nodes[t.parentId]))throw new d(`BAD_REQUEST`,`Canvas node ${t.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},Rt=(e,t,n)=>{let r=n.parentOf.get(e.nodeId);r!==void 0&&(n.children.set(r,(n.children.get(r)??[]).filter(t=>t!==e.nodeId)),n.affected.add(r));let i=[...n.children.get(t.parentId)??[]],a=[],o={...n.document.relationships},s=e=>{let t=i[e];return t===void 0?null:o[t]?.sortKey??null},c=null;try{let e=s(t.index-1),n=s(t.index),r=ke(e,n);(e===null||e.localeCompare(r)<0)&&(n===null||r.localeCompare(n)<0)&&(c=r)}catch{c=null}if(c===null){let n=[...i];n.splice(t.index,0,e.nodeId);let r=Ae(null,null,n.length).toSorted((e,t)=>e.localeCompare(t));for(let[e,i]of n.entries()){let n=r[e];if(n===void 0)throw Error(`Missing generated move sort key.`);let s={parentId:t.parentId,sortKey:n};o[i]=s,a.push({op:`setParentage`,nodeId:i,parentage:s})}}else{let n={parentId:t.parentId,sortKey:c};o[e.nodeId]=n,a.push({op:`setParentage`,nodeId:e.nodeId,parentage:n})}return i.splice(t.index,0,e.nodeId),n.children.set(t.parentId,i),n.parentOf.set(e.nodeId,t.parentId),n.affected.add(t.parentId),{operations:a,document:{...n.document,relationships:o}}},zt=(e,t)=>{if(t.length===0)throw new d(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=Nt(e),r=[];return{operations:t.flatMap(e=>{let t=It(e,n);Lt(e,t,n),r.push({nodeId:e.nodeId,...t});let i=Rt(e,t,n);return n.document=i.document,i.operations}),moves:r,affectedParents:Array.from(n.affected,e=>({parentId:e,children:[...n.children.get(e)??[]]}))}},Bt=(e,t)=>{let n=m(new Set(Object.keys(t))).filter(t=>e.typography?.[t]!==void 0);return n.length===0?null:{op:`patchTypography`,nodeId:e.id,typography:{clear:n}}},Vt=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),Ht=(e,t)=>{let n=new Map((e.additionalStyles?.declarations??[]).map(e=>[e.id,e]));for(let[e,r]of Object.entries(t)){let t=Array.from(n,([,e])=>e).filter(t=>t.property.toLowerCase()===e);for(let e of t)n.delete(e.id);if(r===null||p.safeParse({[e]:r}).success)continue;let i=t[0]?.id??`css-${e}`.slice(0,190),a=i;for(let e=1;n.has(a);e+=1)a=`${i}-${String(e)}`;let o=pe.safeParse({id:a,property:e,value:String(r),enabled:!0});if(!o.success)throw new d(`BAD_REQUEST`,`Style ${e} is not safe CSS.`,`Use a valid CSS property without imports, expressions, or executable URLs.`);n.set(a,o.data)}let r=[];for(let e of n.values()){if(r.length===128)throw new d(`BAD_REQUEST`,`Too many additional CSS declarations.`,`Remove unused declarations before adding more; no styles were changed.`);r.push(e)}let i=r.length===0&&e.additionalStyles===void 0?void 0:{declarations:r},a=rt(e.additionalStyles,i);return a===null?null:{op:`patchAdditionalStyles`,nodeId:e.id,additionalStyles:a}},Ut=(e,t,n,r)=>{let i=new Set(Object.keys(r)),a=r=>[...o(t,r,e),...o(n,r,e)],s=be(t.layout??{},i,{horizontal:a(`horizontal`),vertical:a(`vertical`)});for(let[e,t]of[[`width`,`horizontal`],[`height`,`vertical`]]){let n=r[e];(n===`fill`||n===`hug`)&&(s[t]={mode:n})}return JSON.stringify(s)===JSON.stringify(t.layout??{})?null:{op:`setLayout`,nodeId:t.id,layout:Object.keys(s).length===0?`default`:s}},Wt=(e,t,n)=>{let r={...n};for(let[i,a]of[[`width`,`horizontal`],[`height`,`vertical`]])if(n[i]===`fill`||n[i]===`hug`){r[i]=null;for(let n of o(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},Gt=(e,t,n)=>{let r=Wt(e,t,n),i=Ht(t,r),a=Object.fromEntries(Object.entries(r).filter(([e,t])=>p.safeParse({[e]:t}).success)),o={...t,styles:{...t.styles},...i!==null&&{additionalStyles:x(t.additionalStyles,i.additionalStyles)??void 0}};for(let[e,t]of Object.entries(a))t===null?Reflect.deleteProperty(o.styles,e):o.styles[e]=t;let s=Ut(e,t,o,n),c=Bt(t,r),l=(t.component===`text`?[`color`]:[`background`,`background-color`,`background-image`]).some(e=>Object.hasOwn(r,e))&&t.appearance?.fills!==void 0?[{op:`setAppearance`,nodeId:t.id,appearance:{clear:[`fills`]}}]:[];return[...Object.keys(a).length>0?[{op:`setStyles`,nodeId:t.id,styles:p.parse(a)}]:[],...l,...c===null?[]:[c],...s===null?[]:[s],...i===null?[]:[i]]},Kt=e=>{let t=new Map;for(let n of e)for(let e of n.nodeIds){let r=t.get(e)??{};for(let[e,t]of Object.entries(n.styles)){let n=Vt(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},qt=(e,t)=>{let n=[...Kt(t)].flatMap(([t,n])=>{let r=e.nodes[t];if(r===void 0)throw new d(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use current stable node ids.`);return Gt(e,r,n)});if(n.length===0)throw new d(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return n},Jt=(e,t)=>{let n={...e.styles};for(let[e,r]of Object.entries(t.styles))r==null?Reflect.deleteProperty(n,e):n[e]=r;let r=t.clear??[];for(let e of r)Reflect.deleteProperty(n,e);let i=ye(e.typography,{clear:[...m(new Set([...Object.keys(t.styles),...r]))]});return P({...e,styles:n},`typography`,i??`default`)},Yt=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`patchTypography`,`setLayout`,`setAdditionalStyles`,`patchAdditionalStyles`,`setParentage`]),Xt=e=>Yt.has(e.op),P=(e,t,n)=>{let r={...e};return n==="default"?Reflect.deleteProperty(r,t):Reflect.set(r,t,n),r},Zt=(e,t)=>{switch(t.op){case`setText`:if(e.component!==`text`)throw new d(`BAD_REQUEST`,`Canvas node ${e.id} is not editable text.`,`Use the text node id from canvas tree.`);return{...e,props:{...e.props,text:t.text}};case`setLabel`:return{...e,label:t.label,labelOrigin:`user`};case`setStyles`:return Jt(e,t);case`setAppearance`:{let n={...e.appearance},r=t.appearance.clear??[];for(let e of r)Reflect.deleteProperty(n,e);let i={...e,appearance:n};return Object.keys(n).length===0&&Reflect.deleteProperty(i,`appearance`),i}case`patchTypography`:return P(e,`typography`,ye(e.typography,t.typography)??`default`);case`setTypography`:return P(e,`typography`,t.typography);case`setLayout`:return P(e,`layout`,t.layout);case`patchAdditionalStyles`:{let n=x(e.additionalStyles,t.additionalStyles);return P(e,`additionalStyles`,n??`default`)}case`setAdditionalStyles`:return P(e,`additionalStyles`,t.additionalStyles)}},Qt=(e,t)=>{if(!Xt(t))throw Error(`Unexpected focused edit operation: ${t.op}`);if(t.op===`insertNode`){if(e.nodes[t.node.id]!==void 0)throw new d(`BAD_REQUEST`,`Duplicate id ${t.node.id} already exists.`,`Use a new client token for a new duplication.`);return{...e,nodes:{...e.nodes,[t.node.id]:t.node},relationships:{...e.relationships,[t.node.id]:t.parentage}}}let n=j(e,t.nodeId);return t.op===`setParentage`?{...e,relationships:{...e.relationships,[n.id]:t.parentage}}:{...e,nodes:{...e.nodes,[n.id]:Zt(n,t)}}},$t=e=>{let{nodeId:t,destination:n}=e;switch(n.kind){case`before`:return{nodeId:t,before:n.nodeId};case`after`:return{nodeId:t,after:n.nodeId};case`parent`:return{nodeId:t,parentId:n.parentId,...n.index!==void 0&&{index:n.index}}}},en=(e,t,n,r)=>{switch(e.kind){case`set_text`:return[{op:`setText`,nodeId:e.nodeId,text:e.text}];case`rename`:return[{op:`setLabel`,nodeId:e.nodeId,label:e.name,labelOrigin:`user`}];case`set_styles`:return qt(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=Mt(t.scene,e.nodeIds.map(t=>({id:t,...e.parentId!==void 0&&{parentId:e.parentId}})),i);return t.duplicatedNodes.push(...a.duplicatedNodes),a.operations}case`move`:{let n=zt(t.scene,[$t(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},tn=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=en(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=Qt(r.scene,e);r.operations.push(...t)}return{operations:r.operations,duplicatedNodes:r.duplicatedNodes,moves:r.moves,affectedParents:[...r.affectedParents].map(e=>({parentId:e,children:k(r.scene,e)}))}},F=e=>{switch(e.kind){case`set_text`:case`rename`:return[e.nodeId];case`set_styles`:return e.nodeIds;case`duplicate`:return[...e.nodeIds,...e.parentId===void 0?[]:[e.parentId]];case`move`:return[e.nodeId,e.destination.kind===`parent`?e.destination.parentId:e.destination.nodeId]}},nn=(e,t)=>e.kind===`duplicate`?[...e.nodeIds,...e.parentId===void 0||e.nodeIds.every(n=>t.relationships[n]?.parentId===e.parentId)?[]:[e.parentId]]:e.kind===`move`&&e.destination.kind===`parent`&&t.relationships[e.nodeId]?.parentId===e.destination.parentId?[e.nodeId]:F(e),rn=(e,t)=>{if(e.edits.length===0||e.edits.length>1e3)throw new d(`BAD_REQUEST`,`The edit batch exceeds the canonical operation limit.`,`Split larger changes into bounded batches.`);let n=new Set(e.edits.flatMap(e=>F(e)));if(n.size>1e3)throw new d(`BAD_REQUEST`,`A batch may target at most 1,000 nodes.`,`Split the edit into smaller batches.`);for(let e of n)j(t,e);let r={canvasId:e.canvasId,nodeIds:e.nodeIds??[]};for(let n of e.edits)a(r,t,nn(n,t))},I=e=>({execute:async t=>{let n=await O({remote:e},t.canvasId,t.baseVersion);rn(t,n);let r=tn(n,t.edits,t.idPrefix??`copy_${t.mutationId.replaceAll(`-`,``)}`);i({canvasId:t.canvasId,nodeIds:t.nodeIds??[]},n,r.operations.filter(e=>`nodeId`in e&&n.nodes[e.nodeId]!==void 0));let a=he.safeParse({canvasId:t.canvasId,mutationId:t.mutationId,documentFormatVersion:4,baseVersion:t.baseVersion,operations:r.operations});if(!a.success)throw new d(`BAD_REQUEST`,`The edit exceeds canonical canvas limits.`,a.error.issues[0]?.message??`Reduce the edit batch.`);let o=h.parse(await D(e).execute(a.data));return{...o,next:[`Reuse version ${String(o.version)} as baseVersion for the next edit; no extra read is required.`,`Render the affected screen at version ${String(o.version)} when ready for visual review.`],...r.duplicatedNodes.length>0&&{duplicatedNodes:r.duplicatedNodes},...r.moves.length>0&&{moves:r.moves,affectedParents:r.affectedParents}}}}),L=`canvas.render.getImport`,R=e=>new d(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),an=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),on=e=>{let t=e.failure;return new d(t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`CONVERSION_FAILED`?`BAD_REQUEST`:`INTERNAL`,t.message,t.retryable?"Retry the exact write. If it repeats, run `enhance doctor` and report the job id.":`Inspect the current canvas tree and correct the HTML or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},sn=async(e,t)=>{let n=me.safeParse(await e.query(L,{jobId:t}));if(!n.success)throw R(`HTML import status`);return n.data.job},cn=async(e,t,n)=>{let r=Date.now()+n,i=t;for(;i.state===`queued`||i.state===`running`;){if(Date.now()>=r)return i;await an(250),i=await sn(e,i.id)}if(i.state!==`succeeded`)throw on(i);return i},ln=async(e,t)=>{let n=ge.safeParse(await e.mutate(`canvas.render.importSource`,{canvasId:t.canvasId,expectedVersion:t.baseVersion,source:{kind:`html`,html:t.html,label:`Agent-authored HTML`,...t.idPrefix!==void 0&&{idPrefix:t.idPrefix}},destination:{kind:t.mode,targetNodeId:t.targetNodeId}}));if(!n.success)throw R(`HTML import creation`);return cn(e,n.data.job,t.renderTimeoutMs)},un=(e,t,n)=>({state:`failed`,mutationCommitted:!0,requestedVersion:n,...e instanceof d?{code:e.code,message:e.message,remediation:e.remediation,...e.fields!==void 0&&{fields:e.fields}}:{code:`INTERNAL`,message:`The post-write review render failed.`,remediation:`Render the committed version and affected area again; do not replay the write.`},next:[`enhance canvas render --canvas ${t.canvasId} --expected-version ${String(n)}`,`Do not replay the committed write with a new mutation id.`]}),dn=async(e,t,n)=>{try{return await e.execute({canvasId:t.canvasId,expectedVersion:n.result.version,target:{kind:`node`,nodeId:n.result.rootNodeId},sourceState:null,scale:t.renderScale,outputPath:t.renderOutputPath,overwrite:t.overwriteRender,timeoutMs:t.renderTimeoutMs,retryClientToken:t.renderClientToken})}catch(e){return un(e,t,n.result.version)}},fn=async(e,t)=>{let n=await O({remote:e},t.canvasId,t.result.version);return t.result.insertedNodeIds.map(e=>{let t=n.nodes[e];return{id:e,name:t?.label??``,component:t?.component??``}})},z=(e,t)=>({canvasId:e.canvasId,mutationCommitted:!0,jobId:t.id,mutationId:t.result.mutationId,rootNodeId:t.result.rootNodeId,mode:e.mode,targetNodeId:e.targetNodeId,previousVersion:t.result.previousVersion,version:t.result.version,insertedNodeIds:t.result.insertedNodeIds,removedNodeIds:t.result.removedNodeIds,affected:{inserted:t.result.insertedNodeIds.length,changed:0,removed:t.result.removedNodeIds.length},affectedBounds:t.result.affectedBounds}),pn=e=>({state:`pending`,canvasId:e.canvasId,jobId:e.id,phase:e.phase,status:{tool:`capability_query`,arguments:{capability:L,input:{jobId:e.id}}},next:[`Read the existing import status; do not start another import.`]}),B=(e,t)=>({execute:async n=>{if(n.selectionNodeIds!==void 0&&n.selectionNodeIds.length>0){let t=await O({remote:e},n.canvasId,n.baseVersion);a({canvasId:n.canvasId,nodeIds:n.selectionNodeIds},t,[n.targetNodeId])}let r=await E(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await ln(e,n);if(i.state!==`succeeded`)return pn(i);if(n.review===`none`)return z(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await dn(t,n,i),o=[];try{o=await fn(e,i)}catch{o=[]}return{...z(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),V=(e,t,n)=>{try{Fe(e,t,{flag:n?`w`:`wx`,mode:384}),je(e,384)}catch(t){let n=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new d(n,n===`CONFLICT`?`Refusing to replace ${e}.`:`Could not write ${e}.`,n===`CONFLICT`?`Choose another --output path or pass --force deliberately.`:`Create the parent directory and verify it is writable, then retry.`)}},H=e=>({write:t=>{if(t.outputPath!==null){let e=v.resolve(t.outputPath);return V(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=v.join(e,`sensitive`);Pe(n,{recursive:!0,mode:448}),je(n,448);let r=v.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return V(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),U=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`,`prototype.attach`],W=e=>new d(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),mn=async(e,t)=>{let n=Date.now()+3e5,r=50;for(;Date.now()<n;){let n=s.safeParse(await e.query(U[3],t));if(!n.success)throw W(`status`);if(n.data.state===`ready`||n.data.state===`failed`)return n.data;if(n.data.state===`abandoned`)throw new d(`NOT_FOUND`,`Prototype deployment ${t.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);await Le(r),r=Math.min(r*2,1e3)}throw Error(`prototype ingestion is still running`)},hn=async(e,t,n,r)=>{let i=c.safeParse(await e.mutate(U[1],{canvasId:t.canvasId,...t.prototypeId!==null&&{prototypeId:t.prototypeId},clientToken:t.clientToken,nodeId:t.nodeId,title:t.title,entryPath:n.manifest.entryPath,artifact:n.identity,box:t.box}));if(!i.success)throw W(`artifact creation`);if(r(i.data.deploymentId),i.data.state===`uploading`&&await e.upload({url:i.data.upload.url,headers:i.data.upload.headers,body:n.open()}),(i.data.state===`uploading`||i.data.state===`queued`)&&!l.safeParse(await e.mutate(U[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId})).success)throw W(`artifact submission`);return i.data},gn=e=>{if(e.state!==`failed`)return;let{failure:t}=e;throw new d(`BAD_REQUEST`,t.message,`Fix the build and publish it with a new client token.`,t.path===void 0?void 0:{path:t.path})},_n=async(e,t,n)=>{let r=ie.safeParse(await e.query(U[0],{}));if(!r.success)throw W(`capabilities`);let i=await t.package({directory:n.directory,entryPath:n.entryPath,limits:r.data.limits}),a={deploymentId:null};try{let t=await hn(e,n,i,e=>{a.deploymentId=e}),r=await mn(e,{canvasId:n.canvasId,deploymentId:t.deploymentId});gn(r);let o=re.safeParse(await e.mutate(U[4],{canvasId:n.canvasId,deploymentId:t.deploymentId,baseVersion:n.baseVersion}));if(!o.success)throw W(`attachment`);return{...o.data,fileCount:r.fileCount,totalBytes:r.totalBytes,alreadyExists:t.alreadyExists,next:[o.data.openUrl,`enhance canvas render --canvas ${n.canvasId} --node-id ${o.data.nodeId} --expected-version ${String(o.data.version)}`]}}catch(e){throw e instanceof d&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||a.deploymentId===null?e:new fe(`Prototype deployment ${a.deploymentId} was created, but publishing did not complete.`,`Retry 'enhance prototype publish' with the same --client-token ${n.clientToken}.`)}finally{await i.dispose()}},vn=(e,t)=>({execute:async n=>_n(e,t,n)}),yn=[`transcript.get`],bn=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),xn=e=>({execute:async t=>{let n=f.safeParse(await e.query(yn[0],t));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid transcript response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return n.data.state===`ready`?{...n.data,guidance:`Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.`,next:bn(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),Sn=[`canvas.render.get`,`canvas.render.snapshot`],Cn=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),wn=e=>new d(e.failure?.reason===`VERSION_CHANGED`?`CONFLICT`:e.failure?.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:e.failure?.reason===`TARGET_INVALID`||e.failure?.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,e.failure?.message??`The snapshot job ended without a result.`,`Run 'enhance canvas tree --canvas ${e.canvasId}' and retry the exact snapshot if its recording node still exists.`,{jobId:e.id,phase:e.phase}),Tn=async(e,t)=>{let n=te.safeParse(await e.query(Sn[0],{jobId:t}));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return n.data.job},En=async(e,t,n,r)=>{let i=Date.now()+n.timeoutMs,a=Date.now(),o=t,s=0,c=``;for(;o.state===`queued`||o.state===`running`;){let t=Date.now(),l=`${o.state}:${o.phase}`;if((l!==c||t-s>=5e3)&&(r({event:`snapshot.progress`,jobId:o.id,state:o.state,phase:o.phase,elapsedMs:t-a,timeoutMs:n.timeoutMs,retryClientToken:n.retryClientToken}),s=t,c=l),t>=i)throw new d(`INTERNAL`,`Snapshot ${o.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${n.retryClientToken} and a larger --timeout-ms.`,{jobId:o.id,phase:o.phase});await Cn(),o=await Tn(e,o.id)}if(o.state!==`succeeded`||o.result.snapshot===void 0)throw wn(o);return{...o,result:{...o.result,snapshot:o.result.snapshot}}},Dn=async(e,t,n)=>{let r=ue.safeParse(await e.mutate(Sn[1],{canvasId:n.canvasId,recordingId:n.recordingId,atMs:n.atMs}));if(!r.success)throw new d(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");let i=await En(e,r.data.job,n,t),a=i.result.snapshot;return{jobId:i.id,canvasId:i.canvasId,...a,warnings:i.result.warnings,retryClientToken:n.retryClientToken,next:[`enhance canvas node --canvas ${i.canvasId} --node-id ${a.screenNodeId}`,`enhance canvas render --canvas ${i.canvasId} --node-id ${a.screenNodeId} --expected-version ${String(a.version)}`]}},On=(e,t)=>({execute:async n=>Dn(e,t,n)}),kn=new Date(`1980-01-01T00:00:00.000Z`),An=33188,jn=(e,t)=>new d(`BAD_REQUEST`,e,t),Mn=(e,t)=>{let n=y(`sha256`),r=0;return new Ye({transform:(e,t,i)=>{r+=e.byteLength,n.update(e),i(null,e)},flush:i=>{if(r!==e.bytes){i(Error(`prototype file ${e.path} changed while it was packaged`));return}t({path:e.path,contentType:e.contentType,bytes:r,sha256:n.digest(`hex`)}),i()}})},Nn=e=>{let n=u.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),r=Buffer.from(JSON.stringify(n),`utf8`);if(r.byteLength>e.limits.manifestBytes)throw jn(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(r,t,{mtime:kn,mode:An,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),n},Pn=async e=>{let t=new Ze,n=y(`sha256`),r=new Ye({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=Xe(t.outputStream,r,Ne(e.artifactPath));t.on(`error`,e=>r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)));let s=n=>{i.set(n.path,n),a.manifest===null&&i.size===e.files.length&&(a.manifest=Nn({zip:t,completed:i,...e}))};for(let n of e.files)t.addReadStreamLazy(n.path,{size:n.bytes,mtime:kn,mode:An,compress:!0,forceDosTimestamp:!0},e=>{e(null,Me(n.absolutePath).pipe(Mn(n,s)))});if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let c=await Ge(e.artifactPath);if(c.size>e.limits.artifactBytes)throw jn(`The packaged prototype artifact is too large.`,`This environment accepts ${String(e.limits.artifactBytes)} compressed bytes.`);return{manifest:a.manifest,bytes:c.size,sha256:n.digest(`hex`)}},Fn={".avif":`image/avif`,".css":`text/css; charset=utf-8`,".gif":`image/gif`,".html":`text/html; charset=utf-8`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".map":`application/json; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".mp3":`audio/mpeg`,".mp4":`video/mp4`,".ogg":`audio/ogg`,".otf":`font/otf`,".png":`image/png`,".svg":`image/svg+xml`,".ttf":`font/ttf`,".txt":`text/plain; charset=utf-8`,".wasm":`application/wasm`,".webm":`video/webm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`,".xml":`application/xml`},In=e=>Fn[v.extname(e).toLowerCase()]??`application/octet-stream`,Ln=async e=>{try{return await Ge(e)}catch{return null}},Rn=e=>Buffer.byteLength(e,`utf8`),G=(e,t)=>new d(`BAD_REQUEST`,e,t),zn=(e,t)=>{if(!_e.safeParse(e).success)throw G(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(Rn(e)>t.pathBytes)throw G(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},Bn=async(e,t,n,r)=>{let i=await He(t);if(n.has(i))throw G(`Cannot package the circular directory link at ${t}.`,`Pass a directory tree that can be read once from top to bottom.`);let a=new Set(n).add(i),{readdir:o}=await import(`node:fs/promises`),s=await o(t,{withFileTypes:!0}),c=[],l=s.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of l){let i=v.join(t,n.name),o=await Ln(i);if(o?.isDirectory()===!0){c.push(...await Bn(e,i,a,r));continue}if(o?.isFile()!==!0)throw G(`Cannot read ${i} as a prototype file.`,`Pass a directory containing only regular files and directory links.`);let s=v.relative(e,i).split(v.sep).join(`/`).normalize(`NFC`);zn(s,r),c.push({absolutePath:i,path:s,bytes:Number(o.size),contentType:In(i)})}return c},Vn=(e,t,n)=>{if(e.length===0)throw G(`The prototype build is empty.`,`Build the app before publishing it.`);if(e.length>n.fileCount)throw G(`The prototype has ${String(e.length)} files.`,`This environment currently accepts ${String(n.fileCount)} files per deployment.`);let r=new Set,i=0;for(let t of e){let e=ne(t.path);if(r.has(e))throw G(`The prototype path ${t.path} collides by case or Unicode normalization.`,`Rename one of the colliding files so the build is portable.`);if(r.add(e),t.bytes>n.fileBytes)throw G(`The prototype file ${t.path} is too large.`,`This environment accepts ${String(n.fileBytes)} bytes in one runtime file.`);if(i+=t.bytes,i>n.expandedBytes)throw G(`The prototype build is too large.`,`This environment accepts ${String(n.expandedBytes)} expanded bytes.`)}let a=e.find(e=>e.path===t);if(a===void 0)throw G(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw G(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},Hn=async e=>{let t=v.resolve(e.directory),n=await Ln(t);if(n===null)throw new d(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!n.isDirectory())throw G(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let r=e.entryPath.split(v.sep).join(`/`).normalize(`NFC`);zn(r,e.limits);let i=await Bn(t,t,new Set,e.limits);Vn(i,r,e.limits);let a=await Be(v.join(Oe(),`enhance-prototype-artifact-`)),o=v.join(a,`artifact.zip`);try{let t=await Pn({artifactPath:o,files:i,entryPath:r,limits:e.limits});return{identity:{protocolVersion:1,format:`zip`,bytes:t.bytes,sha256:t.sha256,fileCount:t.manifest.files.length,expandedBytes:t.manifest.files.reduce((e,t)=>e+t.bytes,0)},manifest:t.manifest,open:()=>Me(o),dispose:async()=>We(a,{recursive:!0})}}catch(e){throw await We(a,{recursive:!0}),e}},Un=()=>({package:Hn}),K=e=>_t(e.remote,H(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Wn=async(e,t)=>{let n=ce.parse(t);return D(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Gn=async(e,t,n)=>{let r=xe.parse(t);return K(e).execute({...r,retryClientToken:n})},Kn=async(e,t)=>{let n=Te.parse(t);return B(e.remote,K(e)).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},qn=async(e,t)=>{let n=le.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},Jn=async(e,t,n)=>{let r=Ce.parse(t);return vn(e.remote,Un()).execute({...r,clientToken:n})},Yn=async(e,t,n)=>{let r=ee.parse(t);return On(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},Xn=async(e,t)=>{let r=n.parse(t);return xn(e.remote).execute(r)},Zn=async(t,n,r,i)=>{switch(n){case`canvas.edit`:{let n=Se.parse(r),i=e(n.canvas);return I(t.remote).execute({canvasId:i.canvasId,nodeIds:i.nodeIds,baseVersion:n.baseVersion,edits:n.edits,mutationId:t.mutationKey.current(`canvas.applyOperations`,n)})}case`canvas.apply`:return Wn(t,r);case`canvas.render`:return Gn(t,r,i);case`canvas.writeHtml`:return Kn(t,r);case`comment.attention`:return qn(t,r);case`prototype.publish`:return Jn(t,r,i);case`recording.snapshot`:return Yn(t,r,i);case`transcript.read`:return Xn(t,r);default:throw TypeError(`${n} has no composite execution`)}},Qn=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??b();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Zn(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),$n=`/callback`,er=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),tr=e=>{let t=_.platform===`darwin`?{executable:`open`,arguments:[e]}:_.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=et(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},nr=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==$n){n.writeHead(404).end();return}if(r.searchParams.get(`state`)!==e.state){n.writeHead(400).end(`The OAuth state did not match. Return to the terminal and retry.`);return}let i=r.searchParams.get(`error`),a=r.searchParams.get(`code`);if(i!==null||a===null||a===``){n.writeHead(400).end(`Enhance authentication was not approved.`),e.completion.reject(Error(i??`the authorization response carried no code`));return}n.writeHead(200,{"content-type":`text/html; charset=utf-8`}).end(`<!doctype html><meta charset="utf-8"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>`),e.completion.resolve(a)},rr=e=>{let t=er(e.issuer,`oauth/authorize`);return t.search=new URLSearchParams({response_type:`code`,client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,code_challenge:e.challenge,code_challenge_method:`S256`}).toString(),t.href},ir=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=tt((n,r)=>{nr({state:e.state,completion:t},n,r)});await new Promise((e,t)=>{n.once(`error`,t),n.listen(0,`127.0.0.1`,e)});let r=n.address();if(r===null||typeof r==`string`)throw n.close(),Error(`the OAuth callback listener has no TCP port`);let i=`http://127.0.0.1:${String(r.port)}${$n}`,a=rr({...e,redirectUri:i}),o=()=>{t.reject(Error(`browser authorization cancelled`))};e.signal?.addEventListener(`abort`,o,{once:!0});let s=setTimeout(()=>{t.reject(Error(`browser authorization timed out`))},12e4);try{return e.signal?.throwIfAborted(),e.onReady(a),e.openBrowser&&tr(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},ar=e=>({authorize:async t=>{try{let n=Ie(32).toString(`base64url`),r=y(`sha256`).update(n).digest(`base64url`),i=Ie(32).toString(`base64url`),a=await ir({...t,challenge:r,state:i});return await e.exchangeOauthCode({issuer:t.issuer,clientId:t.clientId,code:a.code,redirectUri:a.redirectUri,verifier:n})}catch(e){throw new d(`UNAUTHORIZED`,e instanceof Error?`Browser authentication failed: ${e.message}.`:`Browser authentication failed.`,`Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.`)}}}),q=e=>e===void 0||e===``?void 0:e,or=((e,t,n)=>{let r=q(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=q(e.ENHANCE3_API_URL),a=v.join(t,`.config`,n.configDirectoryName),o=q(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&i!==n.apiUrl)throw TypeError(`Enhance development cannot use ${i}`);if(o!==void 0&&v.resolve(o)!==v.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}})(_.env,De(),{apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`}),sr=g.object({token:g.string().startsWith(`enh_`)}),cr=e=>{let t=v.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await Ve(t,`utf8`));return sr.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await ze(e,{recursive:!0,mode:448}),await Re(e,448);let r=v.join(e,`credentials.${String(_.pid)}.tmp`);await qe(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await Ue(r,t),await Re(t,384)},remove:async()=>{try{return await Ke(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},lr=g.object({access_token:g.string().min(1)}),ur=g.object({code:g.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),J=`Check network access and proxy settings for this API, then run enhance doctor again.`,Y=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,dr=e=>{let t=ur.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?dr(e.cause):e instanceof Error?e.name:`Network request failed`},X=(e,t)=>new d(`INTERNAL`,`${Y(e)} answered HTTP ${String(t)}.`,J),Z=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new d(`INTERNAL`,`Could not reach ${Y(e)}: ${dr(t)}.`,J)}},fr=async(e,t)=>{let n=await Z(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw X(e,n.status);return n},Q=(e,t,n=null)=>Qe({links:[$e({url:`${e}/trpc`,fetch:async(e,t)=>fr(e,{...t,signal:t?.signal??null}),headers:{...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),pr=async e=>{let t=await fetch(e);if(!t.ok)throw new d(t.status===404||t.status===403?`NOT_FOUND`:`INTERNAL`,`Render download answered HTTP ${String(t.status)}.`,`The result may have expired. Request a new render.`);return new Uint8Array(await t.arrayBuffer())},mr=async e=>{let t=await Z(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new d(`BAD_REQUEST`,`This Enhance API does not support browser authentication.`,`Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.`):new d(`INTERNAL`,`${Y(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,J);return t.json()},hr=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await Z(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw X(e,n.status);return n.json()},gr=async e=>{let t=await Z(new URL(`oauth/token`,e.issuer.endsWith(`/`)?e.issuer:`${e.issuer}/`),{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`authorization_code`,client_id:e.clientId,code:e.code,redirect_uri:e.redirectUri,code_verifier:e.verifier})});if(!t.ok)throw new d(`INTERNAL`,`${Y(e.issuer)} token exchange answered HTTP ${String(t.status)}`,J);return lr.parse(await t.json()).access_token},_r=async e=>{try{let t=await Z(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:X(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${Y(e)}.`}}},vr=(e,t,n)=>{let r=e.replace(/\/$/,``);return{authenticationConfig:async()=>mr(r),oauthMetadata:hr,exchangeOauthCode:gr,query:async(e,n)=>Q(r,await t.read()).query(e,n),queryWithToken:async(e,t,n)=>Q(r,n).query(e,t),mutate:async(e,i)=>Q(r,await t.read(),n.current(e,i)).mutation(e,i),mutateWithToken:async(e,t,n)=>Q(r,n).mutation(e,t),download:pr,upload:async e=>{let t=!(e.body instanceof Uint8Array),n=t?Je.toWeb(e.body):e.body,r={method:`PUT`,headers:e.headers,body:n,...t&&{duplex:`half`}},i=await fetch(e.url,r);if(!i.ok)throw new d(`INTERNAL`,`Signed upload answered HTTP ${String(i.status)}.`,`Retry the fixture command with the same source file.`);let a=i.headers.get(`etag`);if(a===null||a===``)throw new d(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return a.replaceAll(`"`,``)},health:async()=>_r(r)}},$=e=>Array.isArray(e)?e.map(e=>$(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,$(t)])),yr=(e,t,n)=>y(`sha256`).update(`${e}\0${t}\0${JSON.stringify($(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),br=()=>{let e=b(),t=!1;return{current:(n,r)=>t?yr(e,n,r):e,select:(n,r)=>{e=n??b(),t=r}}};export{ar as a,B as c,D as d,E as f,or as i,I as l,at as m,vr as n,Qn as o,_t as p,cr as r,H as s,br as t,O as u};
|