@enhance-eng/enhance-dev 0.1.26-dev.sha-e25164d9c5e2 → 0.1.27-dev.sha-3dce62542ab4
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-DHYR1EKD.mjs +32 -0
- package/dist/main.mjs +13 -13
- package/dist/mcp-main.mjs +42 -1
- package/dist/mcp-server.adapter-DMQEuPGm.mjs +4 -0
- package/dist/mcp.mjs +1 -1
- package/dist/mutation-key.adapter-BN-fQG_0.mjs +2 -0
- package/package.json +1 -1
- package/dist/cli-output-identity.lib-DImbm4C3.mjs +0 -73
- package/dist/mcp-server.adapter-0sYWDrrU.mjs +0 -4
- package/dist/mutation-key.adapter-CyZogRZp.mjs +0 -2
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{At as e,G as t,Gn as n,In as r,Nt as i,Ot as a,Qn as o,Z as s,c,cr as l,er as u,f as ee,jt as d,n as f,nt as p,o as te,r as m,t as h,u as g,wt as _}from"./cli-output-identity.lib-DImbm4C3.mjs";import{z as v}from"zod";import{readFileSync as y}from"node:fs";import b from"node:path";import{createHash as x,randomUUID as S}from"node:crypto";import{readFile as ne,rm as re}from"node:fs/promises";import{StdioServerTransport as ie}from"@modelcontextprotocol/server/stdio";import{CLIENT_INFO_META_KEY as C,McpServer as ae}from"@modelcontextprotocol/server";import{AsyncLocalStorage as oe}from"node:async_hooks";const w=new oe,T=v.object({method:v.literal(`initialize`),params:v.object({clientInfo:v.object({name:v.string(),version:v.string()})})}),E=v.object({[C]:v.object({name:v.string(),version:v.string()}).optional()}),se=()=>w.getStore(),ce=(e,t)=>{let n=E.safeParse(e.mcpReq.envelope),i=n.success?n.data[C]:void 0,a=e.mcpReq.envelope===void 0?void 0:r({path:`local_mcp`,...i!==void 0&&{name:i.name,version:i.version}});return w.run(a,t)},le=e=>{let t=e??new ie,n={metadata:r({path:`local_mcp`}),isInitialized:!1},i=(e,t)=>{let i=T.safeParse(e);!n.isInitialized&&i.success&&(n.metadata=r({path:`local_mcp`,...i.data.params.clientInfo}),n.isInitialized=!0),a.onmessage?.(e,t)},a={start:async()=>{Object.assign(t,{onmessage:i,onclose:()=>a.onclose?.(),onerror:e=>a.onerror?.(e)}),await t.start()},send:async(e,n)=>t.send(e,n),close:async()=>t.close()};return{transport:a,metadata:()=>n.metadata}},D=()=>({current:se,run:ce,createStdio:le}),O=async(e,t,n)=>{let r=await ne(t.path),i=S(),a=`enhance://artifact/${i}`;if(n===`embedded`&&t.cleanup===`unlink-after-use`)try{await re(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:p.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}}},ue=async(e,t,n)=>{let r=s.safeParse(t);if(!r.success)return null;let i=[],a=r.data.complete,o=[];for(let t of r.data.results){let r=p.safeParse(t.outcome);if(!r.success){o.push({...t,pixelsDelivered:!1});continue}try{let a=await O(e,r.data,n);i.push(a),o.push({...t,outcome:a.metadata,pixelsDelivered:!0,contentIndex:i.length,artifact:a.artifact})}catch{a=!1,o.push({id:t.id,target:t.target,maxOutputPixels:t.maxOutputPixels,pixelsDelivered:!1,outcome:{state:`delivery_unavailable`,operation:{kind:`canvas-render`,canvasId:r.data.canvasId,jobId:r.data.jobId},requestedVersion:r.data.requestedVersion,loadedVersion:r.data.loadedVersion,next:[`Read operation_status with includeImage true to collect the existing render.`]}})}}return{value:{...r.data,complete:a,results:o},detail:null,attachments:i}},de=/(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu,fe=/[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu,k=e=>JSON.stringify(e),A=(e,t=``)=>typeof e==`string`?fe.test(e)||de.test(t)&&!t.endsWith(`Id`):Array.isArray(e)?e.some(e=>A(e,t)):typeof e!=`object`||!e?!1:Reflect.get(e,`sensitive`)===!0||Object.entries(e).some(([e,t])=>A(t,e)),j=(e,t,n)=>{let r=S(),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:k(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:k(o)},{type:`resource_link`,name:`Protected Enhance result`,uri:i,mimeType:`application/json`}],structuredContent:o}},M=e=>new i(`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]))),N=async(e,t,n)=>{let r=await ue(e,t,n);if(r!==null)return r;let i=p.safeParse(t);if(i.success){let t=await O(e,i.data,n);return{value:t.metadata,detail:null,attachments:[t]}}let a=m(t);if(a===null)return{value:t,detail:null,attachments:[]};let o=a.detail??a.value,s=p.safeParse(o.review);if(!s.success)return{...a,attachments:[]};try{let t=await O(e,s.data,n),r={...o,review:{...t.metadata,artifact:t.artifact}},i=m(r);return{value:i?.value??r,detail:i?.detail??null,attachments:[t]}}catch{let e={...o,review:{state:`unavailable`,mutationCommitted:!0,requestedVersion:o.version,retry:{tool:`canvas_render`,arguments:{canvas:o.canvasId,expectedVersion:o.version,target:s.data.target}}},next:[`Retry the render of the committed version; do not replay the write.`]},t=m(e);return{value:t?.value??e,detail:t?.detail??null,attachments:[]}}},P=(e,t)=>{let n={ok:!0,result:f(e,t)};return{content:[{type:`text`,text:k(n)}],structuredContent:n}},F=(e,t=`enhance`)=>({success:async(e,n,r)=>{let i=f(n,t),a=await N(e,i,r),o=a.attachments,s=o.length===1?o[0]:void 0,c=k(a.value);if(A(a.value)||o.length===0&&a.detail===null&&Buffer.byteLength(c)>2e4)return j(e,c,r);let l=a.detail===null?null:j(e,k(a.detail),r),u={ok:!0,result:a.value,...s!==void 0&&{artifact:s.artifact},...l!==null&&{detail:l.structuredContent.artifact}};return{content:[{type:`text`,text:k(u)},...o.map(e=>e.image),...l?.content.filter(e=>e.type!==`text`)??[]],structuredContent:u}},inline:e=>P(e,t),structured:e=>({structuredContent:e,content:[{type:`text`,text:k(e)}]}),failure:n=>{let r=h(te(n instanceof v.ZodError?M(n):n),t),i={ok:!1,error:r.code===`UNAUTHORIZED`?{...r,remediation:e}:r};return{content:[{type:`text`,text:k(i)}],structuredContent:i,isError:!0}}}),I=v.object({ok:v.literal(!1),error:v.object({code:v.string(),message:v.string(),remediation:v.string(),fields:v.array(v.object({path:v.string(),message:v.string()})).optional()})}),L=v.object({uri:v.string(),mimeType:v.string(),bytes:v.number().int().nonnegative()}),R=v.object({ok:v.literal(!0),artifact:L}),z=v.object({id:v.string(),operation:v.enum([`query`,`mutation`]),effect:v.enum([`read`,`write`,`delete`,`external`]),idempotency:v.enum([`none`,`single`,`composite`]),summary:v.string(),useWhen:v.string(),preconditions:v.array(v.string()),inputSchema:v.unknown(),exampleInput:v.unknown(),output:v.array(v.object({name:v.string(),required:v.boolean(),meaning:v.string()})),result:v.string(),recovery:v.array(v.string()),next:v.array(v.string()),schemaDigest:v.string(),guidanceDigest:v.string(),behaviorDigest:v.string()}),B=z.pick({id:!0,operation:!0,effect:!0,summary:!0,useWhen:!0}),V=v.union([v.object({ok:v.literal(!0),result:v.unknown(),artifact:L.optional(),detail:L.optional()}),R,I]),pe=v.union([v.object({ok:v.literal(!0),result:v.object({matches:v.array(B),totalMatches:v.number().int().nonnegative(),truncated:v.boolean(),bestContract:z.optional(),detailRequired:v.object({capability:v.string()}).optional()})}),I]),me=v.union([v.object({ok:v.literal(!0),result:z}),I]),he=v.object({capability:v.string().min(1).describe(`Exact query id from an available complete contract.`),input:v.record(v.string(),v.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`)}),H=v.object({capability:v.string().min(1).describe(`Exact mutation id from an available complete contract.`),input:v.record(v.string(),v.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`),clientToken:v.uuid().optional().describe(`Stable UUID reused only when retrying this exact mutation input.`)}),ge=D(),U=(e,t)=>({invoke:async n=>e.invoke({...n,clientMetadata:ge.current()??t?.()??r({path:`local_mcp`})})}),W=v.enum([`apply-canvas-design`,`design-on-canvas`,`publish-prototype`,`respond-to-feedback`]),_e=v.object({name:W,description:v.string().min(1),body:v.string().min(1)}),G=`Before designing on a canvas, responding to feedback, publishing a prototype or applying a canvas design, call workflow_guide with the matching workflow and follow its guidance.`,K=(e,t)=>{let n=W.options.map(t=>{let n=y(b.join(e,t,`SKILL.md`),`utf8`),r=/^---\r?\nname: ([^\r\n]+)\r?\ndescription: ([^\r\n]+)\r?\n---\r?\n([\s\S]+)$/u.exec(n),i=_e.parse({name:r?.[1],description:r?.[2],body:r?.[3]});if(i.name!==t)throw Error(`Workflow name does not match its folder: ${t}`);return i});return{instructions:[G,t].filter(Boolean).join(` `),register:e=>{for(let t of n)e.registerPrompt(t.name,{description:t.description},()=>({messages:[{role:`user`,content:{type:`text`,text:t.body}}]}));e.registerTool(`workflow_guide`,{title:`Load an Enhance workflow`,description:G,inputSchema:v.strictObject({workflow:W}),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},({workflow:e})=>({content:n.filter(t=>t.name===e).map(e=>({type:`text`,text:e.body}))}))}}},q=D(),J=v.uuid().optional().describe(`Reuse only when retrying this exact mutation.`),ve=t.pick({baseVersion:!0,targetNodeId:!0,html:!0,idPrefix:!0}).extend({canvas:v.string().min(1).describe(`Canvas UUID or complete canvas/page/selection URL. Preserve every supplied page and selection.`),mode:v.enum([`insert-children`,`replace`]).default(`insert-children`),clientToken:J}),ye=_.extend({clientToken:J}),be=v.object({clientToken:J,canvas:v.string().min(1),expectedVersion:v.number().int().positive().describe(`Version returned by the latest successful read or write.`),target:u.default({kind:`content`}),sourceState:o.nullable().default(null),scale:v.number().min(.1).max(4).default(1)}),Y=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})},xe=async(t,r)=>{let o=d(r.canvas),s=t.scope??o;if(s.canvasId!==o.canvasId)throw new i(`FORBIDDEN`,`This turn cannot render another canvas.`,`Render the submitted canvas and selection.`);if(!e(s))return{canvasId:s.canvasId,target:r.target};let c=n.parse(await Y(t,`canvas.document.get`,{canvasId:s.canvasId}));if(c.version!==r.expectedVersion)throw new i(`CONFLICT`,`The canvas changed before rendering.`,`Read the selected subtree and render its current version.`);return{canvasId:s.canvasId,target:a(s,l.parse(c.document),r.target)}},X=async(e,t,n)=>{try{return await t.results.success(e,await n(),t.delivery)}catch(e){return t.results.failure(e)}},Se=(e,t)=>{t.catalog.some(e=>e.id===`canvas.writeHtml`)&&e.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. ${t.readTool===`canvas_read`?`Read canonical IDs and the current version with canvas_read. Keep all writes inside the frozen selection.`:`If starting state is unknown, call capability_query with {"capability":"canvas.read","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:ve,outputSchema:V,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},async({canvas:n,clientToken:r,...i},a)=>q.run(a,async()=>X(e,t,async()=>{let e=d(n);return Y(t,`canvas.writeHtml`,{...i,canvasId:e.canvasId,...e.pageId!==void 0&&{pageId:e.pageId},...e.nodeIds.length>0&&{selectionNodeIds:e.nodeIds},review:`none`,renderOutputPath:null,overwriteRender:!1,renderScale:1,renderTimeoutMs:12e4},r??null)})))},Ce=(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:ye,outputSchema:V,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},async({clientToken:n,...r},i)=>q.run(i,async()=>X(e,t,async()=>Y(t,`canvas.edit`,r,n??null))))},we=(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:be,outputSchema:V,annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},async(n,r)=>q.run(r,async()=>X(e,t,async()=>Y(t,`canvas.render`,{...await xe(t,n),expectedVersion:n.expectedVersion,sourceState:n.sourceState,scale:n.scale,outputPath:null,overwrite:!1,timeoutMs:12e4},n.clientToken??null))))},Te=e=>({register:t=>{let n=e.tools??[`write`,`edit`,`render`];n.includes(`write`)&&Se(t,e),n.includes(`edit`)&&Ce(t,e),n.includes(`render`)&&we(t,e)}}),Ee=e=>e.replaceAll(/\s+/gu,` `).trim(),De=e=>{let t=`${e.id} [${e.effect}] — `,n=Ee(e.guide.summary),r=180-t.length;return`${t}${n.slice(0,r)}`},Oe=(e,t)=>{let n=e.toSorted((e,t)=>e.id.localeCompare(t.id)).map(e=>De(e)),r=x(`sha256`).update(n.join(`
|
|
3
|
-
`)).digest(`hex`),i=[`Enhance MCP ${t} — ${String(n.length)} capabilities — sha256:${r}`,...n].join(`
|
|
4
|
-
`);if(Buffer.byteLength(i)>24576)throw RangeError(`the complete capability catalogue exceeds 24 KiB`);return{digest:r,text:i}},ke=(e,t,n=`enhance`)=>{let r=Oe(e,t),i=String(f(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:v.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}]}))}}},Ae=v.object({capability:v.string().min(1).describe(`Exact capability id returned by capability_search or capability_catalogue.`)}),je=(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:Ae,outputSchema:me,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},({capability:n})=>{let r=e.describe(n);return r===null?t.failure(new i(`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(r)})}}),Z=D(),Q={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},Me=v.object({query:v.string().trim().min(1).max(200).describe(`Plain-language task, domain, or exact capability id to discover.`),operation:v.enum([`any`,`query`,`mutation`]).default(`any`).describe(`Filter dispatch, not effect. Omit if unknown; render uses mutation.`),limit:v.number().int().min(1).max(10).default(5).describe(`Maximum contracts to return.`)}),$=(e,t,n)=>{let r=e.find(e=>e.id===t);if(r===void 0)throw new i(`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(r.operation!==n){let e=r.operation===`query`?`capability_query`:`capability_mutate`;throw new i(`BAD_REQUEST`,`${t} is a ${r.operation}, not a ${n}.`,`Call ${e} with the same capability and input.`,{capability:`Use ${e} for this capability.`})}return r},Ne=(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:Me,outputSchema:pe,annotations:Q,_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":t.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":t.length}},async({query:e,operation:t,limit:i},a)=>Z.run(a,async()=>r.inline(n.search({query:e,operation:t,limit:i}))))},Pe=(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:he,outputSchema:V,annotations:Q,_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a},o)=>Z.run(o,async()=>{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)}}))},Fe=(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:H,outputSchema:V,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a,clientToken:o},s)=>Z.run(s,async()=>{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)}}))},Ie=e=>{let t=e.exposures?.includes(`mcp-transport`)===!0?`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.`:void 0,n=e.workflowsDirectory===void 0?void 0:K(e.workflowsDirectory,t),r=n?.instructions??t,i=new ae({name:e.name??`enhance-mcp`,version:e.version},{capabilities:{tools:{listChanged:!1},resources:{listChanged:!0}},...r!==void 0&&{instructions:r}}),a=c(e.catalog??ee(),e.exposures??[`shared`]),o=g(a),s=F(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);ke(a,e.version,e.commandName).register(i),Ne(i,a,o,s),je(o,s).register(i);let l={delivery:e.delivery??`linked`,results:s,invocation:U(e.invocation,e.clientMetadata)};return Pe(i,a,l.invocation,l),Fe(i,a,l.invocation,l),Te({catalog:a,...l}).register(i),n?.register(i),i};export{F as a,V as i,K as n,D as o,U as r,Ie as t};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{$n as e,$t as t,A as n,At as r,Bn as i,Bt as a,C as o,Cn as s,Cr as c,Dn as l,Dt as u,En as d,Er as f,Et as p,F as ee,Fn as te,G as ne,Gn as m,Gt as re,H as ie,Hn as ae,Ht as oe,J as se,Jt as ce,K as le,Kt as ue,Ln as de,M as fe,Mn as h,Mt as pe,N as me,Nn as he,Nt as g,O as ge,On as _e,Pt as ve,Q as ye,Qt as be,Rn as xe,S as Se,Sn as Ce,Sr as we,T as Te,U as Ee,Un as De,Ut as Oe,Vn as _,W as ke,Wn as Ae,Wt as je,X as Me,Xn as Ne,Xt as Pe,Y as Fe,Yn as Ie,Yt as Le,Zn as Re,Zt as ze,_r as Be,_t as Ve,ar as v,at as He,br as Ue,cr as y,ct as We,dt as Ge,fr as Ke,gr as qe,ht as Je,ir as Ye,jn as Xe,jt as b,kn as Ze,lr as Qe,lt as $e,mt as et,nr as tt,nt,or as rt,ot as it,pr as at,q as ot,qt as st,rr as ct,rt as lt,s as ut,tn as dt,tt as ft,ur as pt,ut as mt,v as ht,vr as gt,w as x,wn as _t,wt as vt,x as S,xn as yt,xt as C,yr as bt,yt as xt,z as St}from"./cli-output-identity.lib-DImbm4C3.mjs";import w from"node:process";import{z as T}from"zod";import{homedir as Ct,tmpdir as wt}from"node:os";import{generateKeyBetween as Tt,generateNKeysBetween as Et}from"fractional-indexing";import{chmodSync as Dt,constants as Ot,createReadStream as kt,createWriteStream as At,mkdirSync as jt,writeFileSync as Mt}from"node:fs";import E from"node:path";import{createHash as D,randomBytes as Nt,randomUUID as Pt}from"node:crypto";import{setTimeout as Ft}from"node:timers/promises";import{chmod as It,mkdir as Lt,mkdtemp as Rt,open as zt,readFile as Bt,realpath as Vt,rename as Ht,rm as Ut,stat as Wt,unlink as Gt,writeFile as Kt}from"node:fs/promises";import{isDeepStrictEqual as qt}from"node:util";import{generate as Jt,parse as Yt}from"css-tree";import{parseFragment as Xt,serialize as Zt,serializeOuter as Qt}from"parse5";import{Readable as $t,Transform as en}from"node:stream";import{pipeline as tn}from"node:stream/promises";import{ZipFile as nn}from"yazl";import{createTRPCUntypedClient as rn,httpLink as an}from"@trpc/client";import{spawn as on}from"node:child_process";import{createServer as sn}from"node:http";const cn=(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)??[])]},ln=(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:cn(a,t.order)}},un=(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=ln(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}}},dn=e=>typeof e==`object`&&!!e&&!Array.isArray(e),O=(e,t)=>{if(!dn(e)||e.kind!==`image`||typeof e.assetId!=`string`)return e;let n=t(e.assetId);return n===e.assetId?e:{...e,assetId:n}},fn=(e,t)=>Array.isArray(e)?e.map(e=>{if(!dn(e)||e.kind!==`span`)return e;let n=Array.isArray(e.fills)?e.fills:void 0;return{...e,...n!==void 0&&{fills:n.map(e=>O(e,t))},...Array.isArray(e.children)&&{children:fn(e.children,t)}}}):e,pn=(e,t)=>{let n=e.appearance,r=e.props?.src;return{...e,...n!==void 0&&{appearance:{...n,...n.fills!==void 0&&{fills:n.fills.map(e=>O(e,t))},...n.border!==void 0&&{border:{...n.border,paint:O(n.border.paint,t)}},...n.outline!==void 0&&{outline:{...n.outline,paint:O(n.outline.paint,t)}}}},...e.typography?.stroke!==void 0&&{typography:{...e.typography,stroke:{...e.typography.stroke,paint:O(e.typography.stroke.paint,t)}}},...e.props!==void 0&&{props:{...e.props,...e.component===`image`&&typeof r==`string`&&{src:t(r)},...e.component===`text`&&e.props.richText!==void 0&&{richText:fn(e.props.richText,t)}}}}},mn=/^enh_[\w-]{43}$/,hn=e=>{let t=ze.parse(e);if(t.authentication.kind!==`agent`||t.person===null)throw new g(`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}},gn=(e,n,r)=>({loginWithToken:async t=>{if(!mn.test(t))throw new g(`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=hn(await n.queryWithToken(`person.me`,{},t));return await e.write(t),r},loginWithBrowser:async i=>{let a=be.parse(await n.authenticationConfig());if(a.method===`token`)throw new g(`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 o=await r.authorize({issuer:a.issuer,clientId:a.clientId,scope:a.scope,openBrowser:i.openBrowser,onReady:i.onReady,...i.signal!==void 0&&{signal:i.signal}});i.signal?.throwIfAborted();let s=t.parse(await n.mutateWithToken(`person.createAgentToken`,{label:i.label,expiresAt:null},o)),c=hn(await n.queryWithToken(`person.me`,{},s.token));return i.signal?.throwIfAborted(),await e.write(s.token),c},status:async(t=n)=>{if(await e.read()===null)throw new g(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return hn(await t.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),_n=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),vn=e=>{if(e.byteLength<24||_n.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)}},yn=async(e,t)=>{if(t.result.canvasId!==t.canvasId||t.result.requestedVersion!==t.requestedVersion||t.result.loadedVersion!==t.requestedVersion||JSON.stringify(t.result.target)!==JSON.stringify(t.target))throw new g(`INTERNAL`,`The completed render evidence does not match its requested canvas, revision or target.`,`Do not use the image. Report render job ${t.id}.`);if(t.result.width*t.result.height>Math.min(t.maxOutputPixels??16e6,16e6))throw new g(`INTERNAL`,`The completed render exceeds its authorised output pixel limit.`,`Do not use the image. Report render job ${t.id}.`,{reason:`RENDER_BUDGET_UNSUPPORTED`});let n=Ye.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!n.success||n.data.jobId!==t.id||n.data.download.bytes!==t.result.bytes)throw new g(`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=vn(r);if(i===null||r.byteLength!==t.result.bytes||i.width!==t.result.width||i.height!==t.result.height)throw new g(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return r},bn=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]},xn=(e,t)=>({jobId:e.id,operation:{kind:`canvas-render`,canvasId:e.canvasId,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:bn(e)}),Sn=async(e,t,n,r)=>xn(n,t.write({body:await yn(e,n),...r})),Cn=[`canvas.render.create`,`canvas.render.get`],k=e=>new g(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),wn=e=>{let t=e.failure;if(t===null)return k(`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 g(n,t.message,r,{jobId:e.id,reason:t.reason,phase:t.phase,renderState:e.state})},Tn=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),En=async(e,t)=>{let n=v.safeParse(await e.query(Cn[1],{jobId:t}));if(!n.success||n.data.job.id!==t)throw k(`render status`);return n.data.job},Dn=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){if(t.timeoutOutcome===`pending`)return a;throw new g(`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 Tn(250),a=await En(e,a.id)}if(a.state!==`succeeded`)throw wn(a);return a},On=async(e,t)=>{let n=tt.safeParse(await e.mutate(Cn[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.scope!==void 0&&{scope:t.scope},...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,...t.maxOutputPixels!==void 0&&{maxOutputPixels:t.maxOutputPixels},format:`png`}));if(!n.success)throw k(`render creation`);if(n.data.job.canvasId!==t.canvasId||t.expectedVersion!==null&&n.data.job.requestedVersion!==t.expectedVersion||JSON.stringify(n.data.job.target)!==JSON.stringify(t.target)||n.data.job.scale!==t.scale)throw k(`render identity`);return n.data.job},kn=(e,t)=>{if(t.maxOutputPixels!==void 0&&e.maxOutputPixels!==t.maxOutputPixels)throw new g(`INTERNAL`,`This API does not preserve the requested render pixel budget.`,`Update the API and renderer together before rendering a batch.`,{reason:`RENDER_BUDGET_UNSUPPORTED`})},An=async(e,t)=>{let n=await On(e.remote,t);try{kn(n,t);let r=await Dn(e.remote,{initial:n,deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress,timeoutOutcome:t.timeoutOutcome});return kn(r,t),r.state===`succeeded`?await Sn(e.remote,e.files,r,{outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()}):{state:r.state,phase:r.phase,canvasId:r.canvasId,requestedVersion:r.requestedVersion,target:r.target,operation:{kind:`canvas-render`,canvasId:r.canvasId,jobId:r.id},pixelsDelivered:!1,next:[`Read operation_status with includeImage true. Do not create another render.`]}}catch(e){let r=JSON.stringify({kind:`canvas-render`,canvasId:t.canvasId,jobId:n.id});throw e instanceof g?new g(e.code,e.message,e.remediation,{...e.fields,jobId:n.id,operation:r}):new g(`INTERNAL`,`The native render outcome could not be confirmed.`,`Read operation_status or retry with the identical request and clientToken.`,{jobId:n.id,operation:r})}},jn=(e,t,n,r=()=>null)=>({execute:async i=>An({remote:e,files:t,now:n,progress:r},i)}),A={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},Mn=async e=>{try{return await e(),!0}catch{return!1}},Nn=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await Mn(async()=>e.mutate(A.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 Mn(async()=>e.mutate(A.end,{canvasId:i.canvasId,activityId:n})))}}},Pn=e=>({begin:async t=>{try{let n=he.safeParse(await e.mutate(A.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?Nn(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>Mn(async()=>e.mutate(A.end,{canvasId:t,activityId:n}))}),Fn=new Set([`insertPrototype`,`insertText`,`setBox`]),In=e=>Fn.has(e.op),Ln=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,Rn=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],zn=e=>[...new Set(e.operations.flatMap(e=>Rn(e)))].slice(0,100),Bn=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:In(e)?e.box==="default"?null:e.box:null,Vn=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}},Hn=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:7}),r=_.safeParse(n);if(!r.success)throw new g(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data},j=e=>({execute:async(t,n)=>{if(n?.activity===!1)return Hn(e,t);let r=await Pn(e).begin({canvasId:t.canvasId,phase:Ln(t),nodeIds:zn(t),bounds:Vn(t.operations.flatMap(e=>{let t=Bn(e);return t===null?[]:[t]}))});try{return await Hn(e,t)}finally{await r?.finish()}}}),Un=async(e,t,n)=>{let r=m.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:t}));if(!r.success)throw new g(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(r.data.version!==n)throw new g(`CONFLICT`,`Canvas version ${String(r.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(r.data.version)} before submitting a new edit.`);let i=y.safeParse(r.data.document);if(i.success)return i.data;throw new g(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},M=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),N=e=>{let t=new Map;for(let[n,r]of Object.entries(e.relationships)){let e=t.get(r.parentId)??[];e.push(n),t.set(r.parentId,e)}for(let n of t.values())n.sort((t,n)=>{let r=e.relationships[t]?.sortKey??``,i=e.relationships[n]?.sortKey??``;return r===i?t.localeCompare(n):r.localeCompare(i)});return t},Wn=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),P=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new g(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Gn=(e,t)=>{let n=new Set,r=t=>{for(let i of M(e,t))n.add(i),r(i)};return r(t),n},F=(e,t)=>{let n=new Set,r=t;for(;r!==void 0;){if(n.has(r))throw new g(`BAD_REQUEST`,`The canvas contains a parent cycle.`,`Repair the canvas topology before editing.`);if(n.add(r),P(e,r).locked===!0)return!0;r=e.relationships[r]?.parentId}return!1},Kn=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},qn=e=>{let t=0;return n=>(t+=1,`${Kn(e)}_${Kn(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},Jn=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of M(e,t))r(n)};return r(t),n},Yn=(e,t,n)=>Object.fromEntries(Jn(e,t).map(t=>[t,n(P(e,t).label)])),Xn=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=P(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let p=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??p}}},Zn=e=>{let{document:t,input:n,inputIndex:r,nextId:i}=e,a=P(t,n.id);if(n.id===`root`)throw new g(`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 g(`BAD_REQUEST`,`Canvas node ${n.id} is detached.`,`Choose a reachable node from canvas tree.`);let s=n.parentId??o.parentId;if(!Wn(t.nodes[s]))throw new g(`BAD_REQUEST`,`Canvas node ${s} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let c=Yn(t,n.id,i),l={document:t,rootId:n.id,parentId:s,inputIndex:r,sourceSortKey:o.sortKey,map:c},u=Jn(t,n.id).map(e=>Xn(l,e)),d=c[n.id];if(d===void 0)throw Error(`Missing duplicate root id for ${n.id}`);return{operations:u,summary:{sourceId:n.id,newId:d,name:a.label,component:a.component,descendantIdMap:Object.fromEntries(Object.entries(c).filter(([e])=>e!==n.id))}}},Qn=(e,t,n)=>{if(t.length===0)throw new g(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let r=qn(n),i=t.map((t,n)=>Zn({document:e,input:t,inputIndex:n,nextId:r}));return{operations:i.flatMap(e=>e.operations),duplicatedNodes:i.map(e=>e.summary)}},$n=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,M(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),er=(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))}},tr=(e,t)=>{let n=`before`in e?e.before:e.after;if(n===e.nodeId||t.document.nodes[n]===void 0)throw new g(`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 g(`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}},nr=(e,t)=>`parentId`in e?er(e,t):tr(e,t),rr=(e,t,n)=>{if(e.nodeId===`root`||n.document.nodes[e.nodeId]===void 0)throw new g(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Gn(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!Wn(n.document.nodes[t.parentId]))throw new g(`BAD_REQUEST`,`Canvas node ${t.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},ir=(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=Tt(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=Et(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}}},ar=(e,t)=>{if(t.length===0)throw new g(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=$n(e),r=[];return{operations:t.flatMap(e=>{let t=nr(e,n);rr(e,t,n),r.push({nodeId:e.nodeId,...t});let i=ir(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)??[]]}))}},or=(e,t)=>{let n=Ce(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}}},sr=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),cr=(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=>(e.startsWith(`--`)?t.property:t.property.toLowerCase())===e);for(let e of t)n.delete(e.id);if(r===null||Ie.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=c.safeParse({id:a,property:e,value:String(r),enabled:!0});if(!o.success)throw new g(`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 g(`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=un(e.additionalStyles,i);return a===null?null:{op:`patchAdditionalStyles`,nodeId:e.id,additionalStyles:a}},lr=(e,t,n,r)=>{let i=new Set(Object.keys(r)),a=r=>[...at(t,r,e),...at(n,r,e)],o=De(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`)&&(o[t]={mode:n})}return JSON.stringify(o)===JSON.stringify(t.layout??{})?null:{op:`setLayout`,nodeId:t.id,layout:Object.keys(o).length===0?`default`:o}},ur=(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 at(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},dr=(e,t,n)=>{let r=ur(e,t,n),i=cr(t,r),a=Object.fromEntries(Object.entries(r).filter(([e,t])=>Ie.safeParse({[e]:t}).success)),o={...t,styles:{...t.styles},...i!==null&&{additionalStyles:ln(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=lr(e,t,o,n),c=or(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:Ie.parse(a)}]:[],...l,...c===null?[]:[c],...s===null?[]:[s],...i===null?[]:[i]]},fr=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=sr(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},pr=(e,t)=>{let n=[...fr(t)].flatMap(([t,n])=>{let r=e.nodes[t];if(r===void 0)throw new g(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use current stable node ids.`);return dr(e,r,n)});if(n.length===0)throw new g(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return n},mr=(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=yt(e.typography,{clear:[...Ce(new Set([...Object.keys(t.styles),...r]))]});return I({...e,styles:n},`typography`,i??`default`)},hr=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`patchTypography`,`setLayout`,`setAdditionalStyles`,`patchAdditionalStyles`,`setParentage`]),gr=e=>hr.has(e.op),I=(e,t,n)=>{let r={...e};return n==="default"?Reflect.deleteProperty(r,t):Reflect.set(r,t,n),r},_r=(e,t)=>{switch(t.op){case`setText`:if(e.component!==`text`)throw new g(`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 mr(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 I(e,`typography`,yt(e.typography,t.typography)??`default`);case`setTypography`:return I(e,`typography`,t.typography);case`setLayout`:return I(e,`layout`,t.layout);case`patchAdditionalStyles`:{let n=ln(e.additionalStyles,t.additionalStyles);return I(e,`additionalStyles`,n??`default`)}case`setAdditionalStyles`:return I(e,`additionalStyles`,t.additionalStyles)}},vr=(e,t)=>{if(!gr(t))throw Error(`Unexpected focused edit operation: ${t.op}`);if(t.op===`insertNode`){if(e.nodes[t.node.id]!==void 0)throw new g(`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=P(e,t.nodeId);return t.op===`setParentage`?{...e,relationships:{...e.relationships,[n.id]:t.parentage}}:{...e,nodes:{...e.nodes,[n.id]:_r(n,t)}}},yr=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}}}},br=(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 pr(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=Qn(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=ar(t.scene,[yr(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},xr=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=br(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=vr(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:M(r.scene,e)}))}},L=e=>{throw new g(`BAD_REQUEST`,`These nodes are outside the link selection: ${e.join(`, `)}.`,`Keep the complete link. Edit only its page or selection and preserve the destination page.`)},Sr=(e,t)=>{if(e.op===`insertNode`)return[e.parentage.parentId];if(e.op===`insertText`||e.op===`insertPrototype`)return[e.parentId,...e.afterId===void 0?[]:[e.afterId]];if(e.op===`insertConvertedSubtree`)return e.destination.kind===`adjacent`?L([`adjacent conversion`]):[e.destination.targetNodeId];if(e.op===`move`||e.op===`setParentage`){let n=e.op===`move`?e.parentId:e.parentage.parentId;return[e.nodeId,...n===t.relationships[e.nodeId]?.parentId?[]:[n],...e.op===`move`&&e.afterId!==void 0?[e.afterId]:[]]}return[e.nodeId]},Cr=e=>e.op===`insertNode`?[e.node.id]:e.op===`insertText`||e.op===`insertPrototype`?[e.nodeId]:e.op===`insertConvertedSubtree`?Object.keys(e.nodes):[],wr=(e,t)=>{let n=t.destination;if(n.kind===`adjacent`)return L([`adjacent conversion`]);let r=n.kind===`replace`?e.relationships[n.targetNodeId]?.parentId:n.targetNodeId;if(r===void 0)return L([n.targetNodeId]);let i=n.kind===`insert-children`&&n.targetNodeId===`root`?n.pageId??`canvas-page-default`:Xe(e,n.targetNodeId),a=t.nodes[t.rootNodeId];return a===void 0?L([t.rootNodeId]):{nodes:{...t.nodes,[t.rootNodeId]:{...a,...r===`root`&&i!==null&&{props:{...a.props,canvasPageId:i}}}},relationships:{...t.relationships,[t.rootNodeId]:{parentId:r,sortKey:``}}}},Tr=e=>({component:e.op===`insertText`?`text`:`prototype`,props:{...e.op===`insertPrototype`&&e.canvasPageId!==void 0&&{canvasPageId:e.canvasPageId}}}),Er=(e,t)=>{if(t.op===`insertNode`)return{nodes:{[t.node.id]:t.node},relationships:{[t.node.id]:t.parentage}};if(t.op===`insertText`||t.op===`insertPrototype`)return{nodes:{[t.nodeId]:Tr(t)},relationships:{[t.nodeId]:{parentId:t.parentId,sortKey:``}}};if(t.op===`insertConvertedSubtree`)return wr(e,t);if(t.op===`move`||t.op===`setParentage`)return{nodes:{},relationships:{[t.nodeId]:t.op===`move`?{parentId:t.parentId,sortKey:``}:t.parentage}};if(t.op===`setProps`){let n=e.nodes[t.nodeId];if(n!==void 0)return{nodes:{[t.nodeId]:{...n,props:t.props==="default"?{}:t.props}},relationships:{}}}return{nodes:{},relationships:{}}},Dr=(e,t,n,r)=>{let i=Cr(r),a=e.nodeIds.length===0&&(i.length>0||r.op===`move`||r.op===`setParentage`),o=[...Sr(r,t).filter(e=>!a||e!==`root`),...i.filter(e=>t.nodes[e]!==void 0)].filter(e=>!n.has(e));return o.length>0&&L(o),i},Or=(e,t,n)=>{if(!r(e))return;let i=new Set(u(e,t)),a=h(e,t);if(!a.ok)return L(e.nodeIds);let o={nodes:{...t.nodes},relationships:{...t.relationships}};for(let t of n){let n=Dr(e,o,i,t),r=Er(o,t);Object.assign(o.nodes,r.nodes),Object.assign(o.relationships,r.relationships);let s=[...Object.keys(r.nodes),...Object.keys(r.relationships)].filter(e=>o.nodes[e]?.component===`page`||Xe(o,e)!==a.pageId);s.length>0&&L(s);for(let e of n)i.add(e);if(t.op!==`remove`)continue;let c=h({...e,nodeIds:[t.nodeId]},o);if(c.ok)for(let e of c.nodeIds)i.delete(e),Reflect.deleteProperty(o.nodes,e),Reflect.deleteProperty(o.relationships,e)}},kr=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]}},Ar=(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]:kr(e),jr=(e,t)=>{if(e.edits.length===0||e.edits.length>1e3)throw new g(`BAD_REQUEST`,`The edit batch exceeds the canonical operation limit.`,`Split larger changes into bounded batches.`);let n=new Set(e.edits.flatMap(e=>kr(e)));if(n.size>1e3)throw new g(`BAD_REQUEST`,`A batch may target at most 1,000 nodes.`,`Split the edit into smaller batches.`);for(let e of n)P(t,e);let r={canvasId:e.canvasId,nodeIds:e.nodeIds??[],...e.pageId!==void 0&&{pageId:e.pageId}};for(let n of e.edits)p(r,t,Ar(n,t))},Mr=e=>({execute:async t=>{let n=await Un({remote:e},t.canvasId,t.baseVersion);jr(t,n);let r=xr(n,t.edits,t.idPrefix??`copy_${t.mutationId.replaceAll(`-`,``)}`);Or({canvasId:t.canvasId,nodeIds:t.nodeIds??[],...t.pageId!==void 0&&{pageId:t.pageId}},n,r.operations.filter(e=>`nodeId`in e&&n.nodes[e.nodeId]!==void 0));let a=i.safeParse({canvasId:t.canvasId,mutationId:t.mutationId,documentFormatVersion:7,baseVersion:t.baseVersion,operations:r.operations});if(!a.success)throw new g(`BAD_REQUEST`,`The edit exceeds canonical canvas limits.`,a.error.issues[0]?.message??`Reduce the edit batch.`);let o=_.parse(await j(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}}}}),Nr=(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},R=(e,t,n)=>{if(t>e.length)throw new g(`BAD_REQUEST`,`The operation detail offset is out of range.`,`Restart status pagination at offset 0.`);let r=[],i=2,a=e.slice(t,t+n);for(let e of a){let t=Buffer.byteLength(JSON.stringify(e))+1;if(i+t>48e3)break;r.push(e),i+=t}if(r.length===0&&t<e.length)throw new g(`BAD_REQUEST`,`One operation detail exceeds the inline result budget.`,`Read the full operation through its comprehensive CLI command.`);let o=t+r.length;return{entries:r,total:e.length,offset:t,nextOffset:o<e.length?o:null,complete:o===e.length}},Pr=e=>e.state===`succeeded`?[...e.result.insertedNodeIds.map(e=>({kind:`inserted`,nodeId:e})),...e.result.removedNodeIds.map(e=>({kind:`removed`,nodeId:e})),...Object.entries(e.result.idMap).map(([e,t])=>({kind:`identity`,temporaryId:e,nodeId:t})),...e.result.report.issues.map(e=>({kind:`issue`,issue:e}))]:[],Fr=e=>e.state===`succeeded`?{mutationId:e.result.mutationId,previousVersion:e.result.previousVersion,version:e.result.version,rootNodeId:e.result.rootNodeId,affectedBounds:e.result.affectedBounds,insertedCount:e.result.insertedNodeIds.length,removedCount:e.result.removedNodeIds.length,identityCount:Object.keys(e.result.idMap).length,issueCount:e.result.report.issues.length}:null,Ir=(e,t)=>({kind:`canvas-conversion`,operation:{kind:`canvas-conversion`,canvasId:e.canvasId,jobId:e.id},state:e.state,phase:e.phase,requestedVersion:e.requestedVersion,destination:e.destination,result:Fr(e),failure:e.failure,details:R(Pr(e),t.offset,t.limit),warnings:e.state===`succeeded`?[`This receipt does not verify visual fidelity. Render the committed root to inspect it.`]:[]}),z=e=>new g(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),Lr=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Rr=e=>{let t=e.failure;return new g(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 and correct the conversion source or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},zr=async(e,t)=>{let n=Re.safeParse(await e.query(`canvas.render.getImport`,{jobId:t}));if(!n.success)throw z(`conversion status`);if(n.data.job.id!==t)throw z(`conversion identity`);return n.data.job},Br=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 Lr(250),i=await zr(e,i.id)}if(i.state!==`succeeded`)throw Rr(i);return i},Vr=(e,t)=>{let n=e.destination,r=t.request.destination;return n.kind===r.kind?n.kind===`adjacent`||r.kind===`adjacent`||n.targetNodeId===r.targetNodeId&&(n.kind!==`insert-children`||r.kind!==`insert-children`||n.pageId===r.pageId):!1},Hr=(e,t)=>{let n=t.request;if(e.canvasId!==n.canvasId||e.requestedVersion!==n.expectedVersion||!Vr(e,t))throw z(`conversion destination or revision`);let r=e.source;if(r.kind!==n.source.kind||r.kind===`screen`&&n.source.kind===`screen`&&r.nodeId!==n.source.nodeId||r.kind===`html`&&n.source.kind===`html`&&r.label!==n.source.label)throw z(`conversion source`);if(e.state===`succeeded`&&(e.result.canvasId!==n.canvasId||n.revisionPolicy===`strict`&&e.result.previousVersion!==n.expectedVersion))throw z(`conversion commitment`)},Ur=async(e,t)=>{let n=Ne.safeParse(await e.mutate(`canvas.render.importSource`,t.request));if(!n.success)throw z(`conversion creation`);Hr(n.data.job,t);let r=await Br(e,n.data.job,t.waitMs);return Hr(r,t),r},Wr=async(e,t)=>{let n=xt.parse(t),r=b(n.canvasRef);return Ir(await Ur(e,{request:{canvasId:r.canvasId,expectedVersion:n.baseVersion,revisionPolicy:`strict`,scope:{pageId:r.pageId,nodeIds:[...r.nodeIds]},source:{kind:`screen`,nodeId:n.sourceNodeId},destination:n.placement},waitMs:n.waitMs}),{offset:0,limit:40})},Gr=(e,t,n)=>({state:`failed`,mutationCommitted:!0,requestedVersion:n,...e instanceof g?{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.`]}),Kr=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 Gr(e,t,n.result.version)}},qr=async(e,t)=>{let n=await Un({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??``}})},Jr=(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}),Yr=e=>({state:`pending`,canvasId:e.canvasId,jobId:e.id,phase:e.phase,status:{tool:`capability_query`,arguments:{capability:`canvas.render.getImport`,input:{jobId:e.id}}},next:[`Read the existing import status; do not start another import.`]}),Xr=e=>({waitMs:e.renderTimeoutMs,request:{canvasId:e.canvasId,expectedVersion:e.baseVersion,...e.revisionPolicy!==void 0&&{revisionPolicy:e.revisionPolicy},...(e.pageId!==void 0||(e.selectionNodeIds?.length??0)>0)&&{scope:{pageId:e.pageId,nodeIds:[...e.selectionNodeIds??[]]}},source:{kind:`html`,html:e.html,label:`Agent-authored HTML`,...e.idPrefix!==void 0&&{idPrefix:e.idPrefix}},destination:{kind:e.mode,targetNodeId:e.targetNodeId,...e.mode===`insert-children`&&e.pageId!==void 0&&{pageId:e.pageId}}}}),Zr=(e,t)=>({execute:async n=>{let r=await Pn(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await Ur(e,Xr(n));if(n.responseMode===`bounded`)return Ir(i,{offset:0,limit:40});if(i.state!==`succeeded`)return Yr(i);if(n.review===`none`)return Jr(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await Kr(t,n,i),o=[];try{o=await qr(e,i)}catch{o=[]}return{...Jr(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),Qr=async(e,t)=>{let n=b(t.canvas),i=m.parse(await e.query(`canvas.document.get`,{canvasId:n.canvasId})),a=y.parse(i.document);r(n)&&u(n,a),t.nodeId!==void 0&&p(n,a,[t.nodeId]);let o=h(t.nodeId===void 0?n:{...n,nodeIds:[t.nodeId]},a);if(!o.ok)throw new g(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link. Do not broaden the request.`);let s=Object.groupBy(Object.entries(a.relationships),([,e])=>e.parentId),c=Object.values(a.nodes).filter(e=>o.nodeIds.has(e.id)).map(e=>({...e,kind:e.component,parentId:a.relationships[e.id]?.parentId??null,children:(s[e.id]??[]).map(([e])=>e)}));return{canvasId:n.canvasId,version:i.version,pageId:o.pageId,source:n.nodeIds.length>0?`selection-link`:n.pageId===void 0?`canvas-link`:`page-link`,selectedNodeIds:n.nodeIds,rootNodeIds:o.rootNodeIds,nodeCount:c.length,nodes:c,next:[`Keep the complete supplied canvas link for subsequent reads, edits and renders. Use this version as baseVersion; edit only these nodes or descendants.`]}},$r=(e,t,n)=>{try{Mt(e,t,{flag:n?`w`:`wx`,mode:384}),Dt(e,384)}catch(t){let n=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new g(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.`)}},ei=e=>({write:t=>{if(t.outputPath!==null){let e=E.resolve(t.outputPath);return $r(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=E.join(e,`sensitive`);jt(n,{recursive:!0,mode:448}),Dt(n,448);let r=E.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return $r(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),ti=[`canvas.asset.reserve`,`canvas.asset.complete`,`canvas.document.get`],ni=(e,t)=>new g(e instanceof g?e.code:`INTERNAL`,e instanceof g?e.message:`The asset import did not return a confirmed result.`,e instanceof g?e.remediation:`Read operation_status for this import or retry the same file and clientToken. No canvas placement was requested.`,{...e instanceof g&&e.fields,operation:JSON.stringify(t),outcome:`not_confirmed`}),ri=(e,t)=>{if(e.canvasId!==t.canvasId||e.clientToken!==t.clientToken||e.kind!==t.kind||e.contentType!==t.contentType||e.bytes!==t.bytes||e.sha256!==t.sha256)throw new g(`INTERNAL`,`The returned asset does not match this import intent.`,`Check the API and CLI versions. Do not insert an unverified resource.`)},ii=(e,t)=>({execute:async n=>{let i=b(n.canvasRef);if(r(i)){let t=m.parse(await e.query(ti[2],{canvasId:i.canvasId}));u(i,y.parse(t.document))}let{body:a,...o}=await t.read(),s=gt.parse({...o,canvasId:i.canvasId,clientToken:n.clientToken}),c={kind:`canvas-asset`,canvasId:i.canvasId,clientToken:n.clientToken};try{let t=bt.parse(await e.mutate(ti[0],s));ri(t,s),t.upload!==null&&await e.upload({...t.upload,body:a});let r=Be.parse(await e.mutate(ti[1],{canvasId:i.canvasId,clientToken:n.clientToken}));if(ri(r,s),r.assetId!==t.assetId||r.path!==t.path)throw new g(`INTERNAL`,`The completed asset identity changed.`,`Read operation_status and do not place an unconfirmed resource.`);return fe.parse({operation:c,resource:r,placement:`not_requested`})}catch(e){throw ni(e,c)}}}),ai=new Set([`ready`,`failed`,`abandoned`]),B=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`],V=e=>new g(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,`Check the existing deployment status before retrying with the same publication token.`),oi=async(e,t,n,r)=>{let i=je.safeParse(await e.mutate(B[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 V(`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`){let n=Pe.safeParse(await e.mutate(B[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId}));if(!n.success||n.data.deploymentId!==i.data.deploymentId)throw V(`artifact submission`)}return i.data},si=async(e,t,n,r)=>{let i=ue.safeParse(await e.query(B[0],{}));if(!i.success)throw V(`capabilities`);let a=await t.package({entryPath:n.entryPath,limits:i.data.limits});try{return await oi(e,n,a,r)}finally{await a.dispose()}},ci=async(e,t)=>{let n=st.safeParse(await e.query(B[3],t));if(!n.success||n.data.deploymentId!==t.deploymentId)throw V(`status`);return n.data},li=async(e,t,n)=>{let r=Date.now()+n,i=50,a=await ci(e,t);for(;!ai.has(a.state);){let n=r-Date.now();if(n<=0)return a;await Ft(Math.min(i,n)),i=Math.min(i*2,1e3),a=await ci(e,t)}return a},ui=[`prototype.getArtifactCapabilities`,`prototype.attach`],di=new Set([`BAD_REQUEST`,`FORBIDDEN`,`UNAUTHORIZED`,`NOT_FOUND`]),fi=async e=>{let t=ue.safeParse(await e.query(ui[0],{}));if(!t.success||t.data.attachmentProtocolVersion!==1)throw new g(`BAD_REQUEST`,`This API does not advertise revision-checked prototype attachment.`,`Upgrade the API before publishing through the canvas profile. No artifact was created or attached.`)},pi=e=>e instanceof g?{code:e.code,message:e.message,remediation:e.remediation}:{code:`INTERNAL`,message:`The publication request did not return a confirmed outcome.`,remediation:`Retry the identical request with its original clientToken; do not assume the canvas is unchanged.`},mi=async(e,t,n)=>{let r=b(t.canvasRef),i=Oe.safeParse(await e.mutate(ui[1],{canvasId:r.canvasId,deploymentId:n.deploymentId,baseVersion:t.baseVersion,...r.pageId!==void 0&&{canvasPageId:r.pageId},attachment:{clientToken:t.clientToken,scope:{...r.pageId!==void 0&&{pageId:r.pageId},nodeIds:r.nodeIds}}}));if(!i.success)throw Error(`Invalid prototype attachment response`);let a=i.data,o=a.attachment;if(o===void 0||a.canvasId!==r.canvasId||a.deploymentId!==n.deploymentId||a.prototypeId!==n.prototypeId||a.nodeId!==n.nodeId||a.version!==o.version||o.outcome===`committed`&&(o.mutationId!==t.clientToken||o.previousVersion!==t.baseVersion||o.version!==t.baseVersion+1)||o.outcome===`no_op`&&o.version!==t.baseVersion)throw Error(`Unconfirmed prototype attachment receipt`);return{...a,attachment:o}},hi=async(e,t,n,r)=>{try{let i=await mi(e,t,r);return{...n,attachmentStatus:i.attachment.outcome,attachment:i,nextAction:`inspect_result`}}catch(e){let t=pi(e),r=t.code===`CONFLICT`,i=di.has(t.code);return{...n,attachmentStatus:r?`conflict`:i?`not_attempted`:`not_confirmed`,failure:t,nextAction:r||i?`replan_attachment`:`retry_same_request`,warnings:[`The ready deployment is reusable. A status read never attaches it. Retry uncertainty with the original attachment intent; a changed baseVersion, scope or destination requires a new clientToken.`]}}},gi=async(e,t,n,r)=>{let i={operation:{kind:`prototype-deployment`,canvasId:n,deploymentId:r.deploymentId},deploymentStatus:r.state,publication:r,attachmentStatus:`pending`,attachment:null,failure:null,nextAction:`check_status`,warnings:[]};return r.state===`failed`||r.state===`abandoned`?{...i,attachmentStatus:`not_attempted`,nextAction:`fix_build`,failure:{code:r.state===`failed`?r.failure.code:`NOT_FOUND`,message:r.state===`failed`?r.failure.message:`The deployment was abandoned.`,remediation:`Correct the build and publish a new artifact with a new clientToken.`}}:r.state===`ready`?hi(e,t,i,r):i},_i=(e,t)=>({execute:async n=>{let r=b(n.canvasRef);await fi(e);let i=n.source.kind===`deployment`?n.source.deploymentId:null;try{if(n.source.kind===`build`&&(i=(await si(e,t,{...n.source,canvasId:r.canvasId,clientToken:n.clientToken},e=>{i=e})).deploymentId),i===null)throw Error(`Publication has no deployment`);let a=await li(e,{canvasId:r.canvasId,deploymentId:i},n.waitMs);return await gi(e,n,r.canvasId,a)}catch(e){if(i===null)throw e;return{operation:{kind:`prototype-deployment`,canvasId:r.canvasId,deploymentId:i},deploymentStatus:`unknown`,publication:null,attachmentStatus:`not_attempted`,attachment:null,failure:pi(e),nextAction:`retry_same_request`,warnings:[`An existing deployment may still be processing. Retry the same source and clientToken to recover or finish upload; do not reserve a new publication.`]}}}}),vi=[`prototype.attach`],yi=e=>new g(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),bi=e=>{if(e.state!==`failed`)return;let{failure:t}=e;throw new g(`BAD_REQUEST`,t.message,`Fix the build and publish it with a new client token.`,t.path===void 0?void 0:{path:t.path})},xi=async(e,t,n)=>{let r={deploymentId:null};try{let i=await si(e,t,n,e=>{r.deploymentId=e}),a=await li(e,{canvasId:n.canvasId,deploymentId:i.deploymentId},3e5);if(bi(a),a.state===`abandoned`)throw new g(`NOT_FOUND`,`Prototype deployment ${i.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);if(a.state!==`ready`)throw Error(`prototype ingestion is still running`);let o=Oe.safeParse(await e.mutate(vi[0],{canvasId:n.canvasId,deploymentId:i.deploymentId,baseVersion:n.baseVersion}));if(!o.success)throw yi(`attachment`);return{...o.data,fileCount:a.fileCount,totalBytes:a.totalBytes,alreadyExists:i.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 g&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||r.deploymentId===null?e:new pe(`Prototype deployment ${r.deploymentId} was created, but publishing did not complete.`,`Retry 'enhance prototype publish' with the same --client-token ${n.clientToken}.`)}},Si=(e,t)=>({execute:async n=>xi(e,t,n)}),Ci=(e,t)=>{if(e.id!==t.jobId||e.canvasId!==t.canvasId)throw new g(`NOT_FOUND`,`The preparation does not belong to this operation.`,`Use the complete operation reference returned by the original action.`);return{kind:`canvas-preparation`,operation:t,state:e.state,phase:e.phase,requestedVersion:e.requestedVersion,failure:e.failure,outcome:`not_confirmed`,prepared:e.state===`succeeded`,warnings:[`Preparation is not a canvas commit. Repeat the original tool with identical arguments and clientToken to finish; status reads never commit.`]}},wi=async(e,t)=>{let{job:n}=xe.parse(await e.query(`canvas.render.preparation.get`,{jobId:t.jobId}));return Ci(n,t)},H=(e,t)=>{let n=40,r=e=>{let t=e.slice(0,n);return n-=t.length,t},i=r(e.insertedNodeIds),a=r(e.changedNodeIds),o=r(e.removedNodeIds),s=e.insertedNodeIds.length+e.changedNodeIds.length+e.removedNodeIds.length;return{outcome:`committed`,canvasId:e.canvasId,mutationId:e.mutationId,previousVersion:e.previousVersion,version:e.version,operation:{kind:`canvas-mutation`,canvasId:e.canvasId,mutationId:e.mutationId,fingerprint:t},affected:{insertedNodeIds:i,changedNodeIds:a,removedNodeIds:o,complete:s<=40,total:s},...e.copiedNodeIds!==void 0&&{identities:{entries:Object.entries(e.copiedNodeIds).toSorted(([e],[t])=>e.localeCompare(t,`en`)).slice(0,40).map(([e,t])=>({sourceNodeId:e,nodeId:t})),complete:Object.keys(e.copiedNodeIds).length<=40,total:Object.keys(e.copiedNodeIds).length}},verification:{rendered:!1},warnings:[]}},Ti=async(e,t,n)=>{if(n.kind!==`canvas-render`||n.state!==`succeeded`)return n;try{let{job:r}=v.parse(await e.query(`canvas.render.get`,{jobId:n.operation.jobId}));return r.id!==n.operation.jobId||r.canvasId!==n.operation.canvasId||r.state!==`succeeded`?{...n,warnings:[`The stored result is unavailable for image delivery. Read this operation again.`]}:{status:n,localImage:await Sn(e,t,r,{at:new Date,outputPath:null,overwrite:!1})}}catch{return{...n,warnings:[`The render completed, but its image could not be delivered. Check access and artifact expiry before retrying this operation reference.`]}}},U=[`canvas.mutation.get`,`canvas.render.get`,`canvas.render.getImport`,`prototype.getPublishStatus`,`canvas.asset.get`],Ei=(e,t)=>{if(e!==t)throw new g(`NOT_FOUND`,`The operation does not belong to this canvas.`,`Use the operation reference returned by the original action.`)},Di=e=>[...e.insertedNodeIds.map(e=>({nodeId:e,change:`inserted`})),...e.changedNodeIds.map(e=>({nodeId:e,change:`changed`})),...e.removedNodeIds.map(e=>({nodeId:e,change:`removed`})),...Object.entries(e.copiedNodeIds??{}).toSorted(([e],[t])=>e.localeCompare(t,`en`)).map(([e,t])=>({nodeId:t,sourceNodeId:e,change:`copied`}))],Oi=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,a=ae.parse(await e.query(U[0],{canvasId:n.canvasId,mutationId:n.mutationId,fingerprint:n.fingerprint}));return a.state===`not-found`?{kind:`canvas-mutation`,state:`not_found`,operation:n,outcome:`unknown`,warnings:[`No durable receipt was found. The original request may still be running.`]}:{kind:`canvas-mutation`,state:`committed`,receipt:H(a.result,n.fingerprint),affected:R(Di(a.result),r,i)}},ki=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,{job:a}=v.parse(await e.query(U[1],{jobId:n.jobId}));Ei(a.canvasId,n.canvasId);let o=a.result===null?null:Ai(a.result);return{kind:`canvas-render`,operation:n,state:a.state,phase:a.phase,requestedVersion:a.requestedVersion,target:a.target,sourceState:a.sourceState??null,evidence:o,details:R(ji(a),r,i),failure:a.failure,pixelsDelivered:!1,warnings:[`Status reports stored render evidence. It does not deliver or inspect the image.`]}},Ai=e=>{let{warnings:t,timings:n,...r}=e;return{...r,warningCount:t.length,timingCount:n.length}},ji=e=>e.result===null?[]:[...e.result.warnings.map(e=>({kind:`warning`,warning:e})),...e.result.timings.map(e=>({kind:`timing`,timing:e}))],Mi=async(e,t)=>{let n=Be.parse(await e.query(U[4],{canvasId:t.canvasId,clientToken:t.clientToken}));if(Ei(n.canvasId,t.canvasId),n.clientToken!==t.clientToken)throw new g(`NOT_FOUND`,`The resource does not belong to this import.`,`Use the operation reference returned by the original import.`);return{kind:`canvas-asset`,operation:t,resource:n,placement:`not_checked`}},Ni=async(e,t)=>{let{operation:n,offset:r,limit:i}=t;switch(n.kind){case`canvas-asset`:return R([],r,i),Mi(e,n);case`canvas-mutation`:return Oi(e,{...t,operation:n});case`canvas-preparation`:{let r=await Oi(e,{...t,operation:{kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:n.mutationId,fingerprint:n.fingerprint}});return r.kind===`canvas-mutation`&&r.state===`committed`?r:wi(e,n)}case`canvas-render`:return ki(e,{...t,operation:n});case`canvas-conversion`:{let{job:t}=Re.parse(await e.query(U[2],{jobId:n.jobId}));return Ei(t.canvasId,n.canvasId),Ir(t,{offset:r,limit:i})}case`prototype-deployment`:return R([],r,i),{kind:`prototype-deployment`,operation:n,publication:st.parse(await e.query(U[3],{canvasId:n.canvasId,deploymentId:n.deploymentId})),attachment:`not_checked`,warnings:[`Publication readiness does not establish canvas attachment or successful interactive verification.`]}}},Pi=(e,t)=>({execute:async n=>{let r=await Ni(e,n);return t!==void 0&&n.includeImage?Ti(e,t,r):r}}),Fi=[`transcript.get`],Ii=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),Li=e=>({execute:async t=>{let n=ve.safeParse(await e.query(Fi[0],t));if(!n.success)throw new g(`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:Ii(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),Ri=[`canvas.render.get`,`canvas.render.snapshot`],zi=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),Bi=e=>new g(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}),Vi=async(e,t)=>{let n=v.safeParse(await e.query(Ri[0],{jobId:t}));if(!n.success)throw new g(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return n.data.job},Hi=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 l=Date.now(),u=`${o.state}:${o.phase}`;if((u!==c||l-s>=5e3)&&(r({event:`snapshot.progress`,jobId:o.id,state:o.state,phase:o.phase,elapsedMs:l-a,timeoutMs:n.timeoutMs,retryClientToken:n.retryClientToken}),s=l,c=u),l>=i){if(n.bounded===!0)return o;throw new g(`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 zi();let d=await Vi(e,o.id);if(d.id!==t.id)throw Ui();Wi(d,n),o=d}return o},Ui=()=>new g(`INTERNAL`,`The snapshot response does not match the requested source or revision.`,`Run enhance doctor and report the capture job ID.`),Wi=(e,t)=>{if(e.canvasId!==t.canvasId||e.purpose!==`snapshot`||e.sourceState?.recordingId!==t.recordingId||e.sourceState.atMs!==t.atMs||t.context!==void 0&&e.requestedVersion!==t.context.expectedVersion)throw Ui();if(e.state!==`succeeded`)return;let n=e.result.snapshot,r=e.result.sourceState;if(e.result.canvasId!==t.canvasId||e.result.loadedVersion!==e.requestedVersion||e.result.requestedVersion!==e.requestedVersion||r?.recordingId!==t.recordingId||r.requestedAtMs!==t.atMs||r.settledAtMs!==t.atMs||n?.recordingId!==t.recordingId||n.atMs!==t.atMs||n.screenId!==e.id||n.screenNodeId!==`scr_${t.recordingId}_${String(t.atMs)}`||t.context!==void 0&&n.version!==t.context.expectedVersion+1)throw Ui()},Gi=(e,t)=>({operation:{kind:`canvas-render`,canvasId:e.canvasId,jobId:e.id},state:e.state,requestedVersion:e.requestedVersion,source:{kind:`recording`,recordingId:t.recordingId,atMs:t.atMs},attachment:e.state===`succeeded`?`committed`:e.state===`queued`||e.state===`running`?`pending`:`not_confirmed`,result:e.result?.snapshot??null,failure:e.failure,warningCount:e.result?.warnings.length??0,warnings:[e.state===`succeeded`?`The durable screen is attached. Render the returned node at its committed version to verify placement; use operation_status for source warnings.`:`Follow operation_status for this job. An incomplete job is not proof of attachment or proof that no durable screen was created.`]}),Ki=async(e,t,n)=>{let r=St.parse(t),i=b(r.canvasRef);return Ji(e,()=>null).execute({canvasId:i.canvasId,recordingId:r.source.recordingId,atMs:r.source.atMs,retryClientToken:n,timeoutMs:r.waitMs,bounded:!0,context:{expectedVersion:r.baseVersion,request:{previewJobId:r.previewJobId,scope:{pageId:i.pageId,nodeIds:[...i.nodeIds]},placement:r.placement}}})},qi=async(e,t,n)=>{let r=ct.safeParse(await e.mutate(Ri[1],{canvasId:n.canvasId,recordingId:n.recordingId,atMs:n.atMs,...n.context!==void 0&&{context:n.context}}));if(!r.success)throw new g(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");Wi(r.data.job,n);let i=await Hi(e,r.data.job,n,t);if(n.bounded===!0)return Gi(i,n);if(i.state!==`succeeded`||i.result.snapshot===void 0)throw Bi(i);let a={...i,result:{...i.result,snapshot:i.result.snapshot}},o=a.result.snapshot;return{jobId:a.id,canvasId:a.canvasId,...o,warnings:a.result.warnings,retryClientToken:n.retryClientToken,next:[`enhance canvas node --canvas ${a.canvasId} --node-id ${o.screenNodeId}`,`enhance canvas render --canvas ${a.canvasId} --node-id ${o.screenNodeId} --expected-version ${String(o.version)}`]}},Ji=(e,t)=>({execute:async n=>qi(e,t,n)}),Yi={".avif":`image/avif`,".gif":`image/gif`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".webp":`image/webp`,".ttf":`font/ttf`,".otf":`font/otf`,".woff":`font/woff`,".woff2":`font/woff2`},Xi=()=>new g(`BAD_REQUEST`,`Choose one supported regular image or font file of at most 20 MiB.`,`Use an explicit local PNG, JPEG, GIF, WebP, AVIF, TTF, OTF, WOFF or WOFF2 file.`),Zi=async e=>{let t=Yi[E.extname(e).toLowerCase()];if(t===void 0)throw Xi();let n=await zt(e,Ot.O_RDONLY|Ot.O_NONBLOCK);try{let e=await n.stat();if(!e.isFile()||e.size===0||e.size>20971520)throw Xi();let r=Buffer.alloc(e.size+1),i=0;for(;i<r.byteLength;){let e=await n.read(r,i,r.byteLength-i,i);if(e.bytesRead===0)break;i+=e.bytesRead}if(i!==e.size)throw new g(`CONFLICT`,`The selected asset changed while it was being read.`,`Finish writing the file, then retry the unchanged import intent.`);let a=r.subarray(0,i);return{body:a,kind:t.startsWith(`image/`)?`image`:`font`,contentType:t,bytes:i,sha256:D(`sha256`).update(a).digest(`hex`)}}finally{await n.close()}},Qi=e=>({read:async()=>{try{return await Zi(e)}catch(e){throw e instanceof g?e:new g(`BAD_REQUEST`,`The selected asset file cannot be read.`,`Choose an existing readable image or font file on this computer.`)}}}),$i=[`canvas.list`,`organisation.list`],ea=async(e,t)=>{let[n,r]=await Promise.all([e.query($i[0],{collection:t.collection,...t.title!==void 0&&{title:t.title},scope:`all`,deleted:!1,hasUnresolved:!1}),t.includeDestinations?e.query($i[1],{}):{items:[],truncated:!1}]),i=f.parse(n),a=dt.parse(r),o=i.items.map(e=>({kind:`canvas`,canvasRef:e.id,title:e.title,organisationId:e.organisationId,accessState:e.accessState,viewerCan:e.viewerCan,openPath:`/c/${e.id}`}));return t.includeDestinations&&o.push({kind:`destination`,destination:{kind:`personal`},name:`Personal`},...a.items.filter(e=>t.collection===`everything`||t.collection===e.id).map(e=>({kind:`destination`,destination:{kind:`team`,organisationId:e.id},name:e.name}))),{items:o,sourceTruncated:{canvases:i.truncated,destinations:a.truncated}}},ta=e=>{let t=[],n=2;for(let r of e){let e=Buffer.byteLength(JSON.stringify(r))+1;if(n+e>48e3)break;t.push(r),n+=e}return t},na=e=>({execute:async t=>{let{items:n,sourceTruncated:r}=await ea(e,t),{cursor:i,...a}=t,s=S(a),c=S({items:n,sourceTruncated:r}),l=i===void 0?null:o(i,et);if(l!==null&&l.queryDigest!==s)throw new g(`BAD_REQUEST`,`This cursor belongs to another canvas search.`,`Restart discovery with the requested query.`);if(l!==null&&l.snapshotDigest!==c)throw new g(`CONFLICT`,`The accessible canvases or destinations changed between pages.`,`Restart discovery so results are not silently skipped or combined across permissions.`);let u=l?.offset??0;if(u>n.length)throw new g(`BAD_REQUEST`,`The discovery cursor is out of range.`,`Restart discovery.`);let d=ta(n.slice(u,u+t.limit)),f=u+d.length,p=f<n.length,ee=r.canvases||r.destinations;return{items:d,returnedCount:d.length,totalAvailable:n.length,complete:!p&&!ee,sourceTruncated:r,nextCursor:p?x({protocol:`enhance-canvas-find/1`,queryDigest:s,snapshotDigest:c,offset:f}):null,warnings:ee?[`The source collection reached its existing limit. Refine the title or team; these results are not a complete inventory.`]:[]}}}),ra=async(e,t,n)=>{let r=Date.now()+n,i=t;for(;i.state===`queued`||i.state===`running`;){let n=r-Date.now();if(n<=0)break;if(await Ft(Math.min(250,n)),i=xe.parse(await e.query(`canvas.render.preparation.get`,{jobId:t.id})).job,i.id!==t.id)throw new g(`INTERNAL`,`Preparation identity changed.`,`Retry the original request.`)}return i},ia=async(e,t,n)=>{let r=de.parse(await e.mutate(`canvas.render.preparation.create`,t)),i=await ra(e,r.job,n);if(i.canvasId!==t.canvasId||i.requestedVersion!==t.expectedVersion||!qt(i.scope,t.scope)||!qt(i.request,t.request))throw new g(`CONFLICT`,`The native preparation does not match this request.`,`Read the canvas and prepare a new intent; do not apply this plan.`);if(i.state===`succeeded`&&i.result.loadedVersion!==t.expectedVersion)throw new g(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);return i},aa=async(e,t)=>{try{return _.parse(await j(e).execute(t))}catch(e){throw new g(e instanceof g?e.code:`INTERNAL`,e instanceof g?e.message:`The canvas commit could not be confirmed.`,`Read operation_status or repeat the original action with identical arguments and clientToken.`,{...e instanceof g&&e.fields,outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:t.canvasId,mutationId:t.mutationId,fingerprint:t.requestContext?.fingerprint})})}},oa=async(e,t,n,r)=>{if(n.result.loadedVersion!==t.baseVersion)throw new g(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);if(n.result.operations.length===0)return{outcome:`no_op`,canvasId:n.canvasId,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let a=i.parse({canvasId:n.canvasId,mutationId:t.clientToken,documentFormatVersion:7,baseVersion:t.baseVersion,operations:n.result.operations,requestContext:{fingerprint:r,revisionPolicy:`strict`,...t.request.kind===`duplicate`&&{copiedNodeIds:n.result.idMap}}}),o=await aa(e,a);if(o.canvasId!==n.canvasId||o.mutationId!==t.clientToken||o.previousVersion!==t.baseVersion||o.version!==t.baseVersion+1||t.request.kind===`duplicate`&&!qt(o.copiedNodeIds,n.result.idMap))throw new g(`INTERNAL`,`The canvas commit receipt could not be verified.`,`Check operation_status using the original mutation reference before retrying.`,{outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:r})});return H(o,r)},sa=e=>({execute:async t=>{let n=b(t.canvasRef),r={...n.pageId!==void 0&&{pageId:n.pageId},nodeIds:[...n.nodeIds]},i=S({operation:`canvas.prepare/1`,reference:n,baseVersion:t.baseVersion,request:t.request}),a=ae.parse(await e.query(`canvas.mutation.get`,{canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:i}));if(a.state===`committed`)return H(a.result,i);let o=await ia(e,{canvasId:n.canvasId,expectedVersion:t.baseVersion,request:t.request,scope:r},t.waitMs),s={kind:`canvas-preparation`,canvasId:n.canvasId,jobId:o.id,mutationId:t.clientToken,fingerprint:i};return o.state===`succeeded`?oa(e,t,o,i):Ci(o,s)}}),ca=new Set([`data-enhance-id`,`data-enhance-name`,`data-enhance-opaque`,`style`]),W=e=>{throw new g(`BAD_REQUEST`,e,`Use a complete current editable read and preserve its identity and opaque markers.`)},G=e=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),la=e=>{let t=Yt(e,{context:`declarationList`,onParseError:e=>W(e.message)});if(t.type!==`DeclarationList`)return W(`Expected an inline CSS declaration list.`);let n=new Map;return t.children.forEach(e=>{if(e.type!==`Declaration`||e.important!==!1)return W(`Use ordinary inline CSS properties without !important or at-rules.`);let t=e.property.startsWith(`--`)?e.property:e.property.toLowerCase();if(n.has(t))return W(`Duplicate CSS property: ${t}.`);n.set(t,Jt(e.value))}),Object.fromEntries(n)},ua=e=>{let t=Object.entries(e.styles).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`;`),n=`data-enhance-id="${G(e.id)}" data-enhance-name="${G(e.label)}"${e.opaque?` data-enhance-opaque="true"`:``}${t===``?``:` style="${G(t)}"`}`;return`<${e.tag} ${n}>${G(e.text)}${e.children.map(e=>ua(e)).join(``)}</${e.tag}>`},da=(e,t)=>{let n=new Set,r=[],i=N(e),a=(t,o)=>{if(o>C.depth||n.size>=C.nodes)return W(`This editable subtree exceeds the depth or node budget. Read a smaller root.`);if(n.has(t))return W(`The document contains repeated node identity.`);n.add(t);let s=P(e,t),c=i.get(t)??[],l=F(e,t)||s.component===`text`&&c.length>0||![`root`,`frame`,`group`,`text`].includes(s.component);l&&r.push(s.id);let u=l?{}:la(Object.entries(Ke(s)).map(([e,t])=>`${e}:${qe(e,t)}`).join(`;`));return{id:s.id,tag:s.component===`text`?`span`:`div`,label:s.label,opaque:l,styles:u,text:l||s.component!==`text`?``:pt(s)??``,children:l?[]:c.map(e=>a(e,o+1))}},o=a(t,0),s=ua(o);return s.length>C.characters?W(`This editable subtree exceeds the inline HTML budget. Read a smaller root.`):{projectionVersion:1,root:o,html:s,opaqueNodeIds:r}},fa=e=>e.flatMap(e=>`tagName`in e?[e]:e.nodeName===`#text`&&`value`in e&&e.value.trim()===``?[]:W(`Container content must contain identified elements; text belongs inside its retained span.`)),pa=e=>e.length>C.characters?W(`The submitted HTML exceeds the inline budget.`):Xt(e,{sourceCodeLocationInfo:!0,onParseError:e=>W(`Invalid HTML at line ${String(e.startLine)}: ${e.code}.`)}),ma=e=>{let t=pa(e),n=new Set,r=(e,t)=>{if(t>C.depth||n.size>=C.nodes)return W(`The submitted HTML exceeds the depth or node budget.`);if(e.tagName!==`div`&&e.tagName!==`span`)return W(`Unsupported retained element: ${e.tagName}.`);let i=Object.fromEntries(e.attrs.map(e=>!ca.has(e.name)||e.namespace!==void 0?W(`Unsupported attribute: ${e.name}.`):[e.name,e.value])),a=i[`data-enhance-id`],o=i[`data-enhance-name`];if(a===void 0||a===``||o===void 0)return W(`Every retained element requires its identity and name.`);if(n.has(a))return W(`Duplicate node identity: ${a}.`);n.add(a);let s=i[`data-enhance-opaque`];if(s!==void 0&&s!==`true`)return W(`Invalid opaque marker on ${a}.`);let c=e.tagName===`span`?e.childNodes.map(e=>`value`in e?e.value:W(`Retained text ${a} must contain text only; its existing rich formatting is preserved by the text owner.`)).join(``):``;return{id:a,tag:e.tagName,label:o,opaque:s===`true`,text:c,styles:la(i.style??``),children:e.tagName===`span`?[]:fa(e.childNodes).map(e=>r(e,t+1))}},i=fa(t.childNodes),a=i[0];return a===void 0||i.length!==1?W(`An editable update must contain exactly its original root.`):r(a,0)},ha=(e,t,n)=>{if(e.rootNodeIds!==void 0)return e.rootNodeIds;if(t.nodeIds.length>0)return t.nodeIds;if(t.pageId===void 0)return[`root`];let r=h(t,n);if(r.ok)return r.rootNodeIds;throw u(t,n),new g(`NOT_FOUND`,`The linked page is unavailable.`,`Copy a current page link.`)},ga=(e,t)=>{let n=new Set(t);for(let r of t){let t=new Set,i=e.relationships[r]?.parentId;for(;i!==void 0;){if(t.has(i)||n.has(i))throw new g(`BAD_REQUEST`,`Outline roots overlap or contain a parent cycle.`,`Choose disjoint roots so each depth and coverage statement has one meaning.`);t.add(i),i=e.relationships[i]?.parentId}}if(n.size!==t.length)throw new g(`BAD_REQUEST`,`Outline roots repeat.`,`Choose each root once.`)},_a=(e,t,n,r)=>{let i=[],a=new Set,o=N(e),s=(t,c)=>{if(a.has(t))return;a.add(t);let l=P(e,t),u=o.get(t)??[],d=F(e,t);if(i.push({id:t,label:l.label,kind:l.component,parentId:e.relationships[t]?.parentId??null,sortKey:e.relationships[t]?.sortKey??null,depth:c,childCount:u.length,childrenOmitted:c===n&&u.length>0,locked:d,visible:l.visible!==!1,editable:r&&!d&&[`root`,`frame`,`group`,`text`].includes(l.component),bounds:l.box??null}),c<n)for(let e of u)s(e,c+1)};for(let e of t)s(e,0);return i},va=(e,t,n)=>{if(e===void 0)return 0;let r=o(e,He);if(r.canvasId!==t.reference.canvasId||r.queryDigest!==n)throw new g(`BAD_REQUEST`,`This cursor belongs to another outline query.`,`Restart the outline read with the requested scope.`);if(r.version!==t.version)throw new g(`CONFLICT`,`The canvas changed between outline pages.`,`Restart the scoped read at the current revision. Do not combine pages from different revisions.`,{currentVersion:String(t.version),outcome:`not_committed`});return r.offset},ya=(e,t)=>{let{reference:n,scene:r,version:i,isCurrent:a}=t,o=ha(e,n,r);p(n,r,o),ga(r,o);let s=S({reference:n,roots:e.rootNodeIds??null,depth:e.depth,limit:e.limit}),c=va(e.cursor,t,s),l=_a(r,o,e.depth,a);if(c>l.length)throw new g(`BAD_REQUEST`,`The outline cursor is out of range.`,`Restart the outline read.`);let u=l.slice(c,c+e.limit),d=c+u.length,f=l.some(e=>e.childrenOmitted);return{canvasId:n.canvasId,version:i,scope:{rootNodeIds:[...o]},view:`outline`,complete:d===l.length&&!f,returnedCount:u.length,total:l.length,nodes:u,omittedDescendants:f,nextCursor:d<l.length?x({protocol:`enhance-canvas-outline/1`,canvasId:n.canvasId,version:i,queryDigest:s,offset:d}):null,warnings:a?[]:[`This legacy document is read-only until the normal editor upgrades it.`]}},ba=48e3,xa=e=>{let t=we(e);if(t!==null)return{storage:`canvas-image`,reference:e,ownerId:t.canvasId,assetId:t.assetId};let n=Ue(e);if(n!==null)return{storage:`canvas-font`,reference:e,ownerId:n.canvasId,assetId:n.sha256};let r=/^\/v1\/recording-assets\/([a-f0-9-]{36})\/([a-f0-9]{32,64})$/u.exec(e);return r===null?{storage:e.startsWith(`data:`)?`inline`:/^https?:\/\//u.test(e)?`external`:`opaque`,reference:null,ownerId:null,assetId:null}:{storage:`recording-asset`,reference:e,ownerId:r[1]??null,assetId:r[2]??null}},Sa=(e,t)=>typeof e[t]==`string`?e[t]:null,Ca=(e,t)=>{let n=new Map,r=[...t].toSorted((e,t)=>e.localeCompare(t));for(let t of r){let r=e.scene.nodes[t];if(r===void 0)continue;let i=(e,r,i)=>{let a={nodeId:t,kind:e,sourceDigest:S(r),...xa(r),delivery:`not_checked`,metadata:i};return n.set(S(a),a),r};pn(r,e=>i(`image`,e,null)),Ae(r.props,(e,t)=>i(`font`,e,{family:Sa(t,`family`),style:Sa(t,`style`),weight:Sa(t,`weight`)}))}return Array.from(n,([,e])=>e)},wa=(e,t,n)=>{if(e.cursor===void 0)return 0;let r=o(e.cursor,Ge);if(r.canvasId!==t.reference.canvasId||r.digest!==n)throw new g(`BAD_REQUEST`,`The resource cursor belongs to another query.`,`Restart this scoped resource read.`);if(r.version!==t.version)throw new g(`CONFLICT`,`The canvas changed between resource pages.`,`Restart the read at the current revision.`);return r.offset},Ta=(e,t,n,r)=>{let i=[],a=t.slice(n,n+r);for(let t of a){let n=e([...i,t]);if(Buffer.byteLength(JSON.stringify(n))>ba)break;i.push(t)}let o=e(i);if(i.length===0&&n<t.length||Buffer.byteLength(JSON.stringify(o))>ba)throw new g(`BAD_REQUEST`,`One resource or scope exceeds the bounded read budget.`,`Choose a smaller selection or inspect the resource in the editor.`);return o},Ea=(e,t)=>{let n=h(t.reference,t.scene);if(!n.ok)throw new g(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link; do not broaden the request.`);let r=S({reference:t.reference,limit:e.limit}),i=wa(e,t,r),a=Ca(t,n.nodeIds);if(i>a.length)throw new g(`BAD_REQUEST`,`The resource cursor is out of range.`,`Restart the scoped resource read.`);return Ta(e=>{let o=i+e.length;return{view:`resources`,canvasId:t.reference.canvasId,version:t.version,scope:{rootNodeIds:[...n.rootNodeIds]},coverage:`authored-resource-slots`,resources:e,total:a.length,returnedCount:e.length,complete:o===a.length,nextCursor:o===a.length?null:x({protocol:`enhance-canvas-resources/1`,canvasId:t.reference.canvasId,version:t.version,digest:r,offset:o}),warnings:[`Inventory includes declared image and font resource slots, including hidden and unused declarations. It does not resolve computed font usage or assets inside opaque screens, recordings, prototypes or raw CSS.`,`Resource delivery and availability have not been checked. Protected paths retain product authorization. External URLs and inline bytes are omitted; their digests identify the original source without exposing credentials or blobs.`,`Scoped reads include declarations on selected nodes and descendants only. A font declaration owned by an ancestor requires a separate explicit read of that scope.`]}},a,i,e.limit)},Da=e=>{let t=[...e];for(;Buffer.byteLength(JSON.stringify(t),`utf8`)>48e3;)t.pop();if(t.length===0&&e.length>0)throw new g(`BAD_REQUEST`,`One transcript cue exceeds the inline evidence budget.`,`Read this source through the comprehensive transcript CLI; no partial cue was returned.`);return t},Oa=(e,t,n)=>{if(e.state!==`ready`){if(t.cursor!==void 0)throw new g(`CONFLICT`,`The transcript changed during pagination.`,`Restart the read.`);return e}let{cursor:r,...i}=t,a=S({scope:n,range:i,transcript:e}),s=r===void 0?null:o(r,mt);if(s!==null&&s.digest!==a)throw new g(`CONFLICT`,`The transcript cursor no longer matches this source, range or revision.`,`Restart the requested range; do not combine transcript revisions.`);let c=e.cues.filter(e=>e.endMs>=t.startMs&&(t.endMs===void 0||e.startMs<t.endMs)),l=s?.offset??0;if(l>c.length)throw new g(`BAD_REQUEST`,`Transcript cursor offset is out of range.`,`Restart the read.`);let u=Da(c.slice(l,l+t.limit)),d=l+u.length;return{state:`ready`,languageCode:e.languageCode,integrity:e.integrity,isRefreshing:e.isRefreshing,requestedRange:{startMs:t.startMs,endMs:t.endMs??null},cues:u,returnedCount:u.length,totalInRange:c.length,omittedOutsideRange:e.cues.length-c.length,complete:d===c.length,nextCursor:d<c.length?x({protocol:`enhance-canvas-transcript/1`,digest:a,offset:d}):null}},ka=[`recording.get`,`prototype.getPublishStatus`,`transcript.get`],Aa=e=>{let t=d.safeParse(e.node.props?.capture).data;if(t===void 0)return null;let n=e.screens.find(e=>e.screenId===t.screenId);return{kind:`screen`,screenId:t.screenId,availability:n===void 0?t.html===void 0?`unavailable`:`inline-only`:n.download===null?`pending`:`available`,sourceUrl:n?.route??null,title:n?.title??null,viewport:n?.viewport??t.viewport,atMs:n?.atMs??t.atMs,recordingId:n===void 0?t.provenance?.recordingId??null:n.sourceRecordingId,missingAssetCount:n?.assetBundle?.missingAssetCount??null}},ja=e=>{let t=l.safeParse(e.props?.conversion).data;if(t===void 0)return{kind:`none`};let n=new Map,r=t.report?.issues??[];for(let e of r)n.set(e.code,(n.get(e.code)??0)+1);return{kind:`conversion`,recordingId:t.provenance?.recordingId??null,nodeCount:t.report?.nodeCount??null,issueCounts:Object.fromEntries(n)}},Ma=async(e,t)=>{let{node:n,canvasId:r}=t;if(n.component===`recording`){let t=Ze.parse(n.props),i=T.uuid().parse(t.recordingId),o=a.parse(await e.query(ka[0],{canvasId:r,recordingId:i}));return{kind:`recording`,recordingId:i,durationMs:o.durationMs,viewport:o.viewport,sourceUrl:o.sourceUrl,interrupted:o.interrupted,integrity:o.integrity,chunkCount:o.chunks.length,missingChunkCount:o.chunks.filter(e=>e.state===`missing`).length,hasAudio:o.audio!==null,missingAssetCount:o.missingAssetCount}}if(n.component===`prototype`){let t=_e.parse(n.props),i=st.parse(await e.query(ka[1],{canvasId:r,deploymentId:t.deploymentId}));if(i.prototypeId!==t.prototypeId)throw new g(`CONFLICT`,`Prototype identity does not match its deployment.`,`Read the node again.`);return{kind:`prototype`,...t,state:i.state,fileCount:i.fileCount}}return Aa(t)??ja(n)},Na=e=>({execute:async t=>{let n=await Ma(e,t),r=t.input.transcript,i=`recordingId`in n?n.recordingId:null;if(r!==void 0&&i===null)throw new g(`BAD_REQUEST`,`This object has no recording transcript source.`,`Choose a recording or a capture with recording provenance.`);let a=r===void 0?null:Oa(ve.parse(await e.query(ka[2],{canvasId:t.canvasId,recordingId:T.uuid().parse(i)})),r,{canvasRef:t.input.canvasRef,nodeId:t.node.id,version:t.version}),o=n.kind===`screen`&&[`pending`,`unavailable`].includes(n.availability);return{canvasId:t.canvasId,version:t.version,scope:{rootNodeIds:[t.node.id]},view:`source`,nodeId:t.node.id,source:n,transcript:a,complete:!o&&(a===null||a.state===`empty`||a.state===`ready`&&a.complete),pixelsInspected:!1,warnings:[...o?[`The captured source bytes are not currently available.`]:[],...a===null?[]:[`Transcript times describe speech, not verified visual transitions. Render and inspect candidate moments.`]]}}}),Pa=[`canvas.document.get`],Fa=e=>{throw new g(`CONFLICT`,`Canvas version ${String(e)} no longer matches this read.`,`Restart the scoped read at the current revision. Do not combine pages from different revisions.`,{currentVersion:String(e),outcome:`not_committed`})},Ia=(e,t)=>{let{reference:n,scene:r,version:i}=t;if(!t.isCurrent)throw new g(`BAD_REQUEST`,`This document format cannot produce an editable snapshot.`,`Open it in the current editor before editing.`);p(n,r,[e.rootNodeId]);let a=da(r,e.rootNodeId);return{canvasId:n.canvasId,version:i,scope:{rootNodeIds:[e.rootNodeId]},view:`editable`,complete:!0,projectionVersion:a.projectionVersion,rootNodeId:e.rootNodeId,html:a.html,opaqueNodeIds:[...a.opaqueNodeIds],snapshotToken:Se({reference:n,version:i,rootNodeId:e.rootNodeId,html:a.html}),warnings:a.opaqueNodeIds.length>0?[`Preserve opaque placeholders unchanged; their authored content remains in the canvas.`]:[]}},La=e=>({execute:async t=>{let n=b(t.canvasRef),r=m.parse(await e.query(Pa[0],{canvasId:n.canvasId}));if(t.expectedVersion!==void 0&&t.expectedVersion!==r.version)return Fa(r.version);let i=Qe.safeParse(r.document),a=i.success?i.data:y.parse(r.document);return t.view===`resources`?Ea(t,{reference:n,scene:a,version:r.version,isCurrent:i.success}):t.view===`outline`?ya(t,{reference:n,scene:a,version:r.version,isCurrent:i.success}):t.view===`source`?(p(n,a,[t.nodeId]),Na(e).execute({canvasId:n.canvasId,version:r.version,node:P(a,t.nodeId),screens:r.screens,input:t})):Ia(t,{reference:n,scene:a,version:r.version,isCurrent:i.success})}}),Ra=[`canvas.mutation.get`],za=e=>({execute:async t=>{let n=t.reference.canvasId,r=ae.parse(await e.query(Ra[0],{canvasId:n,mutationId:t.clientToken,fingerprint:t.fingerprint}));if(r.state===`committed`)return H(r.result,t.fingerprint);let a=await Un({remote:e},n,t.baseVersion),o=await t.plan(a);if(`outcome`in o)return o;if(Or(t.reference,a,o),o.length===0)return{outcome:`no_op`,canvasId:n,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let s=i.safeParse({canvasId:n,documentFormatVersion:7,mutationId:t.clientToken,baseVersion:t.baseVersion,operations:o,requestContext:{fingerprint:t.fingerprint,revisionPolicy:`strict`}});if(!s.success)throw new g(`BAD_REQUEST`,`The planned edit exceeds the canonical canvas contract.`,s.error.issues[0]?.message??`Reduce the edit scope.`,{outcome:`not_committed`});return H(_.parse(await j(e).execute(s.data)),t.fingerprint)}}),Ba=(e,t)=>{let n=N(e),r=new Set(t),i=new Set,a=t=>{if(i.has(t))return;if(i.add(t),P(e,t),F(e,t))throw new g(`BAD_REQUEST`,`Removing this subtree would remove locked content: ${t}.`,`Keep the locked subtree, or explicitly unlock it before requesting removal.`);let r=n.get(t)??[];for(let e of r)a(e)};for(let e of r){if(e===`root`)throw new g(`BAD_REQUEST`,`The canvas root cannot be removed.`,`Name its children.`);a(e)}return[...r].filter(t=>{let n=e.relationships[t]?.parentId;for(;n!==void 0;){if(r.has(n))return!1;n=e.relationships[n]?.parentId}return!0}).map(e=>({op:`remove`,nodeId:e}))},Va=e=>({execute:async({clientToken:t,...n})=>{let r=b(n.canvasRef);return za(e).execute({reference:r,baseVersion:n.baseVersion,clientToken:t,fingerprint:S({operation:`canvas.remove/1`,...n,reference:r}),plan:e=>Ba(e,n.rootNodeIds)})}}),Ha=(e,t,n,r)=>{let i=e.parents.get(t),a=e.children.get(n)??[];if(i===n&&a.indexOf(t)===r)return;if(F(e.document,t)||F(e.document,n))throw new g(`BAD_REQUEST`,`Locked node ${t} cannot be rearranged through HTML.`,`Keep locked placeholders in place or unlock them in the editor before editing.`);i!==void 0&&e.children.set(i,(e.children.get(i)??[]).filter(e=>e!==t));let o=e.children.get(n)??[];o.splice(r,0,t),e.children.set(n,o),e.parents.set(t,n),e.moves.push({nodeId:t,parentId:n,index:r})},Ua=(e,t,n)=>{let r={...e,nodes:Object.fromEntries(Object.entries(e.nodes).filter(([e])=>!n.has(e))),relationships:Object.fromEntries(Object.entries(e.relationships).filter(([e])=>!n.has(e)))},i={document:r,parents:new Map(Object.entries(r.relationships).map(([e,t])=>[e,t.parentId])),children:new Map([...N(r)].map(([e,t])=>[e,[...t]])),moves:[]},a=e=>{for(let[t,n]of e.children.entries())Ha(i,n.id,e.id,t),a(n)};return a(t),i.moves.length===0?[]:ar(r,i.moves).operations},K=e=>{throw new g(`BAD_REQUEST`,e,`Read the current subtree and reduce or correct the edit. No canvas changes were committed.`)},Wa=(e,t,n)=>{if(Object.keys(t.idMap).length!==n.fragments.length)return K(`Native compilation returned unexpected fragment identities.`);if(t.operations.length!==n.fragments.length)return K(`Native compilation returned an incomplete insertion plan.`);let r={...e,nodes:{...e.nodes},relationships:{...e.relationships}};for(let[e,i]of n.fragments.entries()){let n=t.operations[e];if(n?.op!==`insertConvertedSubtree`||n.destination.kind!==`insert-children`||n.destination.targetNodeId!==i.parentNodeId||n.rootNodeId!==t.idMap[i.id])return K(`Native compilation returned a mismatched insertion plan.`);for(let e of Object.keys(n.nodes))if(r.nodes[e]!==void 0||Object.hasOwn(r.tombstones,e))return K(`New HTML identity ${e} already exists.`);let a=M(r,i.parentNodeId).at(-1),o=a===void 0?null:r.relationships[a]?.sortKey??null;Object.assign(r.nodes,n.nodes),Object.assign(r.relationships,n.relationships,{[n.rootNodeId]:{parentId:i.parentNodeId,sortKey:Tt(o,null)}})}return r},Ga=(e,t)=>({...e,id:Object.hasOwn(t,e.id)?t[e.id]??e.id:e.id,children:e.children.map(e=>Ga(e,t))}),Ka={operations:[],idMap:{},rootNodeIds:[]},qa=(e,t,n=Ka)=>{let r=Wa(e,n,t),i=Ga(t.root,n.idMap),a=[...t.operations,...n.operations,...Ua(r,i,t.removed)];return a.length>1e3?K(`The complete edit exceeds the canonical operation budget.`):a},Ja=C.nodes,Ya=e=>e.attrs.find(e=>e.name===`data-enhance-id`)?.value,q=e=>{throw new g(`BAD_REQUEST`,e,`Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.`)},Xa=(e,t=0)=>t>C.depth?q(`The submitted HTML exceeds the depth budget.`):e.flatMap(e=>`tagName`in e?[e,...Xa(e.childNodes,t+1)]:[]),Za=e=>{let t=pa(e),n=Xa(t.childNodes);if(n.length>Ja)return q(`The HTML exceeds the node budget.`);let r=new Set(n.map(e=>Ya(e))),i=[],a=(e,t)=>{let n=Ya(e);if(n!==void 0)return{...e,childNodes:e.childNodes.map(e=>`tagName`in e?a(e,n):e)};if(t===void 0)return q(`The submitted HTML must retain its original root identity.`);if([e,...Xa(e.childNodes)].some(e=>e.attrs.some(e=>[`data-enhance-id`,`data-enhance-opaque`].includes(e.name))))return q(`A new HTML subtree cannot wrap retained identities or opaque placeholders. Insert the container and use canvas_arrange to move retained content into it.`);if(i.length>=C.newSubtrees)return q(`One update can compile at most 32 new subtrees.`);let o=`new_${String(i.length)}`;for(;r.has(o);)o=`_${o}`;return r.add(o),i.push({id:o,parentNodeId:t,html:Qt(e)}),{...e,tagName:`div`,nodeName:`div`,childNodes:[],attrs:[{name:`data-enhance-id`,value:o},{name:`data-enhance-name`,value:`New content`},{name:`data-enhance-opaque`,value:`true`}]}};return t.childNodes=t.childNodes.map(e=>`tagName`in e?a(e):e),{root:ma(Zt(t)),fragments:i}},J=e=>{throw new g(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Qa=e=>{let t=new Map,n=e=>{t.set(e.id,e);for(let t of e.children)n(t)};return n(e),t},$a=(e,t)=>Object.keys(e).length===Object.keys(t).length&&Object.entries(e).every(([e,n])=>t[e]===n),eo=(e,t,n,r)=>{let i=new Set,a=e=>{if(i.has(e.id))return J(`Overlapping removal roots include ${e.id}.`);if(t.has(e.id))return J(`Removed node ${e.id} is still present in the HTML.`);i.add(e.id);for(let t of e.children)a(t)};for(let t of n){let n=e.get(t);if(n===void 0||t===r)return J(`Invalid removal root: ${t}.`);a(n)}for(let n of e.keys())if(!t.has(n)&&!i.has(n))return J(`Missing retained node ${n}; declare intentional deletion in removeNodeIds.`);return i},to=(e,t,n)=>{if(t.tag!==n.tag||t.opaque!==n.opaque)return J(`The kind or opaque marker of ${t.id} changed.`);let r=!$a(t.styles,n.styles);if(t.opaque&&(r||t.label!==n.label||t.text!==n.text||n.children.length>0))return J(`Opaque node ${t.id} cannot be changed through HTML.`);let i=e.nodes[t.id];if(i===void 0)return J(`Node ${t.id} no longer exists.`);let a=[];if(t.label!==n.label&&a.push({op:`setLabel`,nodeId:t.id,label:n.label,labelOrigin:`user`}),t.text!==n.text&&a.push({op:`editText`,nodeId:t.id,change:s(i,{...i,props:_t(i,n.text)})}),r){let r=new Set([...Object.keys(t.styles),...Object.keys(n.styles)]),i=Object.fromEntries([...r].filter(e=>t.styles[e]!==n.styles[e]).map(e=>[e,n.styles[e]??null]));a.push(...pr(e,[{nodeIds:[t.id],styles:i}]))}return a},no=(e,t,n,r)=>{let i=da(e,t).root,a=Za(n),o=a.root;if(o.id!==t)return J(`The submitted HTML must retain its original root identity.`);let s=new Set(a.fragments.map(e=>e.id)),c=Qa(i),l=Qa(o),u=eo(c,l,r,t),d=new Set([...u,...r.flatMap(t=>[...Gn(e,t)])]);for(let t of d)if(F(e,t))return J(`Locked node ${t} cannot be removed through HTML.`);let f=r.map(e=>c.get(e)?.opaque===!0?J(`Use explicit canvas removal for opaque node ${e}.`):{op:`remove`,nodeId:e});for(let[t,n]of l){if(s.has(t))continue;let r=c.get(t);if(r===void 0)return J(`Unknown or outside-scope identity: ${t}.`);f.push(...to(e,r,n))}for(let e of a.fragments){let t=c.get(e.parentNodeId);if(t===void 0||t.opaque||t.tag!==`div`)return J(`Node ${e.parentNodeId} cannot contain new HTML.`)}return{root:o,operations:f,removed:d,fragments:a.fragments}},ro=(e,t,n)=>{let r=Te(e.snapshotToken,t);p(t,n,[r.rootNodeId]);let i=da(n,r.rootNodeId);if(Se({reference:t,version:r.version,rootNodeId:r.rootNodeId,html:i.html})!==e.snapshotToken)throw new g(`CONFLICT`,`The editable snapshot no longer matches the complete source.`,`Read the requested subtree again and deliberately reapply the intended change.`,{outcome:`not_committed`});return no(n,r.rootNodeId,e.html,e.removeNodeIds)},io=async(e,t,n)=>{let r=ro(t,n.reference,n.scene);if(r.fragments.length===0)return qa(n.scene,r);let i=await ia(e,{canvasId:n.reference.canvasId,expectedVersion:n.version,scope:{nodeIds:[...n.reference.nodeIds],...n.reference.pageId!==void 0&&{pageId:n.reference.pageId}},request:{kind:`compile-html`,fragments:[...r.fragments],contextOperations:r.operations.filter(e=>e.op!==`remove`)}},t.waitMs);return i.state===`succeeded`?qa(n.scene,r,i.result):Ci(i,{kind:`canvas-preparation`,canvasId:n.reference.canvasId,jobId:i.id,mutationId:t.clientToken,fingerprint:n.fingerprint})},ao=e=>({execute:async t=>{let n=$e.parse(t),r=b(n.canvasRef),i=Te(n.snapshotToken,r),a=S({operation:`canvas.updateHtml/1`,snapshotToken:n.snapshotToken,html:n.html,removeNodeIds:n.removeNodeIds});return za(e).execute({reference:r,baseVersion:i.version,clientToken:n.clientToken,fingerprint:a,plan:async t=>io(e,n,{reference:r,scene:t,fingerprint:a,version:i.version})})}}),oo=(e,t,n)=>({"canvas.arrange":async()=>{let{changes:r,...i}=me.parse(t);return sa(e).execute({...i,clientToken:n,request:{kind:`arrange`,changes:r}})},"canvas.duplicateNodes":async()=>{let{nodeIds:r,destination:i,...a}=ee.parse(t);return sa(e).execute({...a,clientToken:n,request:{kind:`duplicate`,nodeIds:r,destination:i}})},"canvas.find":async()=>na(e).execute(Je.parse(t)),"canvas.remove":async()=>Va(e).execute({...lt.parse(t),clientToken:n}),"canvas.read":async()=>{let n=Ee.safeParse(t);return n.success?Qr(e,n.data):La(e).execute(it.parse(t))},"canvas.updateHtml":async()=>ao(e).execute({...We.parse(t),clientToken:n})}),so=(e,t)=>{let n=b(e.canvasRef),r=n.nodeIds;if(e.target.kind===`content`&&r.length>1)throw new g(`BAD_REQUEST`,`Choose an explicit node within this selection.`,`Render the selected screens separately; do not broaden to the whole canvas.`);let i=e.target.kind===`content`?r[0]===void 0?n.pageId===void 0?e.target:{kind:`page`,pageId:n.pageId}:{kind:`node`,nodeId:r[0]}:e.target;return{canvasId:n.canvasId,expectedVersion:e.expectedVersion,target:i,sourceState:e.sourceState,scale:e.scale,scope:{nodeIds:r,...n.pageId!==void 0&&{pageId:n.pageId}},outputPath:null,overwrite:!1,timeoutMs:e.waitMs,timeoutOutcome:`pending`,retryClientToken:t}},co=(t,n)=>{let r=ye.shape.operation.safeParse({kind:`canvas-render`,canvasId:n.input.canvasId,jobId:t instanceof g?t.fields?.jobId:void 0}),i=e.extract([`failed`,`cancelled`,`expired`]).safeParse(t instanceof g?t.fields?.renderState:void 0);return{...r.success&&{operation:r.data},state:i.success?i.data:`not_confirmed`,error:t instanceof g?{code:t.code,message:t.message,remediation:t.remediation,...t.fields!==void 0&&{fields:t.fields}}:{code:`INTERNAL`,message:`This render outcome could not be confirmed.`,remediation:`Retry the identical batch and clientToken to recover its native render jobs.`}}},lo=(e,t)=>{let n=e.targets.filter(e=>e.maxOutputPixels===void 0).length,r=e.targets.reduce((e,t)=>e+(t.maxOutputPixels??0),0),i=Math.floor((rt-r)/Math.max(n,1));return e.targets.map(({id:n,maxOutputPixels:r,...a})=>{let o=t.get(n);if(o===void 0)throw TypeError(`A batch target has no native render request key.`);return{id:n,maxOutputPixels:r??i,input:so({...e,...a},o)}})},uo=async(e,t)=>{try{let n=await e.execute({...t.input,maxOutputPixels:t.maxOutputPixels}),r=nt.safeParse(n);if(!r.success)return ye.parse(n);let i=r.data.width*r.data.height;if(!Number.isSafeInteger(i)||i<=0||i>t.maxOutputPixels)throw new g(`INTERNAL`,`The render exceeded its allocated pixel budget.`,`Update the API and renderer together, then retry.`,{reason:`RENDER_BUDGET_UNSUPPORTED`});return r.data}catch(e){return co(e,t)}},fo={state:`not_started`,error:{code:`INTERNAL`,message:`Earlier work could not enforce the render budget.`,remediation:`Update the API and renderer together before retrying this batch.`}},po=e=>({execute:async(t,n)=>{let r=Me.parse(t),i=lo(r,n),a=[],o=0,s=!1;for(let t of i){let n=s?fo:await uo(e,t);`jobId`in n&&(o+=n.width*n.height),`error`in n&&n.error.fields?.reason===`RENDER_BUDGET_UNSUPPORTED`&&(s=!0),a.push({id:t.id,target:t.input.target,maxOutputPixels:t.maxOutputPixels,outcome:n})}let c=i[0];if(c===void 0)throw TypeError(`A render batch requires at least one target.`);return{kind:`canvas-render-batch`,canvasId:c.input.canvasId,requestedVersion:r.expectedVersion,complete:a.every(e=>`jobId`in e.outcome),maxOutputPixels:rt,renderedPixels:o,results:a,next:[`Inspect each delivered image alongside its target id. Collect pending images with operation_status and includeImage true. Retry uncertain outcomes with the identical batch and clientToken.`]}}}),Y=e=>jn(e.remote,ei(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),mo=async(e,t,n)=>{let r=Me.safeParse(t);if(r.success){e.mutationKey.select(n,!0);let t=new Map(r.data.targets.map(t=>[t.id,e.mutationKey.current(`canvas.render.create`,{batch:{canvasRef:r.data.canvasRef,expectedVersion:r.data.expectedVersion,targets:r.data.targets},targetId:t.id})])),i=Y(e);return po({execute:async t=>(e.mutationKey.select(t.retryClientToken,!1),i.execute(t))}).execute(r.data,t)}let i=ft.safeParse(t);if(i.success)return Y(e).execute(so(i.data,n));let a=ke.parse(t);return Y(e).execute({...a,retryClientToken:n})},ho=e=>({render:Y(e),execute:async(t,n)=>mo(e,t,n)}),go=new Date(`1980-01-01T00:00:00.000Z`),_o=33188,vo=(e,t)=>new g(`BAD_REQUEST`,e,t),yo=(e,t)=>{let n=D(`sha256`),r=0;return new en({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()}})},bo=e=>{let t=ce.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),n=Buffer.from(JSON.stringify(t),`utf8`);if(n.byteLength>e.limits.manifestBytes)throw vo(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,oe,{mtime:go,mode:_o,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},xo=(e,t,n)=>{let{source:r,content:i}=t,a={mtime:go,mode:_o,compress:i===null,forceDosTimestamp:!0};if(i===null){e.addReadStreamLazy(r.path,{...a,size:r.bytes},e=>{e(null,kt(r.absolutePath).pipe(yo(r,n)))});return}if(i.byteLength!==r.bytes)throw Error(`prototype file ${r.path} changed while it was packaged`);e.addBuffer(i,r.path,a),n({path:r.path,contentType:r.contentType,bytes:i.byteLength,sha256:D(`sha256`).update(i).digest(`hex`)})},So=async(e,t,n)=>{for(let r=0;r<t.length;r+=32){let i=await Promise.all(t.slice(r,r+32).map(async e=>({source:e,content:e.bytes<=128?await Bt(e.absolutePath):null})));for(let t of i)xo(e,t,n)}},Co=async e=>{let t=new nn,n=D(`sha256`),r=new en({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=tn(t.outputStream,r,At(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=bo({zip:t,completed:i,...e}))};try{await So(t,e.files,s)}catch(e){r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)),await o}if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let c=await Wt(e.artifactPath);if(c.size>e.limits.artifactBytes)throw vo(`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`)}},wo={".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`},To=e=>wo[E.extname(e).toLowerCase()]??`application/octet-stream`,Eo=async e=>{try{return await Wt(e)}catch{return null}},Do=e=>Buffer.byteLength(e,`utf8`),X=(e,t)=>new g(`BAD_REQUEST`,e,t),Oo=(e,t)=>{if(!Le.safeParse(e).success)throw X(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(Do(e)>t.pathBytes)throw X(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},ko=async(e,t,n,r)=>{let i=await Vt(t);if(n.has(i))throw X(`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=E.join(t,n.name),o=await Eo(i);if(o?.isDirectory()===!0){c.push(...await ko(e,i,a,r));continue}if(o?.isFile()!==!0)throw X(`Cannot read ${i} as a prototype file.`,`Pass a directory containing only regular files and directory links.`);let s=E.relative(e,i).split(E.sep).join(`/`).normalize(`NFC`);Oo(s,r),c.push({absolutePath:i,path:s,bytes:Number(o.size),contentType:To(i)})}return c},Ao=(e,t,n)=>{if(e.length===0)throw X(`The prototype build is empty.`,`Build the app before publishing it.`);if(e.length>n.fileCount)throw X(`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=re(t.path);if(r.has(e))throw X(`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 X(`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 X(`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 X(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw X(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},jo=async e=>{let t=E.resolve(e.directory),n=await Eo(t);if(n===null)throw new g(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!n.isDirectory())throw X(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let r=e.entryPath.split(E.sep).join(`/`).normalize(`NFC`);Oo(r,e.limits);let i=await ko(t,t,new Set,e.limits);Ao(i,r,e.limits);let a=await Rt(E.join(wt(),`enhance-prototype-artifact-`)),o=E.join(a,`artifact.zip`);try{let t=await Co({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:()=>kt(o),dispose:async()=>Ut(a,{recursive:!0})}}catch(e){throw await Ut(a,{recursive:!0}),e}},Mo=e=>({package:async t=>{if(e===void 0)throw X(`No build directory was selected.`,`Select a build before publishing.`);return jo({...t,directory:e})}}),No=async(e,t)=>{let n=ie.parse(t);return j(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Po=async(e,t)=>{let n=ne.parse(t);return Zr(e.remote,ho(e).render).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},Fo=async(e,t,n)=>{let r=Ve.parse(t),i=b(r.canvasRef);return Zr(e.remote,ho(e).render).execute({canvasId:i.canvasId,pageId:i.pageId,selectionNodeIds:i.nodeIds,targetNodeId:r.destination.parentNodeId,mode:`insert-children`,html:r.html,baseVersion:r.baseVersion,revisionPolicy:`strict`,responseMode:`bounded`,review:`none`,renderClientToken:n,renderOutputPath:null,overwriteRender:!1,renderScale:1,renderTimeoutMs:r.waitMs})},Io=async(e,t)=>{let n=le.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},Lo=async(e,t,n)=>{let r=ot.parse(t);return Si(e.remote,Mo(r.directory)).execute({...r,clientToken:n})},Ro=async(e,t,n)=>{let r=se.parse(t);return Ji(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},zo=async(e,t)=>{let n=Fe.parse(t);return Li(e.remote).execute(n)},Bo=async(e,t)=>{let n=vt.parse(t),r=b(n.canvas);return Mr(e.remote).execute({...r,baseVersion:n.baseVersion,edits:n.edits,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Vo=async(e,t)=>Pi(e.remote,ei(e.configDirectory)).execute(ge.parse(t)),Ho=async(e,t,r,i)=>{let a={...oo(e.remote,r,i),"canvas.importAsset":async()=>{let t=n.parse(r);return ii(e.remote,Qi(t.source.path)).execute({canvasRef:t.canvasRef,clientToken:i})},"operation.status":async()=>Vo(e,r),"canvas.edit":async()=>Bo(e,r),"canvas.apply":async()=>No(e,r),"canvas.render":async()=>ho(e).execute(r,i),"canvas.writeHtml":async()=>Po(e,r),"canvas.insertHtml":async()=>Fo(e,r,i),"canvas.capture":async()=>Ki(e.remote,r,i),"canvas.makeEditable":async()=>Wr(e.remote,r),"comment.attention":async()=>Io(e,r),"prototype.publishCanvas":async()=>{let t=ht.parse(r);return _i(e.remote,Mo(t.source.kind===`directory`?t.source.directory:void 0)).execute({...t,source:t.source.kind===`directory`?{...t.source,kind:`build`}:t.source,clientToken:i})},"prototype.publish":async()=>Lo(e,r,i),"recording.snapshot":async()=>Ro(e,r,i),"transcript.read":async()=>zo(e,r)}[t];if(a===void 0)throw TypeError(`${t} has no composite execution`);return a()},Uo=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??Pt();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Ho(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),Wo=`/callback`,Go=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),Ko=e=>{let t=w.platform===`darwin`?{executable:`open`,arguments:[e]}:w.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=on(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},qo=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==Wo){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)},Jo=e=>{let t=Go(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},Yo=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=sn((n,r)=>{qo({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)}${Wo}`,a=Jo({...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&&Ko(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},Xo=e=>({authorize:async t=>{try{let n=Nt(32).toString(`base64url`),r=D(`sha256`).update(n).digest(`base64url`),i=Nt(32).toString(`base64url`),a=await Yo({...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 g(`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.`)}}}),Zo=e=>e===void 0||e===``?void 0:e,Qo=(e,t,n)=>{let r=Zo(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=Zo(e.ENHANCE3_API_URL),a=E.join(t,`.config`,n.configDirectoryName),o=Zo(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&&E.resolve(o)!==E.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}},$o={apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`},es=()=>Qo(w.env,Ct(),$o),ts=()=>{let e=T.enum([`legacy`,`canvas`]).default(`legacy`).parse(w.env.ENHANCE_MCP_PROFILE),t=T.enum([`true`,`false`]).default(`false`).parse(w.env.ENHANCE_MCP_READ_ONLY)===`true`;if(t&&e!==`canvas`)throw Error(`ENHANCE_MCP_READ_ONLY requires the canvas profile.`);return{...es(),profile:e,isReadOnly:t,workflowsDirectory:w.env.ENHANCE_WORKFLOWS_DIR}},ns=T.object({token:T.string().startsWith(`enh_`)}),rs=e=>{let t=E.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await Bt(t,`utf8`));return ns.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Lt(e,{recursive:!0,mode:448}),await It(e,448);let r=E.join(e,`credentials.${String(w.pid)}.tmp`);await Kt(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await Ht(r,t),await It(t,384)},remove:async()=>{try{return await Gt(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},is={path:`direct_cli`},as=T.object({access_token:T.string().min(1)}),os=T.object({code:T.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),Z=`Check network access and proxy settings for this API, then run enhance doctor again.`,Q=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,ss=e=>{let t=os.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?ss(e.cause):e instanceof Error?e.name:`Network request failed`},cs=(e,t)=>new g(`INTERNAL`,`${Q(e)} answered HTTP ${String(t)}.`,Z),$=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new g(`INTERNAL`,`Could not reach ${Q(e)}: ${ss(t)}.`,Z)}},ls=async(e,t)=>{let n=await $(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw cs(e,n.status);return n},us=(e,t,n=null,r=is)=>rn({links:[an({url:`${e}/trpc`,fetch:async(e,t)=>ls(e,{...t,signal:t?.signal??null}),headers:{[te]:JSON.stringify(r),...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),ds=async e=>{try{return await e()}catch(e){throw ut(e)}},fs=async e=>{let t=await fetch(e);if(!t.ok)throw new g(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())},ps=async e=>{let t=await $(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new g(`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 g(`INTERNAL`,`${Q(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,Z);return t.json()},ms=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await $(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw cs(e,n.status);return n.json()},hs=async e=>{let t=await $(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 g(`INTERNAL`,`${Q(e.issuer)} token exchange answered HTTP ${String(t.status)}`,Z);return as.parse(await t.json()).access_token},gs=async e=>{try{let t=await $(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:cs(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${Q(e)}.`}}},_s=async e=>{let t=!(e.body instanceof Uint8Array),n=t?$t.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 g(`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 g(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return a.replaceAll(`"`,``)},vs=(e,t,n,r=is)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>ps(i),oauthMetadata:ms,exchangeOauthCode:hs,query:async(e,n)=>ds(async()=>us(i,await t.read(),null,r).query(e,n)),queryWithToken:async(e,t,n)=>ds(async()=>us(i,n,null,r).query(e,t)),mutate:async(e,a)=>ds(async()=>us(i,await t.read(),n.current(e,a),r).mutation(e,a)),mutateWithToken:async(e,t,n)=>ds(async()=>us(i,n,null,r).mutation(e,t)),download:fs,upload:_s,health:async()=>gs(i)}},ys=e=>Array.isArray(e)?e.map(e=>ys(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ys(t)])),bs=(e,t,n)=>D(`sha256`).update(`${e}\0${t}\0${JSON.stringify(ys(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),xs=()=>{let e=Pt(),t=!1;return{current:(n,r)=>t?bs(e,n,r):e,select:(n,r)=>{e=n??Pt(),t=r}}};export{jn as _,ts as a,ei as c,Nr as d,Mr as f,Pn as g,j as h,es as i,Qr as l,Un as m,vs as n,Xo as o,Or as p,rs as r,Uo as s,xs as t,Zr as u,gn as v};
|