@enhance-eng/enhance-dev 0.1.7-dev.sha-e8d495edd470
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/capability-inventory.mapper-B_GMS9z3.mjs +2 -0
- package/dist/cli-output-identity.lib-COXLA7bt.mjs +25 -0
- package/dist/main.mjs +14 -0
- package/dist/mcp-main.mjs +2 -0
- package/dist/mcp-server.adapter-CH7nbGxy.mjs +4 -0
- package/dist/mcp.mjs +2 -0
- package/dist/mutation-key.adapter-BhdfFChs.mjs +2 -0
- package/package.json +46 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
const e=e=>e.map(e=>({id:e.id,cliPath:e.cli?.path??null,operation:e.operation,source:e.source,effect:e.effect,idempotency:e.idempotency,exposure:e.policy.exposure,reason:e.policy.reason,owner:e.policy.owner,schemaDigest:e.schemaDigest,guidanceDigest:e.guidanceDigest,behaviorDigest:e.behaviorDigest}));export{e as t};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{FailedToExitError as e,parseRouter as t}from"trpc-cli";import{z as n}from"zod";import{createHash as r}from"node:crypto";import{TRPCError as i,initTRPC as a}from"@trpc/server";import{middlewareMarker as o}from"@trpc/server/unstable-core-do-not-import";import{TRPCClientError as s}from"@trpc/client";var c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const l=2048,ee=1e4,u=1024,d=u*u;n.object({cursor:n.string().nullable().default(null),limit:n.number().int().min(1).max(100).default(20)});const f=e=>n.object({items:n.array(e),truncated:n.boolean()}),te=n.enum([`never-captured`,`capture-pending`,`extension-unavailable`,`capture-failed`,`source-mismatch`,`upload-incomplete`,`blob-missing`,`image-load-failed`,`unsupported-legacy-state`]),ne=n.object({thumbnailId:n.uuid(),url:n.string().max(4096),width:n.literal(528),height:n.literal(312),bytes:n.number().int().min(1).max(1048576)}),re=n.object({canvasId:n.uuid(),thumbnailId:n.uuid(),clientReleaseIdentity:n.string().min(1).max(100),attemptedOperation:n.literal(`thumbnail-download`),recoveryOutcome:n.literal(`fallback-shown`)}),ie=n.object({recorded:n.literal(!0)}),ae=n.enum([`invite-only`,`link-view`,`link-comment`]),p=n.enum([`owner`,`can-comment`,`can-view`]),m=n.enum([`can-comment`,`can-view`]),oe=n.object({read:n.boolean(),comment:n.enum([`yes`,`sign-in`,`no`]),share:n.boolean(),manage:n.boolean()}),h=n.object({id:n.uuid(),title:n.string().min(1).max(200),accessState:ae,organisationId:n.uuid().nullable(),sourceUrl:n.string().max(l).nullable(),unresolvedCount:n.number().int().min(0),viewerCan:oe,createdAt:n.iso.datetime(),lastActivityAt:n.iso.datetime()}),g=n.object({title:n.string().trim().min(1).max(200),organisationId:n.uuid().nullable().default(null),sourceUrl:n.string().max(l).nullable().default(null)}),se=n.object({canvasId:n.uuid()}),ce=n.union([n.literal(`own`),n.literal(`everything`),n.uuid()]),le=n.object({collection:ce.default(`own`),title:n.string().trim().min(1).max(200).optional().describe(`Title text to match before returning canvas ids.`),deleted:n.boolean().default(!1),accessState:ae.optional(),scope:n.enum([`all`,`mine`,`shared`]).default(`all`),hasUnresolved:n.boolean().default(!1)}),ue=h.extend({screenCount:n.number().int().min(0),hasRecording:n.boolean()}),de=f(n.union([ue.extend({thumbnail:ne}),ue.extend({thumbnail:n.null(),thumbnailFallbackReason:te})])),fe=n.object({canvasId:n.uuid(),title:n.string().trim().min(1).max(200)}),pe=n.object({canvasId:n.uuid()}),me=n.object({canvasId:n.uuid(),deletedAt:n.iso.datetime()}),he=n.object({canvasId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)])}),ge=n.object({canvas:h}),_e=n.object({canvasId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)]),title:n.string().trim().min(1).max(200).optional()}),ve=n.object({canvas:h}),ye=n.object({canvasId:n.uuid(),confirmation:n.string().min(1).max(200)}),be=n.object({canvasId:n.uuid()}),xe=n.object({canvasId:n.uuid(),accessState:ae}),Se=n.object({canvas:h,widened:n.boolean()}),Ce=n.object({canvasId:n.uuid()}),we=n.object({lastViewedAt:n.iso.datetime().nullable()}),Te=n.object({canvasId:n.uuid()}),Ee=n.object({canvasId:n.uuid()}),De=1e5,_=n.number().min(-1e5).max(De),v=n.number().nonnegative().max(De),Oe=n.object({ratio:v,offset:_.optional()}),ke=n.object({min:v.optional(),max:v.optional(),minParent:Oe.optional(),maxParent:Oe.optional()}).refine(({min:e,max:t})=>e===void 0||t===void 0||e<=t,`size minimum cannot exceed maximum`),Ae=n.discriminatedUnion(`mode`,[n.object({mode:n.literal(`fixed`),value:v}),ke.extend({mode:n.literal(`hug`),basis:v.optional()}),ke.extend({mode:n.literal(`fill`),offset:_.optional()})]),je=n.object({top:v,right:v,bottom:v,left:v}),Me=n.union([n.literal(`auto`),_]),Ne=n.object({top:Me,right:Me,bottom:Me,left:Me}),Pe=n.object({basis:v,align:n.enum([`start`,`center`,`end`,`stretch`])}),Fe=n.object({mode:n.enum([`auto-fill`,`auto-fit`]),minimum:n.number().positive().max(De)}),Ie=n.object({x:_,y:_}),Le=n.object({direction:n.enum([`row`,`column`]),alignItems:n.enum([`start`,`center`,`end`,`stretch`]),alignContent:n.enum([`start`,`center`,`end`,`stretch`,`space-between`,`space-around`,`space-evenly`]).optional(),justifyContent:n.enum([`start`,`center`,`end`,`space-between`,`space-around`,`space-evenly`]),gap:v,rowGap:v.optional(),columnGap:v.optional(),wrap:n.enum([`nowrap`,`wrap`]).optional(),gridColumns:n.number().int().positive().max(De).optional(),gridAutoRepeat:Fe.optional(),materialized:n.boolean().optional(),padding:je}),Re=n.object({rotation:_,flipHorizontal:n.boolean().optional(),flipVertical:n.boolean().optional(),aspectRatioLocked:n.boolean().optional(),aspectRatio:n.number().positive().max(De).optional(),horizontal:Ae,vertical:Ae,position:n.enum([`flow`,`absolute`]),alignSelf:n.enum([`auto`,`start`,`center`,`end`,`stretch`]).optional(),flexGrow:v.optional(),flexShrink:v.optional(),flexBasis:n.union([n.literal(`auto`),v,Oe]).optional(),flowOffset:Ie.optional(),order:_.int().optional(),margin:Ne.optional(),gridTrack:Pe.optional(),clipContent:n.boolean().optional(),container:Le.optional()}),ze=_,y=v,b=n.number().min(0).max(1),Be=n.string().min(1).max(200),Ve=n.object({space:n.enum([`srgb`,`display-p3`]),red:b,green:b,blue:b,alpha:b}),He=n.object({id:Be,position:b,color:Ve}),Ue=n.object({x:b,y:b}),We=n.object({id:Be,visible:n.boolean(),opacity:b}),Ge=n.discriminatedUnion(`kind`,[We.extend({kind:n.literal(`solid`),color:Ve}),We.extend({kind:n.literal(`linear-gradient`),angle:ze,stops:n.array(He).min(2).max(32)}),We.extend({kind:n.literal(`radial-gradient`),center:Ue,radius:Ue,stops:n.array(He).min(2).max(32)}),We.extend({kind:n.literal(`image`),assetId:n.string().min(1).max(500),fit:n.enum([`fill`,`fit`,`crop`,`tile`]),crop:n.object({x:b,y:b,width:b,height:b}).optional()})]),Ke=n.object({topLeft:y,topRight:y,bottomRight:y,bottomLeft:y}),qe=n.object({visible:n.boolean(),width:n.object({top:y,right:y,bottom:y,left:y}),style:n.enum([`solid`,`dashed`,`dotted`]),paint:Ge,alignment:n.enum([`inside`,`center`,`outside`])}),Je=n.object({visible:n.boolean(),width:y,offset:ze,style:n.enum([`solid`,`dashed`,`dotted`]),paint:Ge}),Ye=n.object({id:Be,visible:n.boolean(),kind:n.enum([`outer`,`inner`]),color:Ve,offsetX:ze,offsetY:ze,blur:y,spread:ze}),x=n.object({id:Be,visible:n.boolean()}),Xe=n.discriminatedUnion(`kind`,[x.extend({kind:n.literal(`blur`),value:y}),x.extend({kind:n.literal(`brightness`),value:y}),x.extend({kind:n.literal(`contrast`),value:y}),x.extend({kind:n.literal(`grayscale`),value:b}),x.extend({kind:n.literal(`hue-rotate`),value:ze}),x.extend({kind:n.literal(`invert`),value:b}),x.extend({kind:n.literal(`saturate`),value:y}),x.extend({kind:n.literal(`sepia`),value:b})]),Ze=n.enum([`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`plus-lighter`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`]);n.object({opacity:b,blendMode:Ze,fills:n.array(Ge).max(32),border:qe,outline:Je,radius:Ke,shadows:n.array(Ye).max(32),filters:n.array(Xe).max(32),backdropFilters:n.array(Xe).max(32)});const Qe=n.object({opacity:b.optional(),blendMode:Ze.optional(),fills:n.array(Ge).max(32).optional(),border:qe.optional(),outline:Je.optional(),radius:Ke.optional(),shadows:n.array(Ye).max(32).optional(),filters:n.array(Xe).max(32).optional(),backdropFilters:n.array(Xe).max(32).optional()}).refine(e=>Object.keys(e).length>0,`appearance values cannot be empty`),$e=[`opacity`,`blendMode`,`fills`,`border`,`outline`,`radius`,`shadows`,`filters`,`backdropFilters`],et=n.enum($e),tt=n.object({opacity:b.optional(),blendMode:Ze.optional(),fills:n.array(Ge).max(32).optional(),border:qe.optional(),outline:Je.optional(),radius:Ke.optional(),shadows:n.array(Ye).max(32).optional(),filters:n.array(Xe).max(32).optional(),backdropFilters:n.array(Xe).max(32).optional(),clear:n.array(et).min(1).max($e.length).optional()}).refine(e=>Object.keys(e).length>0,`appearance patch cannot be empty`).refine(({clear:e,...t})=>e===void 0||e.every(e=>t[e]===void 0),`appearance patch cannot set and clear the same property`),nt=n.number().min(-1e5).max(De),rt=n.number().nonnegative().max(De),it=n.object({family:n.string().min(1).max(500),fallbackFamilies:n.array(n.string().min(1).max(500)).max(20),size:rt,weight:n.number().int().min(1).max(1e3),style:n.enum([`normal`,`italic`,`oblique`]),lineHeight:n.discriminatedUnion(`mode`,[n.object({mode:n.literal(`normal`)}),n.object({mode:n.literal(`fixed`),value:rt})]),letterSpacing:nt,align:n.enum([`left`,`center`,`right`,`justify`]),verticalAlign:n.enum([`top`,`middle`,`bottom`]),transform:n.enum([`none`,`uppercase`,`lowercase`,`capitalize`]),decoration:n.object({line:n.enum([`none`,`underline`,`line-through`]),style:n.enum([`solid`,`double`,`dotted`,`dashed`,`wavy`]),color:Ve.optional(),thickness:rt.optional()}),stroke:n.object({width:rt,paint:Ge}).optional(),wrapping:n.enum([`wrap`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]),insets:n.object({top:nt,right:nt,bottom:nt,left:nt}).optional()}),at=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,ot=/^(?:behavior|-moz-binding)$/iu,st=n.string().min(1).max(200).regex(/^(?:--[\w-]+|-(?:webkit|moz|ms|o)-[a-z][a-z\d-]*|[a-z][a-z\d-]*)$/iu).refine(e=>!ot.test(e),`unsafe CSS property`),ct=n.string().max(1e4).refine(e=>!at.test(e),`unsafe CSS value`),lt=n.object({id:n.string().min(1).max(200),property:st,value:ct,enabled:n.boolean()}),ut=n.object({declarations:n.array(lt).max(128)}).refine(({declarations:e})=>new Set(e.map(e=>e.id)).size===e.length,`additional style ids must be unique`),S=n.object({x:n.number(),y:n.number(),width:n.number().nonnegative(),height:n.number().nonnegative()}),dt=n.enum([`start`,`center`,`end`,`stretch`,`scale`]),ft=n.object({x:dt,y:dt}),pt=n.enum([`source`,`generated`,`user`]),mt=n.looseObject({id:n.string().min(1).max(200),label:n.string().max(500),component:n.string().min(1).max(100),labelOrigin:pt.optional(),visible:n.boolean().optional(),locked:n.boolean().optional(),constraints:ft.optional(),styles:n.record(n.string(),n.union([n.string(),n.number()])),layout:Re.optional(),responsive:n.never().optional(),appearance:Qe.optional(),typography:it.optional(),additionalStyles:ut.optional(),props:n.record(n.string(),n.unknown()).optional(),box:S.optional()}),ht=n.object({version:n.literal(2),nodes:n.record(n.string(),mt),relationships:n.record(n.string(),n.object({parentId:n.string().min(1).max(200),sortKey:n.string().min(1).max(500)})),tombstones:n.record(n.string(),n.literal(!0)).default({})}),gt=()=>({version:2,nodes:{root:{id:`root`,label:`Canvas`,component:`root`,labelOrigin:`generated`,visible:!0,locked:!1,styles:{}}},relationships:{},tombstones:{}}),_t=3e4,C=5e4,vt=n.string().min(1).max(200),yt=n.object({code:n.enum([`asset-unavailable`,`content-omitted`,`cross-origin-frame`,`nodes-truncated`,`responsive-behavior-not-editable`,`style-degraded`,`unsupported-surface`]),message:n.string().min(1).max(500),temporaryId:vt.optional()}),bt=n.object({nodeCount:n.number().int().positive().max(_t),sourceNodeCount:n.number().int().positive().max(C).optional(),collapsedNodeCount:n.number().int().nonnegative().max(C).optional(),collapsedWrapperNodeCount:n.number().int().nonnegative().max(C).optional(),collapsedNeutralWrapperNodeCount:n.number().int().nonnegative().max(C).optional(),collapsedTransferredWrapperNodeCount:n.number().int().nonnegative().max(C).optional(),layoutContainerCount:n.number().int().nonnegative().max(_t).optional(),removedLeafNodeCount:n.number().int().nonnegative().max(C).optional(),retainedSemanticOwnerNodeCount:n.number().int().nonnegative().max(C).optional(),truncatedNodeCount:n.number().int().nonnegative().max(C).optional(),issues:n.array(yt).max(C)}).refine(({collapsedNeutralWrapperNodeCount:e,collapsedTransferredWrapperNodeCount:t,collapsedWrapperNodeCount:n})=>n===void 0||e===void 0||t===void 0||e+t===n,`wrapper collapse proof classes must explain the collapsed wrapper count`).refine(({collapsedNodeCount:e,collapsedWrapperNodeCount:t,removedLeafNodeCount:n})=>e===void 0||t===void 0||n===void 0||t+n===e,`collapsed node kinds must explain the total collapsed node count`).refine(({collapsedNodeCount:e,nodeCount:t,sourceNodeCount:n,truncatedNodeCount:r})=>n===void 0||e===void 0||n-t===e+(r??0),`collapsed and truncated node counts must explain the source to editable difference`).refine(({layoutContainerCount:e,nodeCount:t})=>e===void 0||e<=t,`layout container count cannot exceed editable node count`),xt=mt.omit({id:!0}).extend({temporaryId:vt}),St=n.object({temporaryId:vt,parentTemporaryId:vt,sortKey:n.string().min(1).max(500)}),Ct=n.object({version:n.literal(1),rootTemporaryId:vt,nodes:n.array(xt).min(1).max(_t),relationships:n.array(St).max(_t-1),report:bt}),wt=n.object({canvasId:n.uuid(),mutationId:n.uuid(),baseVersion:n.number().int().positive(),screenNodeId:n.string().min(1).max(200),draft:Ct}),Tt=n.object({canvasId:n.uuid(),mutationId:n.uuid(),previousVersion:n.number().int().positive(),version:n.number().int().positive(),rootNodeId:n.string().min(1).max(200),idMap:n.record(vt,n.string().min(1).max(200)),insertedNodeIds:n.array(n.string().min(1).max(200)),removedNodeIds:n.array(n.string().min(1).max(200)),boxes:n.record(n.string().min(1).max(200),S),affectedBounds:S}),w=n.object({url:n.url(),expiresAt:n.iso.datetime(),headers:n.record(n.string(),n.string())}),Et=n.object({url:n.url(),expiresAt:n.iso.datetime(),bytes:n.number().int().min(0)}),Dt=[`queued`,`claimed`,`grant`,`navigate`,`document`,`sources`,`fonts`,`layout`,`target`,`capture`,`serialize`,`compile`,`commit`,`upload`,`complete`],Ot=[`queued`,`running`,`succeeded`,`failed`,`cancelled`,`expired`],kt=[`VERSION_CHANGED`,`TARGET_NOT_FOUND`,`TARGET_INVALID`,`OUTPUT_TOO_LARGE`,`READINESS_TIMEOUT`,`SOURCE_FAILED`,`BROWSER_CRASH`,`CAPTURE_FAILED`,`CONVERSION_FAILED`,`UPLOAD_FAILED`,`WORKER_UNAVAILABLE`,`CANCELLED`,`EXPIRED`,`INTERNAL`],At=[`ASSET_UNAVAILABLE`,`FONT_FALLBACK`,`SOURCE_FALLBACK`,`SCALE_REDUCED`],jt=32*d,Mt=64*d,Nt=1e5,Pt=.1,T=n.object({x:n.number(),y:n.number(),width:n.number().positive().max(Nt),height:n.number().positive().max(Nt)}),Ft=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`content`)}),n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`bounds`),bounds:T})]),It=n.object({kind:n.literal(`recording`),recordingId:n.uuid(),atMs:n.number().int().nonnegative()}),Lt=n.object({kind:n.literal(`recording`),recordingId:n.uuid(),requestedAtMs:n.number().int().nonnegative(),settledAtMs:n.number().int().nonnegative()}),Rt=n.object({recordingId:n.uuid(),atMs:n.number().int().nonnegative(),screenId:n.uuid(),screenNodeId:n.string().min(1).max(200),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()}),box:T,version:n.number().int().positive(),alreadyPresent:n.boolean()}),zt=n.object({canvasId:n.uuid(),expectedVersion:n.number().int().positive().optional(),target:Ft.default({kind:`content`}),sourceState:It.optional(),scale:n.number().min(Pt).max(4).default(1),format:n.literal(`png`).default(`png`)}).refine(e=>e.sourceState===void 0||e.target.kind===`node`,{message:`a source state requires a node render target`,path:[`sourceState`]}),Bt=n.enum(Dt);n.enum(Ot);const Vt=n.enum(kt),Ht=n.enum(At),Ut=n.object({code:Ht,message:n.string().min(1).max(500),sourceId:n.string().min(1).max(200).nullable()}),E=n.object({reason:Vt,phase:Bt,message:n.string().min(1).max(500),retryable:n.boolean(),sourceId:n.string().min(1).max(200).nullable()}),Wt=n.object({phase:Bt,durationMs:n.number().int().min(0)}),Gt=n.object({canvasId:n.uuid(),requestedVersion:n.number().int().positive(),loadedVersion:n.number().int().positive(),target:Ft,sourceState:Lt.optional(),snapshot:Rt.optional(),bounds:T,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive(),contentType:n.literal(`image/png`),bytes:n.number().int().positive().max(jt),warnings:n.array(Ut),timings:n.array(Wt),expiresAt:n.iso.datetime()}).refine(e=>e.width*e.height<=16e6,{message:`render output may contain at most 16000000 pixels`,path:[`width`]}),Kt=n.object({id:n.uuid(),canvasId:n.uuid(),purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),phase:Bt,requestedVersion:n.number().int().positive(),target:Ft,sourceState:It.optional(),scale:n.number().positive(),format:n.literal(`png`),attempt:n.number().int().min(0),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime()}),qt=n.discriminatedUnion(`state`,[Kt.extend({state:n.literal(`queued`),result:n.null(),failure:n.null()}),Kt.extend({state:n.literal(`running`),result:n.null(),failure:n.null()}),Kt.extend({state:n.literal(`succeeded`),phase:n.literal(`complete`),result:Gt,failure:n.null()}),Kt.extend({state:n.literal(`failed`),result:n.null(),failure:E}),Kt.extend({state:n.literal(`cancelled`),result:n.null(),failure:E.extend({reason:n.literal(`CANCELLED`)})}),Kt.extend({state:n.literal(`expired`),result:n.null(),failure:E.extend({reason:n.literal(`EXPIRED`)})})]),Jt=n.object({job:qt,alreadyExists:n.boolean()}),Yt=n.object({jobId:n.uuid()}),Xt=n.object({job:qt}),Zt=n.object({jobId:n.uuid()}),Qt=n.object({job:qt}),$t=n.object({jobId:n.uuid()}),en=n.object({jobId:n.uuid(),download:Et}),tn=n.object({canvasId:n.uuid(),recordingId:n.uuid(),atMs:n.number().int().nonnegative()}),nn=n.object({job:qt,alreadyExists:n.boolean()}),rn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`adjacent`)}),n.object({kind:n.literal(`insert-children`),targetNodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`replace`),targetNodeId:n.string().min(1).max(200)})]),an=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`screen`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`html`),html:n.string().min(1).max(262144),label:n.string().min(1).max(500),idPrefix:n.string().min(1).max(80).regex(/^[\w-]+$/u).optional()})]),on=n.object({source:an,destination:rn}).superRefine((e,t)=>{e.source.kind===`screen`&&e.destination.kind!==`adjacent`&&t.addIssue({code:`custom`,message:`stored screens convert beside their source`,path:[`destination`]}),e.source.kind===`html`&&e.destination.kind===`adjacent`&&t.addIssue({code:`custom`,message:`authored HTML requires an editable destination`,path:[`destination`]})}),sn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`screen`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`html`),label:n.string().min(1).max(500)})]),cn=n.object({id:n.uuid(),canvasId:n.uuid(),source:sn,destination:rn,phase:Bt,requestedVersion:n.number().int().positive(),attempt:n.number().int().nonnegative(),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime()}),ln=n.discriminatedUnion(`state`,[cn.extend({state:n.literal(`queued`),result:n.null(),failure:n.null()}),cn.extend({state:n.literal(`running`),result:n.null(),failure:n.null()}),cn.extend({state:n.literal(`succeeded`),phase:n.literal(`complete`),result:Tt.extend({report:bt}),failure:n.null()}),cn.extend({state:n.literal(`failed`),result:n.null(),failure:E}),cn.extend({state:n.literal(`cancelled`),result:n.null(),failure:E.extend({reason:n.literal(`CANCELLED`)})}),cn.extend({state:n.literal(`expired`),result:n.null(),failure:E.extend({reason:n.literal(`EXPIRED`)})})]),un=on.and(n.object({canvasId:n.uuid(),expectedVersion:n.number().int().positive().optional()})),dn=n.object({job:ln,alreadyExists:n.boolean()}),fn=n.object({jobId:n.uuid()}),pn=n.object({job:ln}),mn=n.object({jobId:n.uuid()}),hn=n.object({job:ln});n.discriminatedUnion(`state`,[n.object({state:n.literal(`loading`),jobId:n.uuid()}),n.object({state:n.literal(`ready`),jobId:n.uuid(),loadedVersion:n.number().int().positive(),draft:Ct}),n.object({state:n.literal(`failed`),jobId:n.uuid(),message:n.string().min(1).max(500)})]);const gn=n.record(n.string(),n.unknown()),_n=n.object({canvasId:n.uuid()}),vn=n.object({screenId:n.uuid(),route:n.string().max(l).nullable(),title:n.string().max(200).nullable(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()}),atMs:n.number().int().min(0).nullable(),sourceRecordingId:n.uuid().nullable(),assetBundle:n.object({assetBundleId:n.uuid(),sourceUrl:n.string().max(l),assets:n.array(n.object({url:n.string().max(l),contentType:n.string().max(200),path:n.string().startsWith(`/v1/recording-assets/`)})),missingAssetCount:n.number().int().min(0)}).nullable(),download:Et.nullable()}),yn=n.object({version:n.number().int().min(1),document:gn,screens:n.array(vn)}),bn=n.object({canvasId:n.uuid(),baseVersion:n.number().int().min(1),document:gn,screenIds:n.array(n.uuid()).max(2e3)}),xn=n.discriminatedUnion(`outcome`,[n.object({outcome:n.literal(`saved`),version:n.number().int().min(1)}),n.object({outcome:n.literal(`conflict`),version:n.number().int().min(1),document:gn})]),Sn=n.object({canvasId:n.uuid(),contentType:n.enum([`image/avif`,`image/gif`,`image/jpeg`,`image/png`,`image/webp`]),bytes:n.number().int().positive().max(20971520)}),Cn=n.object({assetId:n.uuid(),path:n.string().startsWith(`/v1/canvas-assets/`),upload:w}),wn=(e,t)=>`/v1/canvas-assets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,Tn=n.enum([`position`,`layout`,`clip`,`cornerRadius`,`blending`,`typography`,`nativeControl`,`textDecoration`,`fill`,`outline`,`textStroke`,`border`,`outerShadow`,`innerShadow`,`filters`,`additionalStyles`,`vector`,`export`,`source`]),En=n.object({id:n.string().min(1).max(200),label:n.string().max(500),kind:n.string().min(1).max(100),parentId:n.string().min(1).max(200).nullable(),childCount:n.number().int().min(0),box:T.nullable(),propertySections:n.array(Tn)}),Dn=n.object({canvasId:n.uuid()}),On=n.object({canvasId:n.uuid(),title:n.string().min(1),version:n.number().int().positive(),nodeCount:n.number().int().min(0),rootChildCount:n.number().int().min(0),bounds:T.nullable(),kinds:n.record(n.string(),n.number().int().min(0)),next:n.array(n.string().min(1))}),kn=n.object({canvasId:n.uuid()}),An=n.object({canvasId:n.uuid(),version:n.number().int().positive(),nodes:n.array(En)}),jn=n.object({canvasId:n.uuid(),nodeId:n.string().min(1).max(200)}),Mn=n.object({canvasId:n.uuid(),version:n.number().int().positive(),node:En.extend({styles:n.record(n.string(),n.union([n.string(),n.number()])),layout:Re.optional(),appearance:Qe.optional(),typography:it.optional(),additionalStyles:ut.optional(),props:n.record(n.string(),n.unknown()),children:n.array(n.string().min(1).max(200))}),next:n.array(n.string().min(1))}),Nn=[`position`,`layout`,`cornerRadius`,`blending`,`fill`,`outline`,`border`,`outerShadow`,`innerShadow`,`filters`,`additionalStyles`,`export`],Pn=[`position`,`layout`,`clip`,...Nn.filter(e=>e!==`position`&&e!==`layout`)],Fn=[...Nn,`vector`],In=Object.fromEntries([{objectKind:`prototype`,label:`Prototype`,category:`import`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1,commentAnchor:`node`},capture:{preservesHtmlCssAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:[`position`,`layout`]},{objectKind:`root`,label:`Canvas`,category:`container`,capabilities:{canSelect:!1,canContainChildren:!0,canEditProperties:!1},selectionBehavior:{hitTarget:`children`},propertySections:[]},{objectKind:`page`,label:`Page`,category:`container`,capabilities:{canSelect:!1,canContainChildren:!1,canEditProperties:!1},selectionBehavior:{hitTarget:`children`},propertySections:[]},{objectKind:`screen`,label:`Screen`,category:`import`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1,commentAnchor:`screen`},capture:{preservesHtmlCssAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:[`position`,`layout`,`source`]},{objectKind:`frame`,label:`Frame`,category:`container`,capabilities:{canSelect:!0,canContainChildren:!0,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:Pn},{objectKind:`group`,label:`Group`,category:`container`,capabilities:{canSelect:!0,canContainChildren:!0,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:[`position`,`layout`,`blending`,`additionalStyles`,`export`]},{objectKind:`rectangle`,label:`Rectangle`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:Nn},{objectKind:`image`,label:`Image`,category:`media`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,heightFollowsContent:!1},propertySections:Nn},{objectKind:`svg`,label:`SVG`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},capture:{preservesVectorData:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,heightFollowsContent:!1},propertySections:Fn},{objectKind:`recording`,label:`Recording`,category:`media`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1},capture:{preservesAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,heightFollowsContent:!1},propertySections:[]},{objectKind:`text`,label:`Text`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`text`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!0},propertySections:[`position`,`layout`,`typography`,`nativeControl`,`textDecoration`,`textStroke`,`blending`,`fill`,`outerShadow`,`filters`,`additionalStyles`,`export`]}].map(e=>[e.objectKind,e])),Ln=e=>In[e]??null,Rn=e=>Ln(e)?.propertySections??[],zn=n.string().regex(/^(?:\d+(?:\.\d+)?|\.\d+)px$/u),Bn=n.string().regex(/^-?(?:\d+(?:\.\d+)?|\.\d+)px$/u),D={color:n.union([n.enum([`var(--note-ink)`,`var(--note-slate)`,`var(--note-red)`,`var(--note-orange)`,`var(--note-amber)`,`var(--note-green)`,`var(--note-teal)`,`var(--note-blue)`,`var(--note-violet)`,`var(--note-magenta)`]),n.string().regex(/^#[\da-f]{6}$/iu)]),"font-family":n.enum([`var(--sans)`,`var(--mono)`]),"font-size":n.union([n.literal(16),n.literal(24),n.literal(40),n.literal(64),n.literal(96)]),"font-weight":n.enum([`400`,`700`]),"font-style":n.enum([`normal`,`italic`,`oblique`]),"letter-spacing":n.number().min(-100).max(100),"line-height":n.union([n.number().positive().max(1e4),n.string().regex(/^(?:\d+(?:\.\d+)?(?:px|em|rem|%)?|normal)$/u)]),"text-align":n.enum([`left`,`center`,`right`]),"white-space":n.enum([`normal`,`nowrap`,`pre`,`pre-wrap`,`pre-line`,`break-spaces`])},Vn=n.strictObject({color:D.color.optional(),"font-family":D[`font-family`].optional(),"font-size":D[`font-size`].optional(),"font-weight":D[`font-weight`].optional(),"font-style":D[`font-style`].optional(),"letter-spacing":D[`letter-spacing`].optional(),"line-height":D[`line-height`].optional(),"text-align":D[`text-align`].optional(),"white-space":D[`white-space`].optional()}),Hn=n.strictObject({color:D.color.nullable().optional(),"font-family":D[`font-family`].nullable().optional(),"font-size":n.union([v,zn]).nullable().optional(),"font-weight":n.string().regex(/^(?:[1-9]\d{0,2}|1000)$/u).nullable().optional(),"font-style":D[`font-style`].nullable().optional(),"font-stretch":n.union([n.enum([`normal`,`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`]),n.string().regex(/^\d+(?:\.\d+)?%$/u)]).nullable().optional(),"letter-spacing":n.union([_,Bn,n.literal(`normal`)]).nullable().optional(),"line-height":D[`line-height`].nullable().optional(),"text-align":D[`text-align`].nullable().optional(),"text-indent":n.union([_,Bn]).nullable().optional(),"white-space":D[`white-space`].nullable().optional(),"word-spacing":n.union([_,Bn,n.literal(`normal`)]).nullable().optional()}),Un=n.enum([`auto`,`clip`,`hidden`,`scroll`,`visible`]),O=n.union([n.string(),_]),Wn=Hn.extend({background:n.string().nullable().optional(),"background-color":n.string().nullable().optional(),"border-bottom-left-radius":O.optional(),"border-bottom-right-radius":O.optional(),"border-bottom-width":O.optional(),"border-color":n.string().nullable().optional(),"border-left-width":O.optional(),"border-radius":O.nullable().optional(),"border-right-width":O.optional(),"border-style":n.enum([`none`,`solid`,`dashed`,`dotted`]).nullable().optional(),"border-top-left-radius":O.optional(),"border-top-right-radius":O.optional(),"border-top-width":O.optional(),"border-width":O.nullable().optional(),"box-shadow":n.string().nullable().optional(),"column-gap":O.optional(),gap:O.optional(),"margin-bottom":O.optional(),"margin-left":O.optional(),"margin-right":O.optional(),"margin-top":O.optional(),opacity:n.union([n.string(),n.number()]).nullable().optional(),"outline-offset":O.optional(),"outline-width":O.optional(),overflow:Un.nullable().optional(),"overflow-x":Un.nullable().optional(),"overflow-y":Un.nullable().optional(),"padding-bottom":O.optional(),"padding-left":O.optional(),"padding-right":O.optional(),"padding-top":O.optional(),"row-gap":O.optional(),"stroke-width":O.optional()}),Gn=n.object({parentId:n.string().min(1).max(200),sortKey:n.string().min(1).max(500)}),Kn=n.object({op:n.literal(`insertConvertedSubtree`),destination:rn,sourceNodeId:n.string().min(1).max(200).optional(),rootNodeId:n.string().min(1).max(200),nodes:n.record(n.string().min(1).max(200),mt).refine(e=>Object.keys(e).length<=_t),relationships:n.record(n.string().min(1).max(200),Gn).refine(e=>Object.keys(e).length<_t)}),qn=1e5,Jn=1e3,k=n.string().min(1).max(200),Yn=n.string().min(1).max(500),Xn=S.extend({width:n.number().positive(),height:n.number().positive()}),Zn=n.object({parentId:k,afterId:k.optional()}),Qn=n.object({parentId:k,sortKey:Yn}),$n=n.discriminatedUnion(`op`,[Kn,n.object({op:n.literal(`insertNode`),node:mt,parentage:Qn}),Zn.extend({op:n.literal(`insertText`),nodeId:k,label:n.string().max(500).default(`Text`),text:n.string().max(qn),box:Xn,styles:Vn.default({})}),Zn.extend({op:n.literal(`insertPrototype`),nodeId:k,label:n.string().max(500).default(`Prototype`),prototypeId:n.uuid(),deploymentId:n.uuid(),box:Xn}),n.object({op:n.literal(`setPrototypeDeployment`),nodeId:k,prototypeId:n.uuid(),deploymentId:n.uuid()}),n.object({op:n.literal(`setText`),nodeId:k,text:n.string().max(qn)}),n.object({op:n.literal(`setBox`),nodeId:k,box:S}),n.object({op:n.literal(`setLabel`),nodeId:k,label:n.string().trim().min(1).max(500),labelOrigin:pt.optional()}),n.object({op:n.literal(`setVisibility`),nodeId:k,visible:n.boolean()}),n.object({op:n.literal(`setLocked`),nodeId:k,locked:n.boolean()}),n.object({op:n.literal(`setConstraints`),nodeId:k,constraints:ft}),n.object({op:n.literal(`setStyles`),nodeId:k,styles:Wn}),n.object({op:n.literal(`setAppearance`),nodeId:k,appearance:tt}),n.object({op:n.literal(`setLayout`),nodeId:k,layout:n.union([Re,n.literal(`default`)])}),n.object({op:n.literal(`setTypography`),nodeId:k,typography:n.union([it,n.literal(`default`)])}),n.object({op:n.literal(`setAdditionalStyles`),nodeId:k,additionalStyles:n.union([ut,n.literal(`default`)])}),n.object({op:n.literal(`setProps`),nodeId:k,props:n.record(n.string(),n.unknown())}),n.object({op:n.literal(`setParentage`),nodeId:k,parentage:Qn}),Zn.extend({op:n.literal(`move`),nodeId:k}),n.object({op:n.literal(`remove`),nodeId:k})]),er=n.object({canvasId:n.uuid(),mutationId:n.uuid(),baseVersion:n.number().int().positive(),operations:n.array($n).min(1).max(Jn)}),tr=n.object({canvasId:n.uuid(),mutationId:n.uuid(),previousVersion:n.number().int().positive(),version:n.number().int().positive(),insertedNodeIds:n.array(k),changedNodeIds:n.array(k),removedNodeIds:n.array(k),boxes:n.record(k,S),affectedBounds:Xn.nullable(),next:n.array(n.string().min(1))}),nr=Tt.extend({operation:Kn,next:n.array(n.string().min(1))}),rr=`enhance3.canvas.v1`,ir=n.enum([`blue`,`violet`,`green`,`amber`,`magenta`,`teal`,`red`,`orange`]),ar=n.object({kind:n.literal(`person`),connectionId:n.uuid(),personId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),colour:ir}),or=n.object({kind:n.literal(`guest`),connectionId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),colour:ir}),sr=n.discriminatedUnion(`kind`,[ar,or]),cr=n.object({kind:n.literal(`agent`),personId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),tokenLabel:n.string().min(1).max(100),colour:ir}),lr=n.discriminatedUnion(`kind`,[ar.omit({connectionId:!0}),cr]),ur=n.object({x:n.number(),y:n.number()}),dr=S.extend({width:n.number().positive(),height:n.number().positive()}),fr=n.object({kind:n.enum([`drag`,`resize`]),baseVersion:n.number().int().positive(),boxes:n.record(n.string().min(1).max(200),dr)}),pr=n.object({cursor:ur.nullable().optional(),input:n.enum([`pointer`,`touch`,`keyboard`]).optional(),focused:n.boolean().optional(),selectedNodeIds:n.array(n.string().min(1).max(200)).max(100).optional(),visibleWorldBox:dr.optional(),gesture:fr.nullable().optional(),cursorChat:n.string().max(140).nullable().optional()}).refine(e=>Object.keys(e).length>0,`presence patch cannot be empty`),mr=n.object({actor:sr,seq:n.number().int().nonnegative(),cursor:ur.nullable(),input:n.enum([`pointer`,`touch`,`keyboard`]),focused:n.boolean(),selectedNodeIds:n.array(n.string().min(1).max(200)).max(100),visibleWorldBox:dr.nullable(),gesture:fr.nullable(),cursorChat:n.string().max(140).nullable().default(null),expiresAt:n.iso.datetime()}),hr=n.enum([`reading`,`writing`,`creating`,`deleting`,`rendering`]),gr=n.object({activityId:n.uuid(),canvasId:n.uuid(),actor:cr,phase:hr,nodeIds:n.array(n.string().min(1).max(200)).max(100),bounds:dr.nullable(),expiresAt:n.iso.datetime()}),_r=n.object({canvasId:n.uuid(),protocols:n.array(n.literal(rr)).min(1).max(1)}),vr=n.object({endpoint:n.url(),ticket:n.string().min(1).max(4096),protocol:n.literal(rr),expiresAt:n.iso.datetime()}),yr=n.object({canvasId:n.uuid(),phase:hr,nodeIds:n.array(n.string().min(1).max(200)).max(100).default([]),bounds:dr.nullable().default(null)}),br=n.object({activityId:n.uuid(),expiresAt:n.iso.datetime(),renewAfterMs:n.number().int().positive()}),xr=yr.extend({activityId:n.uuid()}),Sr=n.object({canvasId:n.uuid(),activityId:n.uuid()}),Cr=n.object({ended:n.literal(!0)});n.discriminatedUnion(`type`,[n.object({v:n.literal(1),type:n.literal(`presence.patch`),seq:n.number().int().nonnegative(),payload:pr}),n.object({v:n.literal(1),type:n.literal(`room.pong`),seq:n.number().int().nonnegative(),payload:n.object({pingId:n.uuid()})})]);const A={v:n.literal(1),seq:n.number().int().nonnegative()};n.discriminatedUnion(`type`,[n.object({...A,type:n.literal(`room.snapshot`),payload:n.object({connectionId:n.uuid(),peers:n.array(mr),activities:n.array(gr),documentVersion:n.number().int().positive()})}),n.object({...A,type:n.literal(`presence.patch`),payload:mr}),n.object({...A,type:n.literal(`presence.left`),payload:n.object({connectionId:n.uuid()})}),n.object({...A,type:n.literal(`agent.activity`),payload:n.object({activityId:n.uuid(),activity:gr.nullable()})}),n.object({...A,type:n.literal(`document.committed`),payload:n.object({mutationId:n.uuid(),actor:lr,previousVersion:n.number().int().positive(),version:n.number().int().positive(),operations:n.array($n).min(1)})}),n.object({...A,type:n.literal(`sync.required`),payload:n.object({version:n.number().int().positive(),reason:n.enum([`gap`,`relay`,`replace`,`history-restored`])})}),n.object({...A,type:n.literal(`room.ping`),payload:n.object({pingId:n.uuid(),sentAt:n.iso.datetime()})}),n.object({...A,type:n.literal(`room.error`),payload:n.object({code:n.enum([`auth`,`permission`,`protocol`,`payload`,`rate`,`unavailable`]),message:n.string().min(1).max(200)})})]);const wr=n.object({jobId:n.uuid()}),Tr=n.object({jobId:n.uuid(),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),target:Ft,sourceState:It.optional()}),Er=n.discriminatedUnion(`purpose`,[Tr.extend({purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),scale:n.number().positive().max(4),format:n.literal(`png`)}),Tr.extend({purpose:n.literal(`conversion`),target:n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),sourceState:n.undefined().optional(),conversion:on,scale:n.literal(1),format:n.literal(`json`)})]);n.object({jobId:n.uuid()}),n.object({jobId:n.uuid()});const Dr=n.object({jobId:n.uuid(),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),grantToken:n.string().startsWith(`rgr_`).min(40).max(100),grantCookieName:n.string().min(1).max(100),renderUrl:n.url(),releaseIdentity:n.string().min(1).max(100)});n.discriminatedUnion(`purpose`,[Dr.extend({purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),target:Ft,sourceState:It.optional(),scale:n.number().positive(),outputKey:n.string().min(1).max(500)}),Dr.extend({purpose:n.literal(`conversion`),target:n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),sourceState:n.undefined().optional(),conversion:on,scale:n.literal(1)})]),n.object({jobId:n.uuid(),loadedVersion:n.number().int().positive(),bounds:T,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive(),bytes:n.number().int().positive().max(jt),storageKey:n.string().min(1).max(500),warnings:n.array(Ut),timings:n.array(Wt),sourceState:Lt.optional(),snapshot:n.object({artifactBytes:n.number().int().positive().max(Mt),artifactStorageKey:n.string().min(1).max(500),route:n.string().optional(),title:n.string().optional(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()})}).optional()}),n.object({accepted:n.literal(!0)}),n.object({jobId:n.uuid(),loadedVersion:n.number().int().positive(),draft:Ct}),n.object({accepted:n.literal(!0)}),n.object({recordingId:n.uuid(),requestedAtMs:n.number().int().nonnegative(),settledAtMs:n.number().int().nonnegative(),artifact:n.string().min(1).max(Mt),route:n.string().optional(),title:n.string().optional(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()})}),n.object({jobId:n.uuid(),failure:E}),n.object({accepted:n.literal(!0),willRetry:n.boolean()}),n.object({workerId:n.string().regex(/^[\w.-]+$/u).min(1).max(100),releaseIdentity:n.string().min(1).max(100),timestamp:n.coerce.number().int().nonnegative(),nonce:n.uuid(),mac:n.base64().min(32).max(200)});const Or=n.object({total:n.number().int().nonnegative(),loading:n.number().int().nonnegative(),unavailable:n.number().int().nonnegative()}),kr=n.object({jobId:n.uuid(),canvasId:n.uuid().nullable(),requestedVersion:n.number().int().positive().nullable(),loadedVersion:n.number().int().positive().nullable(),phase:Bt.exclude([`queued`,`claimed`,`capture`,`upload`,`complete`]),sources:Or,warnings:n.array(Ut),timings:n.array(Wt),sourceState:Lt.optional()}),Ar=n.object({selector:n.string().min(1).max(500),contentSelector:n.string().min(1).max(500).optional(),bounds:T,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive()});n.discriminatedUnion(`state`,[kr.extend({state:n.literal(`loading`),capture:n.null(),failure:n.null()}),kr.extend({state:n.literal(`ready`),phase:n.literal(`target`),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),loadedVersion:n.number().int().positive(),capture:Ar,failure:n.null()}),kr.extend({state:n.literal(`failed`),failure:n.object({reason:Vt,message:n.string().min(1).max(500),sourceId:n.string().min(1).max(200).nullable()}),capture:n.null()})]);const jr=n.string().min(1).max(200),Mr=n.object({canvasId:n.uuid()}),Nr=n.object({canvasId:n.uuid(),status:n.enum([`selected`,`none`,`offline`,`stale`]),documentVersion:n.number().int().positive(),selectionRevision:n.number().int().positive().nullable(),selectionChangedAt:n.iso.datetime().nullable(),selectedNodeIds:n.array(jr),missingNodeIds:n.array(jr),nodes:n.array(En),contextRootId:jr.nullable(),visibleWorldBox:T.nullable(),next:n.array(n.string().min(1)).max(12)}),Pr=1e3,Fr=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`person`),personId:n.uuid(),displayName:n.string().min(1).max(200),initials:n.string().min(1).max(2)}),n.object({kind:n.literal(`agent`),personId:n.uuid(),displayName:n.string().min(1).max(200),initials:n.string().min(1).max(2),tokenLabel:n.string().min(1).max(200)})]),Ir=n.object({id:n.uuid(),canvasId:n.uuid(),documentVersion:n.number().int().positive(),origin:n.enum([`automatic`,`manual`,`restore`]),restoreRole:n.enum([`before`,`result`]).nullable(),retention:n.enum([`automatic`,`named`,`restore-boundary`]),title:n.string().min(1).max(200).nullable(),description:n.string().max(Pr).nullable(),actor:Fr,sourceVersionEntryId:n.uuid().nullable(),expiresAt:n.iso.datetime().nullable(),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime(),screenCount:n.number().int().min(0)}),Lr=n.object({canvasId:n.uuid(),limit:n.number().int().min(1).max(100).default(50),cursor:n.string().min(1).max(1e3).optional(),includeAutomatic:n.boolean().default(!1),actor:n.enum([`all`,`mine`]).default(`all`)}),Rr=n.object({current:n.object({documentVersion:n.number().int().positive(),updatedAt:n.iso.datetime()}),items:n.array(Ir),nextCursor:n.string().min(1).nullable(),hasExpiredHistory:n.boolean()}),zr=n.object({canvasId:n.uuid(),versionId:n.uuid()}),Br=n.object({outcome:n.literal(`ready`),entry:Ir,document:gn,screens:n.array(vn)}),Vr=n.object({outcome:n.literal(`missing-resources`),entry:Ir,document:gn,screens:n.array(vn),missingScreenIds:n.array(n.uuid()).min(1)}),Hr=n.discriminatedUnion(`outcome`,[Br,Vr,n.object({outcome:n.literal(`corrupt`),entry:Ir})]),Ur=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`current`),expectedVersion:n.number().int().positive()}),n.object({kind:n.literal(`version`),versionId:n.uuid()})]),Wr=n.object({canvasId:n.uuid(),target:Ur,title:n.string().trim().min(1).max(200),description:n.string().trim().max(Pr).nullable().default(null)}),Gr=n.object({canvasId:n.uuid(),versionId:n.uuid(),title:n.string().trim().min(1).max(200),description:n.string().trim().max(Pr).nullable().default(null)}),Kr=n.object({canvasId:n.uuid(),versionId:n.uuid()}),qr=n.object({entry:Ir}),Jr=n.object({canvasId:n.uuid(),versionId:n.uuid(),expectedVersion:n.number().int().positive()}),Yr=n.object({canvasId:n.uuid(),version:n.number().int().positive(),beforeVersionId:n.uuid(),restoredVersionId:n.uuid(),restoreFenceVersion:n.number().int().positive()}),Xr=n.object({canvasId:n.uuid(),versionId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)]),title:n.string().trim().min(1).max(200).optional()}),Zr=n.object({canvasId:n.uuid(),title:n.string().min(1).max(200),version:n.literal(1)}),Qr=n.object({inviteId:n.uuid(),email:n.string().max(254),accessLevel:m,sendCount:n.number().int().min(1),lastSentAt:n.iso.datetime(),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`expired`]),deliveryState:n.enum([`queued`,`accepted`,`failed`]),deliveryError:n.string()}),$r=n.object({canvasTitle:n.string().min(1),invitedBy:n.string().min(1),email:n.string().max(254).pipe(n.email()),accessLevel:m,expiresAt:n.iso.datetime(),state:n.enum([`pending`,`accepted`]),hasAccount:n.boolean()}),ei=n.object({canvasId:n.uuid(),email:n.string().max(254).transform(e=>e.trim().toLowerCase()).pipe(n.email()),accessLevel:m}),ti=n.object({invite:Qr,acceptToken:n.string().max(512).optional()}),ni=n.object({canvasId:n.uuid()}),ri=f(Qr),ii=n.object({canvasId:n.uuid(),inviteId:n.uuid()}),ai=n.object({canvasId:n.uuid(),inviteId:n.uuid()}),oi=n.string().min(1).max(512),si=n.object({token:oi}),ci=n.object({token:oi}),li=n.object({canvasId:n.uuid(),accessLevel:m}),ui=n.object({personId:n.uuid().nullable(),email:n.string().max(254).nullable(),displayName:n.string().max(120).nullable(),initials:n.string().max(4).nullable(),avatarUrl:n.string().max(l).nullable(),accessLevel:p,isPending:n.boolean(),reviewState:n.enum([`not-started`,`in-progress`,`done`]).nullable(),lastViewedAt:n.iso.datetime().nullable()}),di=n.object({canvasId:n.uuid()}),fi=f(ui),pi=n.object({canvasId:n.uuid(),personId:n.uuid(),accessLevel:m}),mi=n.object({canvasId:n.uuid(),personId:n.uuid()}),hi=n.object({personId:n.uuid(),revoked:n.boolean()}),gi=n.object({canvasId:n.uuid(),reviewState:n.enum([`not-started`,`in-progress`,`done`])}),_i=n.object({reviewState:gi.shape.reviewState.nullable()}),vi=n.object({selector:n.string().min(1).max(2e3),tagName:n.string().min(1).max(40),label:n.string().max(80).nullable(),source:n.object({file:n.string().min(1).max(1024),line:n.number().int().min(0).nullable()}).nullable()}),yi=n.object({x:n.number(),y:n.number()}),bi=n.object({x:n.number().min(0).max(1),y:n.number().min(0).max(1)}),xi=n.object({x:n.number().min(0).max(1),y:n.number().min(0).max(1),width:n.number().min(0).max(1),height:n.number().min(0).max(1)}),Si=vi.extend({role:n.string().min(1).max(80).optional()}),Ci=n.object({path:n.array(n.number().int().min(0)).max(64),offset:n.number().int().min(0)}),wi=n.discriminatedUnion(`kind`,[n.object({version:n.literal(1),kind:n.literal(`element`),locator:Si,attachment:bi,fallbackBounds:xi}),n.object({version:n.literal(1),kind:n.literal(`text`),root:Si,quote:n.object({exact:n.string().min(1).max(1e3),prefix:n.string().max(120),suffix:n.string().max(120)}),range:n.object({start:Ci,end:Ci}),attachment:bi,fallbackBounds:xi}),n.object({version:n.literal(1),kind:n.literal(`elements`),members:n.array(Si).min(2).max(32),truncated:n.boolean(),attachment:bi,fallbackBounds:xi}),n.object({version:n.literal(1),kind:n.literal(`area`),bounds:xi,attachment:bi})]),Ti=n.discriminatedUnion(`on`,[n.object({on:n.literal(`canvas`),point:yi}),n.object({on:n.literal(`node`),nodeId:n.string().min(1).max(120),point:yi,element:n.null()}),n.object({on:n.literal(`screen`),nodeId:n.string().min(1).max(120),screenId:n.uuid(),point:yi,element:vi.nullable(),target:wi.optional()})]),Ei=n.object({kind:n.enum([`person`,`agent`]),personId:n.uuid(),name:n.string().min(1).max(120),initials:n.string().min(1).max(4),avatarUrl:n.string().max(l).nullable(),tokenLabel:n.string().max(120).nullable()}),Di=n.object({personId:n.uuid(),name:n.string().min(1).max(120)}),Oi=n.object({emoji:n.string().min(1).max(16),people:n.array(Di).min(1)}),ki=n.object({messageId:n.uuid(),seq:n.number().int().min(1),body:n.string().min(1),author:Ei,createdAt:n.iso.datetime(),editedAt:n.iso.datetime().nullable(),mentions:n.array(Di),reactions:n.array(Oi)}),Ai=n.object({kind:n.enum([`person`,`agent`]),personId:n.uuid(),name:n.string().min(1).max(120),tokenLabel:n.string().max(120).nullable()}),j=n.object({threadId:n.uuid(),canvasId:n.uuid(),anchor:Ti,author:Ei,messages:n.array(ki).min(1).max(50),messageCount:n.number().int().min(1),hasMoreMessages:n.boolean(),isResolved:n.boolean(),resolvedAt:n.iso.datetime().nullable(),resolvedBy:Ai.nullable(),createdAt:n.iso.datetime(),lastMessageAt:n.iso.datetime()}),ji=n.object({canvasId:n.uuid(),filter:n.enum([`open`,`resolved`,`all`]).default(`open`),authorPersonId:n.uuid().optional(),agentActionable:n.boolean().default(!1),query:n.string().trim().max(200).optional()}),Mi=f(j),Ni=n.object({canvasId:n.uuid(),clientThreadId:n.uuid(),anchor:Ti,body:n.string().trim().min(1).max(ee),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),Pi=n.object({canvasId:n.uuid(),threadId:n.uuid(),clientMessageId:n.uuid(),body:n.string().trim().min(1).max(ee),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),Fi=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid(),body:n.string().trim().min(1).max(ee),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),Ii=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid(),emoji:n.string().trim().min(1).max(16),reacted:n.boolean()}),Li=n.object({canvasId:n.uuid(),threadId:n.uuid(),anchor:Ti}),Ri=n.object({canvasId:n.uuid(),threadId:n.uuid(),resolved:n.boolean()}),zi=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid().optional()}),Bi=n.object({deletedThreadIds:n.array(n.uuid()),deletedMessageIds:n.array(n.uuid())}),Vi=n.enum([`owner`,`admin`,`member`]),Hi=n.object({id:n.uuid(),name:n.string().min(1).max(120),role:Vi}),Ui=n.object({}),Wi=f(Hi),Gi=n.object({name:n.string().trim().min(1).max(120)}),Ki=n.object({organisation:Hi}),qi=n.object({organisationId:n.uuid(),name:n.string().trim().min(1).max(120)}),Ji=n.object({organisationId:n.uuid()}),Yi=n.object({organisationId:n.uuid(),movedCanvasCount:n.number().int().min(0)}),Xi=n.object({personId:n.uuid(),displayName:n.string().max(120),initials:n.string().max(4),email:n.string().max(254).nullable(),role:Vi}),Zi=n.object({organisationId:n.uuid()}),Qi=f(Xi),$i=n.object({organisationId:n.uuid(),email:n.email().trim().toLowerCase().max(254),role:n.enum([`admin`,`member`]).default(`member`)}),ea=n.object({personId:n.uuid()}),ta=n.object({organisationId:n.uuid(),personId:n.uuid(),role:n.enum([`admin`,`member`])}),na=ta.pick({personId:!0,role:!0}),ra=n.object({organisationId:n.uuid(),personId:n.uuid()}),ia=n.object({personId:n.uuid(),removed:n.literal(!0)}),aa=n.object({organisationId:n.uuid(),personId:n.uuid()}),oa=n.object({ownerPersonId:n.uuid()}),sa=n.object({inviteId:n.uuid(),email:n.string().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]),sendCount:n.number().int().min(1),lastSentAt:n.iso.datetime(),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`expired`]),deliveryState:n.enum([`queued`,`accepted`,`failed`]),deliveryError:n.string()}),ca=n.object({organisationId:n.uuid(),email:n.string().trim().toLowerCase().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]).default(`member`)}),la=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`member`),personId:n.uuid()}),n.object({kind:n.literal(`invitation`),invite:sa})]),ua=n.object({invite:sa}),da=n.object({organisationId:n.uuid()}),fa=f(sa),pa=n.object({organisationId:n.uuid(),inviteId:n.uuid()}),ma=pa.extend({}),ha=n.string().min(1).max(512),ga=n.object({token:ha}),_a=n.object({token:ha}),va=n.object({teamName:n.string().min(1).max(120),invitedBy:n.string().min(1).max(120),email:n.string().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`accepted`]),hasAccount:n.boolean()}),ya=n.object({organisationId:n.uuid()}),ba=n.object({id:n.uuid(),label:n.string().min(1).max(120),createdAt:n.iso.datetime(),lastUsedAt:n.iso.datetime().nullable(),expiresAt:n.iso.datetime().nullable(),revoked:n.boolean()}),xa=n.object({label:n.string().trim().min(1).max(120).describe(`Label naming the agent.`),expiresAt:n.iso.datetime().nullable().describe(`Expiry timestamp, or null for a token that does not expire.`)}),Sa=n.object({token:n.string().startsWith(`enh_`),agentToken:ba}),Ca=n.object({}),wa=n.object({items:n.array(ba)}),Ta=n.object({tokenId:n.uuid()}),Ea=n.object({tokenId:n.uuid(),revoked:n.literal(!0)}),Da=n.discriminatedUnion(`method`,[n.object({method:n.literal(`token`)}),n.object({method:n.literal(`browser`),issuer:n.url(),clientId:n.string().min(1),scope:n.literal(`openid`)})]),Oa=n.object({id:n.uuid(),preparedCanvasId:n.uuid(),displayName:n.string().min(1).max(120),initials:n.string().min(1).max(4),avatarUrl:n.string().max(l).nullable(),email:n.string().max(254).nullable(),createdAt:n.iso.datetime()}),ka=n.object({}),Aa=n.object({person:Oa.nullable(),authentication:n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`anonymous`)}),n.object({kind:n.literal(`person`)}),n.object({kind:n.literal(`agent`),tokenId:n.uuid(),tokenLabel:n.string(),expiresAt:n.iso.datetime().nullable()}),n.object({kind:n.literal(`oauth-agent`),tokenId:n.uuid(),tokenLabel:n.string(),clientId:n.string().min(1),scopes:n.array(n.string()),expiresAt:n.iso.datetime(),resource:n.url()})])}),ja=n.object({displayName:n.string().trim().min(1).max(120)}),Ma=n.object({person:Oa}),Na=n.string().trim().toLowerCase().min(3).max(40).regex(/^[a-z0-9][a-z0-9._-]*$/,`letters, digits, dot, underscore and dash only`),Pa=n.enum([`cookie`,`token`]).default(`cookie`),Fa=n.object({username:Na,password:n.string().min(10).max(200),displayName:n.string().trim().min(1).max(120),deliver:Pa,email:n.string().max(254).transform(e=>e.trim().toLowerCase()).pipe(n.email())}),Ia=n.object({username:Na,password:n.string().min(1).max(200),deliver:Pa}),La=n.object({person:Oa,token:n.string().nullable()}),Ra=La.extend({preparedCanvasId:n.uuid()}),za=n.object({}),Ba=n.object({signedOut:n.literal(!0)}),Va=n.string().max(254).pipe(n.email()),Ha=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`person`),personId:n.uuid(),displayName:n.string().min(1).max(120),initials:n.string().min(1).max(4),email:Va}),n.object({kind:n.literal(`email`),email:Va})]),Ua=n.object({query:n.string().trim().min(1).max(200)}),Wa=n.object({recipients:n.array(Ha).max(5)}),Ga=n.object({}),Ka=Wa.extend({}),qa=`enhance3:session-handoff`;n.union([n.object({kind:n.literal(qa),body:n.object({token:n.string().min(1),displayName:n.string().min(1)})}),n.object({kind:n.literal(qa),signedOut:n.literal(!0)})]);const Ja=n.string().min(1).max(500).refine(e=>!e.startsWith(`/`)&&!e.endsWith(`/`)&&!e.includes(`\\`)&&!e.includes(`\0`)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{message:`prototype paths must be portable relative file paths`}),Ya=n.object({path:Ja,contentType:n.string().min(1).max(200),bytes:n.number().int().nonnegative().max(26214400)}),Xa=n.enum([`uploading`,`verifying`,`ready`,`failed`,`abandoned`]),Za=n.object({canvasId:n.uuid(),prototypeId:n.uuid().optional(),clientToken:n.uuid(),nodeId:n.string().min(1).max(200),title:n.string().trim().min(1).max(200),entryPath:Ja.default(`index.html`),files:n.array(Ya).min(1).max(2e3),box:S.extend({width:n.number().positive(),height:n.number().positive()})}),Qa=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1).max(200),state:Xa,alreadyExists:n.boolean(),fileCount:n.number().int().positive(),totalBytes:n.number().int().positive().max(262144e3)}),$a=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),cursor:n.number().int().min(0).default(0)}),eo=n.object({path:Ja,upload:w}),to=n.object({deploymentId:n.uuid(),uploads:n.array(eo).max(50),nextCursor:n.number().int().min(0).optional()}),no=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),baseVersion:n.number().int().positive()}),ro=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1).max(200),version:n.number().int().positive(),state:n.literal(`ready`),origin:n.url(),openUrl:n.string().startsWith(`/c/`)}),io=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid()}),ao=n.object({deploymentId:n.uuid(),origin:n.url(),bootUrl:n.url(),expiresAt:n.iso.datetime()}),oo=`__enhance/manifest.json`,so=n.string().length(64).refine(e=>{for(let t of e)if(!/[\da-f]/u.test(t))return!1;return!0}),co=e=>{for(let t of e){let e=t.codePointAt(0);if(e!==void 0&&(e===127||e<=31))return!0}return!1},lo=e=>e.normalize(`NFKC`).toUpperCase().toLowerCase(),uo=n.string().min(1).refine(e=>e===e.normalize(`NFC`),{message:`prototype paths must use NFC Unicode normalization`}).refine(e=>!e.startsWith(`/`)&&!/^[A-Za-z]:\//u.test(e)&&!e.endsWith(`/`)&&!e.includes(`\\`)&&!co(e)&&!e.startsWith(`__enhance/`)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{message:`prototype paths must be portable relative file paths`}),fo=n.object({path:uo,contentType:n.string().trim().min(1).max(200).refine(e=>!co(e)),bytes:n.number().int().nonnegative().max(2**53-1),sha256:so}),po=n.object({version:n.literal(1),entryPath:uo,files:n.array(fo).min(1)}),mo=n.object({artifactBytes:n.number().int().positive().max(2**53-1),expandedBytes:n.number().int().positive().max(2**53-1),fileBytes:n.number().int().positive().max(2**53-1),manifestBytes:n.number().int().positive().max(2**53-1),fileCount:n.number().int().positive().max(2**53-1),pathBytes:n.number().int().positive().max(2**53-1)}),ho=n.object({}),go=n.object({protocolVersion:n.literal(1),format:n.literal(`zip`),limits:mo}),_o=n.object({protocolVersion:n.literal(1),format:n.literal(`zip`),bytes:n.number().int().positive().max(2**53-1),sha256:so,fileCount:n.number().int().positive().max(2**53-1),expandedBytes:n.number().int().positive().max(2**53-1)}),vo=n.object({canvasId:n.uuid(),prototypeId:n.uuid().optional(),clientToken:n.uuid(),nodeId:n.string().min(1),title:n.string().trim().min(1).max(200),entryPath:uo,artifact:_o,box:S.extend({width:n.number().positive(),height:n.number().positive()})}),yo=n.enum([`uploading`,`queued`,`ingesting`,`ready`,`failed`,`abandoned`]),bo=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),alreadyExists:n.boolean(),artifact:_o}),xo=n.discriminatedUnion(`state`,[bo.extend({state:n.literal(`uploading`),upload:w}),bo.extend({state:n.enum([`queued`,`ingesting`,`ready`,`failed`,`abandoned`])})]),So=n.object({canvasId:n.uuid(),deploymentId:n.uuid()}),Co=n.object({deploymentId:n.uuid(),state:yo}),wo=n.object(So.shape),To=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),fileCount:n.number().int().nonnegative(),totalBytes:n.number().int().nonnegative().max(2**53-1),processedFiles:n.number().int().nonnegative()}),Eo=n.discriminatedUnion(`state`,[To.extend({state:n.literal(`failed`),failure:n.object({code:n.string().min(1),message:n.string().min(1),path:uo.optional()})}),To.extend({state:n.enum([`uploading`,`queued`,`ingesting`,`ready`,`abandoned`])})]),Do=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),baseVersion:n.number().int().positive()}),Oo=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),version:n.number().int().positive(),state:n.literal(`ready`),origin:n.url(),openUrl:n.string().startsWith(`/c/`)});n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.capture`),requestId:n.uuid()}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.ready`)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.escape`)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.zoom`),deltaX:n.number(),deltaY:n.number(),deltaMode:n.union([n.literal(0),n.literal(1),n.literal(2)]),anchorX:n.number().min(0).max(1),anchorY:n.number().min(0).max(1)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.navigate`),direction:n.enum([`back`,`forward`])}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.navigation`),canGoBack:n.boolean(),canGoForward:n.boolean()});const ko=n.object({artifact:n.string().min(1),viewport:n.object({width:n.number().positive(),height:n.number().positive()}),title:n.string()}),Ao=n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.captured`),requestId:n.uuid()});n.discriminatedUnion(`outcome`,[Ao.extend({outcome:n.literal(`captured`),screen:ko}),Ao.extend({outcome:n.literal(`failed`),error:n.string().min(1)})]);const jo=2166136261,Mo=Number.parseInt(`9e3779b9`,16),No=Number.parseInt(`85ebca6b`,16),Po=Number.parseInt(`c2b2ae35`,16);jo^Mo,jo^No,jo^Po;const Fo=n.object({width:n.number().int().positive(),height:n.number().int().positive()}),Io=16*d,Lo=8*d,Ro=l,zo=n.object({mimeType:n.string().min(1).max(100),sampleRate:n.number().int().min(8e3).max(192e3)}),Bo=n.object({sourceUrl:n.string().max(Ro),viewport:Fo,pageTitle:n.string().max(200).nullable(),audio:zo.nullable().default(null)}),Vo=n.object({recordingId:n.uuid(),ownerPersonId:n.uuid(),chunkIndex:n.literal(0),upload:w,audioUpload:w.nullable()}),Ho=n.object({recordingId:n.uuid(),index:n.number().int().min(0),firstEventMs:n.number().int().min(0),lastEventMs:n.number().int().min(0),eventCount:n.number().int().min(0),continues:n.boolean().default(!1),bytes:n.number().int().min(1).max(Io),etag:n.string().min(1).max(200).optional()}),Uo=n.object({nextChunkIndex:n.number().int().min(1),upload:w}),Wo=n.object({recordingId:n.uuid(),index:n.number().int().min(0),firstMs:n.number().int().min(0),lastMs:n.number().int().min(0),bytes:n.number().int().min(1).max(Io),epoch:n.number().int().min(0).default(0),startsEpoch:n.boolean().default(!1),etag:n.string().min(1).max(200).optional()}),Go=n.object({nextChunkIndex:n.number().int().min(1),upload:w}),Ko=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0).max(144e5),viewport:Fo,sourceUrl:n.string().max(Ro),interrupted:n.boolean().default(!1),canvasId:n.uuid().optional(),organisationId:n.uuid().optional(),audioChunkCount:n.number().int().min(0).default(0),hasRecoverableBytes:n.boolean().default(!1)}).refine(e=>e.canvasId===void 0||e.organisationId===void 0,{message:`choose an existing canvas or a team for a new canvas, not both`}),qo=n.enum([`whole`,`recovering`,`partial`]),Jo=n.enum([`dom`,`audio`]),Yo=n.object({recordingId:n.uuid(),canvasId:n.uuid(),canvasTitle:n.string().min(1).max(200),isNewCanvas:n.boolean(),storedChunkCount:n.number().int().min(0),missingChunkIndexes:n.array(n.number().int().min(0)).max(64),missingChunkCount:n.number().int().min(0),storedAudioChunkCount:n.number().int().min(0),missingAudioChunkIndexes:n.array(n.number().int().min(0)).max(64),missingAudioChunkCount:n.number().int().min(0),integrity:qo}),Xo=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0),viewport:Fo,interrupted:n.boolean(),chunkCount:n.number().int().min(0),startedAt:n.iso.datetime()}),Zo=n.object({recordingId:n.uuid(),assets:n.array(n.object({url:n.url().max(Ro),contentType:n.string().min(1).max(200),byteSize:n.number().int().min(1).max(Lo)})).max(400)}),Qo=n.object({reserved:n.array(n.object({url:n.string(),upload:w}))}),$o=n.object({recordingId:n.uuid(),arrived:n.array(n.object({url:n.url().max(Ro),etag:n.string().min(1).max(200),byteSize:n.number().int().min(1).max(Lo)})).max(400)}),es=n.object({missingAssetCount:n.number().int().min(0)}),ts=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),ns=n.object({seq:n.number().int().min(0),firstEventMs:n.number().int().min(0),lastEventMs:n.number().int().min(0),continues:n.boolean()}),rs=n.discriminatedUnion(`state`,[ns.extend({state:n.literal(`available`),download:Et}),ns.extend({state:n.literal(`missing`)})]),is=n.object({seq:n.number().int().min(0),firstMs:n.number().int().min(0),lastMs:n.number().int().min(0),epoch:n.number().int().min(0),startsEpoch:n.boolean()}),as=n.discriminatedUnion(`state`,[is.extend({state:n.literal(`available`),download:Et}),is.extend({state:n.literal(`missing`)})]),os=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0),viewport:Fo,sourceUrl:n.string().max(Ro),interrupted:n.boolean(),integrity:qo,chunks:n.array(rs),audio:n.object({mimeType:n.string(),chunks:n.array(as)}).nullable(),assets:n.array(n.object({url:n.string(),contentType:n.string(),path:n.string().startsWith(`/v1/recording-assets/`)})),missingAssetCount:n.number().int().min(0)}),ss=n.object({recordingId:n.uuid(),track:Jo,index:n.number().int().min(0)}),cs=n.object({upload:w}),ls=ss.extend({etag:n.string().min(1).max(200)}),us=n.object({integrity:qo}),ds=n.object({canvasId:n.uuid()}),fs=f(Xo),ps=n.object({recordingId:n.uuid()}),ms=n.object({recordingId:n.uuid(),discarded:n.literal(!0)}),hs=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),gs=n.object({recordingId:n.uuid(),detachedScreenCount:n.number().int().min(0)}),_s=(e,t)=>`/v1/recording-assets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`;[`[data-enhance-unsupported]:not([data-enhance-unsupported-hidden]):not([style*="display: none"]) {
|
|
3
|
+
align-items: center !important;
|
|
4
|
+
background-color: #f7f7f8 !important;
|
|
5
|
+
background-image: linear-gradient(to top right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)), linear-gradient(to bottom right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)) !important;
|
|
6
|
+
border: 1px solid #c7c7cc !important;
|
|
7
|
+
box-sizing: border-box !important;
|
|
8
|
+
color: #4f4f55 !important;
|
|
9
|
+
display: flex !important;
|
|
10
|
+
font: 500 14px/1.4 Inter, ui-sans-serif, system-ui, sans-serif !important;
|
|
11
|
+
justify-content: center !important;
|
|
12
|
+
overflow: hidden !important;
|
|
13
|
+
text-align: center !important;
|
|
14
|
+
}`,`[data-enhance-unsupported-hidden], [data-enhance-unsupported][style*="display: none"] {
|
|
15
|
+
display: none !important;
|
|
16
|
+
}`,`[data-enhance-unsupported]::after {
|
|
17
|
+
background: #f7f7f8 !important;
|
|
18
|
+
content: attr(data-enhance-unsupported) !important;
|
|
19
|
+
padding: 4px 8px !important;
|
|
20
|
+
}`,`iframe[data-enhance-unsupported="Embedded content not supported"] {
|
|
21
|
+
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='260' height='44'%3E%3Crect width='260' height='44' rx='6' fill='%23f7f7f8'/%3E%3Ctext x='130' y='27' text-anchor='middle' font-family='Arial,sans-serif' font-size='14' font-weight='500' fill='%234f4f55'%3EEmbedded%20content%20not%20supported%3C/text%3E%3C/svg%3E"), linear-gradient(to top right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)), linear-gradient(to bottom right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)) !important;
|
|
22
|
+
background-position: center, center, center !important;
|
|
23
|
+
background-repeat: no-repeat !important;
|
|
24
|
+
}`].join(`
|
|
25
|
+
`);const vs=n.object({clientToken:n.uuid(),provenance:n.object({sourceRecordingId:n.uuid(),atMs:n.number().int().min(0)}).nullable(),route:n.string().max(l).nullable(),pageTitle:n.string().max(200).nullable(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()}),bytes:n.number().int().min(1).max(2**53-1)}),ys=n.object({screenId:n.uuid(),upload:w,alreadyExists:n.boolean(),state:n.enum([`pending`,`stored`])}),bs=n.object({screenId:n.uuid(),etag:n.string().min(1).max(200)}),xs=n.object({screenId:n.uuid(),storedBytes:n.number().int().min(1),uploadedAt:n.iso.datetime()}),Ss=n.object({screenId:n.uuid()}),Cs=n.object({screenId:n.uuid(),deletedThreadCount:n.number().int().min(0)}),ws=n.object({code:n.enum([`BAD_REQUEST`,`UNAUTHORIZED`,`FORBIDDEN`,`NOT_FOUND`,`CONFLICT`,`RATE_LIMITED`,`INTERNAL`]),message:n.string().min(1),fields:n.record(n.string(),n.string()).optional()}),Ts=e=>ws.safeParse(e).success,M=(e,t,n)=>n===void 0?{code:e,message:t}:{code:e,message:t,fields:n},N=n.number().int().min(0).max(18e5),P=n.number().int().min(0).max(1e6),Es={canvasId:n.uuid(),clientViewId:n.uuid(),releaseIdentity:n.string().min(1).max(100),capabilityVersion:n.number().int().min(1).max(16)},Ds={longTaskCount:P,longTaskTotalMs:N,longestTaskMs:N,loafCount:P,loafTotalBlockingMs:N,loafLongestBlockingMs:N,loafStyleAndLayoutMs:N,loafTopScriptMs:N,loafTopScriptSource:n.enum([`app`,`extension`,`third-party`,`unknown`])},Os=n.discriminatedUnion(`name`,[n.object({...Es,...Ds,name:n.literal(`canvas_load`),outcome:n.enum([`ready`,`slow`,`degraded`,`timed-out`]),bottleneck:n.enum([`metadata`,`projection`,`sources`,`replays`]),durationMs:N,shellMs:N,projectionMs:N,sourcesMs:N,replaysMs:N,nodeCount:P,recordingCount:P,screenCount:P,replayCount:P,unavailableSourceCount:P,assetFailureCount:P,apiRequestCount:P,apiLongestMs:N,mirroredAssetRequestCount:P,mirroredAssetUniqueCount:P,mirroredAssetTransferBytes:n.number().int().min(0).max(1073741824)}),n.object({...Es,...Ds,name:n.literal(`canvas_interaction`),kind:n.enum([`pan`,`zoom`,`drag`,`edit`]),outcome:n.enum([`smooth`,`janky`]),durationMs:N,frameCount:P,slowFrameCount:P,worstFrameMs:N,nodeCount:P,replayCount:P}),n.object({...Es,name:n.literal(`canvas_realtime`),kind:n.enum([`room-ready`,`reconnect`,`recovery`]),outcome:n.enum([`succeeded`,`failed`]),reason:n.enum([`initial`,`transport`,`snapshot`,`gap`,`replace`,`relay`,`history-restored`]),durationMs:N})]),ks=n.object({accepted:n.literal(!0)});n.discriminatedUnion(`type`,[n.object({type:n.literal(`enhance3:extension-probe`)}).strict(),n.object({type:n.literal(`enhance3:extension-present`)}).strict()]);const As=n.enum([`content`,`popup`,`worker`,`offscreen`,`synthetic`]),js=n.uuid(),Ms=n.string().regex(/^[\w.-]{1,64}$/u),Ns=n.enum([`0`,`1`,`2-5`,`6-25`,`26+`]),Ps=n.number().int().min(0).max(18e5),F={correlationId:js,extensionRelease:Ms,capabilityVersion:n.number().int().min(1).max(16),context:As},Fs=n.discriminatedUnion(`name`,[n.object({...F,name:n.literal(`context_lifecycle`),outcome:n.enum([`opened`,`ready`,`closed`,`open-failed`,`close-failed`])}),n.object({...F,name:n.literal(`screen_preview`),outcome:n.enum([`ready`,`unavailable`,`failed`]),source:n.enum([`button`,`shortcut`]),durationMs:Ps,messageBytes:n.number().int().min(0).max(67108864)}),n.object({...F,name:n.literal(`authentication`),state:n.enum([`signed-in`,`signed-out`,`invalid`,`unknown`])}),n.object({...F,name:n.literal(`destination_request`),outcome:n.enum([`succeeded`,`empty`,`failed`]),latencyMs:Ps,resultCountBucket:Ns,retryOutcome:n.enum([`not-retried`,`retry-succeeded`,`retry-failed`])}),n.object({...F,name:n.literal(`destination_picker`),outcome:n.enum([`options`,`blank`,`error`]),optionCountBucket:Ns}),n.object({...F,name:n.literal(`recording_transition`),state:n.enum([`starting`,`recording`,`stopping`,`landed`,`failed`,`cancelled`,`reloaded`]),terminalReason:n.enum([`none`,`completed`,`failed`,`cancelled`,`tab-closed`,`worker-reloaded`,`start-timeout`,`session-rejected`])}),n.object({...F,name:n.literal(`microphone_session`),outcome:n.enum([`opened`,`refused`,`closed`,`still-active`]),durationMs:Ps,activeAudioTrackCount:n.number().int().min(0).max(8)}),n.object({...F,name:n.literal(`microphone_permission`),standing:n.enum([`prompt`,`granted`,`denied`,`unknown`]),outcome:n.enum([`observed`,`request-started`,`granted`,`denied`,`refused`,`no-device`,`in-use`,`unavailable`,`settings-opened`])}),n.object({...F,name:n.literal(`recording_cleanup`),outcome:n.enum([`released`,`still-active`,`incomplete`]),terminalReason:n.enum([`completed`,`failed`,`cancelled`,`tab-closed`,`worker-reloaded`,`start-timeout`,`session-rejected`]),mediaRecorderState:n.enum([`not-created`,`inactive`,`recording`,`paused`,`unknown`]),activeAudioTrackCount:n.number().int().min(0).max(8),audioContextState:n.enum([`not-created`,`closed`,`running`,`suspended`,`interrupted`,`unknown`]),offscreenDocumentState:n.enum([`open`,`closed`,`not-open`,`unknown`])}),n.object({...F,name:n.literal(`synthetic_stage`),stage:n.enum([`release-identity`,`authentication`,`destination-list`,`recording-start`,`recording-landed`,`microphone-release`]),outcome:n.enum([`passed`,`failed`]),durationMs:Ps})]),Is=n.object({accepted:n.literal(!0)}),Ls=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),Rs=Ls,zs=n.object({sequence:n.number().int().min(0),startMs:n.number().int().min(0),endMs:n.number().int().min(0),text:n.string().min(1)}),Bs=n.object({state:n.literal(`processing`),hasPublishedTranscript:n.boolean()}),Vs=n.object({state:n.literal(`ready`),languageCode:n.string().min(1),integrity:n.enum([`whole`,`partial`]),isRefreshing:n.boolean(),cues:n.array(zs)}),Hs=n.object({state:n.literal(`empty`),reason:n.enum([`no-audio`,`too-short`,`audio-missing`,`no-speech`])}),Us=n.object({state:n.literal(`failed`),canRetry:n.boolean()}),Ws=n.discriminatedUnion(`state`,[Bs,Vs,Hs,Us]),Gs=Ls,Ks=Bs;var qs=class extends Error{code;remediation;fields;constructor(e,t,n,r){super(t),this.name=`CliError`,this.code=e,this.remediation=n,this.fields=r}},Js=class extends qs{constructor(e,t){super(`INTERNAL`,e,t),this.name=`PartialBatchError`}};const I=`00000000-0000-4000-8000-000000000010`,Ys=.1,Xs=er.omit({mutationId:!0}),Zs=n.object({canvasId:n.uuid(),expectedVersion:n.number().int().positive().nullable().describe(`Exact document version to render, or null to accept the current version.`),target:Ft.describe(`Area to render: all authored content, one stable node id, or explicit world-space bounds.`),sourceState:It.nullable().describe(`Recording moment to display while rendering its recording node, or null.`),scale:n.number().min(Ys).max(4).describe(`Output pixels per canvas unit, from 0.1 through 4.`),outputPath:n.string().min(1).nullable().describe(`Local PNG path, or null for a protected temporary artifact.`),overwrite:n.boolean().describe(`Whether an existing outputPath may be replaced.`),timeoutMs:n.number().int().positive().describe(`Local render polling deadline in milliseconds.`)}),Qs=n.object({canvasId:n.uuid(),targetNodeId:n.string().min(1).max(200).describe(`Stable container id for insert-children, or subtree root id for replace.`),mode:n.enum([`insert-children`,`replace`]).describe(`Insert the compiled group inside the target, or replace the target subtree.`),html:n.string().min(1).max(1e6).describe(`Exactly one safe top-level HTML/CSS visual group to compile into editable nodes.`),idPrefix:n.string().min(1).max(100).optional().describe(`Optional stable namespace for the node ids generated by this import.`),baseVersion:n.number().int().positive(),renderOutputPath:n.string().min(1).nullable().describe(`Local review PNG path, or null for a protected temporary artifact.`),overwriteRender:n.boolean().describe(`Whether an existing renderOutputPath may be replaced.`),renderScale:n.number().min(Ys).max(4).describe(`Review PNG pixels per canvas unit, from 0.1 through 4.`),renderTimeoutMs:n.number().int().positive().describe(`Local import and review-render polling deadline in milliseconds.`)}),$s=n.object({canvasId:n.uuid()}),ec=n.object({canvasId:n.uuid(),prototypeId:n.uuid().nullable().describe(`Existing prototype id to redeploy, or null to create one.`),nodeId:n.string().min(1),title:n.string().min(1),directory:n.string().min(1).describe(`Absolute local directory containing the built prototype.`),entryPath:n.string().min(1).describe(`HTML entry file path relative to directory, normally index.html.`),baseVersion:n.number().int().positive(),box:n.object({x:n.number(),y:n.number(),width:n.number().positive(),height:n.number().positive()}).describe(`World-space position and size for the prototype node on the canvas.`)}),tc=n.object({canvasId:n.uuid(),recordingId:n.uuid(),atMs:n.number().int().nonnegative().describe(`Visually reviewed recording timestamp to persist, in milliseconds.`),timeoutMs:n.number().int().positive().describe(`Local snapshot polling deadline in milliseconds.`)}),nc=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),rc=[{id:`canvas.apply`,cliPath:`canvas apply`,operation:`mutation`,effect:`write`,idempotency:`single`,inputSchema:Xs,outputSchema:tr,summary:`Atomically apply bounded canvas edits and report their exact affected state.`,procedures:[`canvas.realtime.activity.begin`,`canvas.realtime.activity.renew`,`canvas.realtime.activity.end`,`canvas.applyOperations`],inputExample:{canvasId:I,baseVersion:1,operations:[{op:`setText`,nodeId:`text_title`,text:`Ready`}]},outputExample:{canvasId:I,mutationId:I,previousVersion:1,version:2,insertedNodeIds:[],changedNodeIds:[`text_title`],removedNodeIds:[],boxes:{},affectedBounds:null,next:[`Inspect version 2.`]}},{id:`canvas.render`,cliPath:`canvas render`,operation:`mutation`,effect:`read`,idempotency:`single`,inputSchema:Zs,outputSchema:n.looseObject({jobId:n.uuid(),canvasId:n.uuid(),loadedVersion:n.number().int().positive(),contentType:n.literal(`image/png`),bytes:n.number().int().positive(),path:n.string().min(1),sensitive:n.literal(!0),next:n.array(n.string())}),summary:`Render production-faithful canvas pixels into a protected PNG artifact.`,procedures:[`canvas.render.create`,`canvas.render.get`,`canvas.render.download`],inputExample:{canvasId:I,expectedVersion:1,target:{kind:`content`},sourceState:null,scale:1,outputPath:null,overwrite:!1,timeoutMs:12e4},outputExample:{jobId:I,canvasId:I,loadedVersion:1,contentType:`image/png`,bytes:68,path:`/protected/render.png`,sensitive:!0,next:[`Inspect the PNG.`]}},{id:`canvas.writeHtml`,cliPath:`canvas write-html`,operation:`mutation`,effect:`write`,idempotency:`composite`,inputSchema:Qs,outputSchema:n.looseObject({canvasId:n.uuid(),mutationCommitted:n.literal(!0),previousVersion:n.number().int().positive(),version:n.number().int().positive(),createdNodes:n.array(n.object({id:n.string(),name:n.string(),component:n.string()})),removedNodeIds:n.array(n.string()),next:n.array(n.string())}),summary:`Compile safe HTML and CSS into editable canvas nodes, then render the result.`,procedures:[`canvas.realtime.activity.begin`,`canvas.realtime.activity.renew`,`canvas.realtime.activity.end`,`canvas.document.get`,`canvas.render.importSource`,`canvas.render.getImport`,`canvas.render.create`,`canvas.render.get`,`canvas.render.download`],inputExample:{canvasId:I,targetNodeId:`root`,mode:`insert-children`,html:`<div layer-name="Ready" style="display:flex;width:320px;height:180px"></div>`,idPrefix:`example`,baseVersion:1,renderOutputPath:null,overwriteRender:!1,renderScale:1,renderTimeoutMs:12e4},outputExample:{canvasId:I,mutationCommitted:!0,previousVersion:1,version:2,createdNodes:[{id:`example_ready_0001`,name:`Ready`,component:`frame`}],removedNodeIds:[],next:[`Inspect the review PNG.`]}}],ic=n.record(n.string(),n.unknown()),ac=e=>{let t=ic.safeParse(e);return t.success?t.data:null},oc=e=>{if(e.format===`uuid`)return I;if(e.format===`email`)return`agent@example.test`;if(e.format===`date-time`)return`2026-08-10T00:00:00.000Z`;if(e.format===`uri`||e.format===`url`)return`https://example.test/path`;if((typeof e.pattern==`string`?e.pattern:``).includes(`development`))return`development`;let t=typeof e.minLength==`number`?e.minLength:1;return`x`.repeat(Math.max(1,t))},sc=e=>{let t=Array.isArray(e.anyOf)?e.anyOf:null,n=Array.isArray(e.oneOf)?e.oneOf:null,r=t??n;return r===null?void 0:uc(r[0])},cc=e=>{let t=ac(e.properties)??{},n=Array.isArray(e.required)?e.required:[],r=[];for(let e of n)typeof e==`string`&&r.push([e,uc(t[e])]);return Object.fromEntries(r)},lc=e=>typeof e.minimum==`number`?e.minimum:typeof e.exclusiveMinimum==`number`?e.exclusiveMinimum+1:0,uc=e=>{let t=ac(e);if(t===null)return{};if(`default`in t)return t.default;if(`const`in t)return t.const;let n=t.enum;if(Array.isArray(n))return n[0];let r=sc(t);if(r!==void 0)return r;if(t.type===`null`)return null;if(t.type===`string`)return oc(t);if(t.type===`boolean`)return!1;if(t.type===`number`||t.type===`integer`)return lc(t);if(t.type===`array`){let e=typeof t.minItems==`number`?t.minItems:0;return Array.from({length:e},()=>uc(t.items))}return cc(t)},dc={"canvas.version.list":`List retained versions of a canvas, newest first.`,"canvas.version.get":`Read the document and screen manifest retained for one canvas version.`,"canvas.version.name":`Name the current or a retained canvas version so it is kept.`,"canvas.version.updateMetadata":`Replace the title and description of a named canvas version.`,"canvas.version.removeName":`Remove a canvas version’s name and return it to automatic retention.`},fc={"--version-id":"Canvas version entry id returned by `enhance canvas version list`.","--cursor":`Opaque continuation cursor returned by the preceding list page.`,"--limit":`Maximum number of results to return on this page.`,"--include-automatic":`Include unnamed automatic versions as well as retained versions.`,"--actor":"Version author filter: `all` or only versions created by `mine`.","--target":`Version target JSON: current with its expectedVersion, or a retained version with its versionId.`,"--description":`Optional detail explaining why this named version matters, or null.`},pc={...dc,"canvas.createEditableFrame":`Insert one validated primitive subtree beside its source screen as an atomic canvas edit.`,"canvas.create":`Create a canvas and return the id required by canvas-scoped commands.`,"canvas.applyOperations":`Atomically apply validated text, geometry, style, ordering, and removal operations to one canvas version.`,"canvas.realtime.ticket":`Issue a one-use browser ticket for a live canvas room.`,"canvas.realtime.activity.begin":`Show that this agent has started work on a canvas.`,"canvas.realtime.activity.renew":`Renew an active agent-work indicator before its lease expires.`,"canvas.realtime.activity.end":`Remove an agent-work indicator after work completes.`,"canvas.get":`Read one canvas by id, including access and viewer capabilities.`,"canvas.setAccess":`Change how a canvas can be reached by people with its link.`,"canvas.delete":`Move a canvas to its recoverable bin; retention is currently indefinite.`,"canvas.move":`Move a canvas between the personal shelf and a team shelf.`,"canvas.duplicate":`Copy a canvas and its document into the selected shelf.`,"canvas.deletePermanently":`Permanently delete a canvas already in the recoverable bin.`,"canvas.restore":`Restore a canvas from the recoverable bin.`,"canvas.markViewed":`Record that the authenticated person has viewed a canvas.`,"canvas.list":`Find canvas ids by collection, title, access, review state, or deletion state.`,"canvas.rename":`Rename a canvas owned by the authenticated person.`,"canvas.setReviewState":`Change the authenticated person’s review state on a canvas.`,"canvas.document.get":`Read a canvas document, version, and attached screen manifest.`,"canvas.document.save":`Replace a canvas document. A stale base version exits 5 as CONFLICT; read, merge, and retry.`,"canvas.inspect":`Summarize one canvas, its exact document version, kind counts, bounds, and next inspection commands.`,"canvas.tree":`List stable node ids, hierarchy, kinds, and world-space boxes for one canvas.`,"canvas.node":`Read one stable node with its exact styles, props, children, and current version.`,"canvas.selection":`Read the accountable person’s most recently changed live browser selection at an exact canvas version.`,"canvas.participants.list":`List people with direct access to a canvas.`,"canvas.participants.setAccess":`Change a canvas participant between view and comment access.`,"canvas.participants.revoke":`Remove a participant’s direct access to a canvas.`,"canvas.invites.create":`Invite an email address to access a canvas and return the pending invitation.`,"canvas.invites.accept":`Accept a canvas invitation using its secret token.`,"canvas.invites.preview":`Inspect what an invitation grants before accepting it.`,"canvas.invites.list":`List pending and expired invitations for a canvas.`,"canvas.invites.revoke":`Revoke a pending canvas invitation.`,"canvas.invites.resend":`Replace a pending canvas invitation token and send the invitation again.`,"comment.list":`List comment threads and replies on a canvas.`,"comment.start":`Start a comment thread anchored to a canvas location.`,"comment.resolve":`Set a thread resolved or reopened with an explicit target state.`,"comment.reply":`Add a reply to an existing comment thread.`,"comment.react":`Set or remove one emoji reaction on a comment message.`,"comment.edit":`Replace the body of a comment message authored by this person.`,"comment.move":`Move a comment thread anchor to a new canvas location.`,"comment.delete":`Delete an entire comment thread, or tombstone one message when its id is set.`,"organisation.list":`List teams the authenticated person belongs to.`,"organisation.create":`Create a team and make the authenticated person its owner.`,"organisation.update":`Rename a team managed by the authenticated person.`,"organisation.delete":`Delete a team and rehome every canvas to its creator’s personal shelf.`,"organisation.people.list":`List the people and roles in a team.`,"organisation.people.add":`Add an existing account by email; use organisation invites create when no account exists.`,"organisation.people.setRole":`Change a team member between administrator and member.`,"organisation.people.remove":`Remove a person from a team without deleting their account.`,"organisation.people.transferOwnership":`Transfer team ownership to another current member.`,"organisation.invites.create":`Invite an email address to join a team with the selected role.`,"organisation.invites.list":`List pending and expired invitations for a team.`,"organisation.invites.revoke":`Revoke a pending team invitation.`,"organisation.invites.resend":`Replace a team invitation token and send it again.`,"organisation.invites.preview":`Inspect a team invitation before accepting it.`,"organisation.invites.accept":`Accept a team invitation using its secret token.`,"person.me":`Resolve the current person and authentication kind.`,"person.recipients.search":`Find people who can be invited by matching a name or email.`,"person.recipients.recent":`List people recently selected as sharing recipients.`,"person.updateDisplayName":`Change the name shown for the current person throughout Enhance.`,"recording.start":`Start a recording attempt and receive its first signed chunk upload.`,"recording.appendChunk":`Commit metadata for the uploaded DOM chunk at this index, then reserve the next upload.`,"recording.appendAudioChunk":`Commit metadata for the uploaded audio chunk at this index, then reserve the next upload.`,"recording.complete":`Finish a recording and report any missing event or audio chunks.`,"recording.get":`Read one recording and its replay metadata by id.`,"recording.discard":`Abandon an incomplete recording attempt and its uploaded chunks.`,"recording.list":`List recordings attached to one canvas.`,"recording.delete":`Soft-delete a completed recording while preserving screens and clearing their provenance.`,"recording.refreshUpload":`Replace an expired signed upload for a recording chunk.`,"recording.confirmUpload":`Confirm that a repaired recording chunk reached storage.`,"recordingAsset.reserve":`Reserve signed uploads for external assets used by a recording.`,"recordingAsset.confirm":`Confirm which reserved recording assets reached storage.`,"screen.create":`Reserve a signed upload for a captured page and return its screen id.`,"screen.complete":`Confirm a captured page after its bytes have been uploaded.`,"screen.delete":`Delete an unattached captured page owned by this person.`},mc={...fc,"--canvas-id":"Canvas id, from `enhance canvas list`.","--mutation-id":`Client-minted UUID identifying this atomic canvas mutation.`,"--organisation-id":"Team id, from `enhance organisation list`.","--recording-id":"Recording id, from `enhance recording list` or `recording start`.","--screen-id":"Screen id returned by `enhance screen create` or `fixture screen`.","--thread-id":"Comment thread id returned by `comment start` or `enhance comment list`.","--message-id":"Comment message id returned by comment writes or `enhance comment list`.","--node-id":"Stable node id returned by `enhance canvas tree`.","--screen-node-id":"Root-level screen node id returned by `enhance canvas tree`.","--job-id":`Render or conversion job id returned by its create command.`,"--person-id":`Person id returned by the relevant people or participants list.`,"--display-name":`Name to show for the current person in comments and collaboration surfaces.`,"--invite-id":`Invitation id returned by the relevant invites list.`,"--client-token":`Stable UUID to reuse when retrying the exact same mutation.`,"--collection":"Canvas shelf: `own` (default), `everything`, or a team UUID from `organisation list`.","--scope":"Within the shelf, return `all`, only `mine`, or only canvases `shared` with me.","--deleted":`Set true to search the recoverable canvas bin instead of active canvases.`,"--access-state":`Filter or set link reach: invite-only, link-view, or link-comment.`,"--has-unresolved":`Set true to return only canvases with unresolved comment threads.`,"--base-version":"Document version returned by `enhance canvas document get`.","--operations":`One or more validated canvas operations; use the canvas apply command’s @file form for a batch.`,"--phase":`Agent work now in progress: reading, writing, creating, deleting, or rendering.`,"--node-ids":`Stable canvas node ids affected by the current agent activity.`,"--bounds":`Optional world-space activity bounds as x, y, width, and height JSON.`,"--activity-id":`Active agent-work lease id returned by canvas realtime activity begin.`,"--role":`Team role to grant: admin or member.`,"--access-level":`Participant access to grant: can-comment or can-view.`,"--expires-at":`ISO date-time when the token expires, or the literal null for no expiry.`,"--etag":`ETag returned by the signed upload PUT, with surrounding quotes removed.`,"--index":`Zero-based chunk index expected by the current recording upload.`,"--bytes":`Exact byte length of the content uploaded through the signed URL.`,"--viewport":'Viewport JSON, for example `{"width":1440,"height":900}`.',"--route":`Original page route retained with the captured screen.`,"--page-title":`Page title retained with the capture or used for a new canvas.`,"--title":`Human-readable title used to name or find the resource.`,"--email":`Email address of the person to invite or add.`,"--body":`Comment text; use the JSON input for content that is difficult to quote.`,"--source-url":`Original page URL associated with the capture or recording.`,"--name":`Human-readable team name.`,"--token":`Secret invitation token from its delivery message or local create result.`,"--filter":`Comment state to return: open, resolved, or all.`,"--author-person-id":`Only comments by this person id, from a comment author object.`,"--agent-actionable":`Set true to require an element source file; use --filter open for open actionable threads.`,"--query":`Text to search for in the resources returned by this command.`,"--client-thread-id":`Client-minted UUID; reuse it when retrying this thread creation.`,"--client-message-id":`Client-minted UUID; reuse it when retrying this reply.`,"--mentioned-person-ids":`Person UUIDs to mention; get them from the relevant people or participants list.`,"--resolved":`Target state: true resolves the thread; false reopens it.`,"--emoji":`Single emoji to add to or remove from the comment message.`,"--reacted":`Target state: true adds this person’s reaction; false removes it.`,"--review-state":`Review state to store: not-started, in-progress, or done.`,"--confirmation":`Exact current canvas title; get it from the deleted canvas list.`,"--document":`Complete opaque canvas document as one JSON object.`,"--draft":`Versioned primitive subtree JSON produced by screen conversion.`,"--screen-ids":`Every attached screen UUID; omit the option to replace the manifest with none.`,"--anchor":'Anchor JSON; canvas example: `{"on":"canvas","point":{"x":120,"y":160}}`.',"--label":`Human-readable label identifying an agent credential.`,"--audio":'Audio JSON such as `{"mimeType":"audio/webm;codecs=opus","sampleRate":48000}`, or null.',"--first-event-ms":`Earliest event offset in this DOM chunk, in milliseconds.`,"--last-event-ms":`Latest event offset in this DOM chunk, in milliseconds.`,"--event-count":`Number of events that begin in this DOM chunk; zero is valid.`,"--continues":`True when the first byte continues an event begun in the previous DOM chunk.`,"--first-ms":`Start offset of this audio chunk, in milliseconds.`,"--last-ms":`End offset of this audio chunk, in milliseconds.`,"--epoch":`Zero-based independently decodable audio segment number.`,"--starts-epoch":`True when this audio chunk contains its epoch container header.`,"--duration-ms":`Total recording duration in milliseconds.`,"--interrupted":`True when capture ended unexpectedly rather than by an ordinary stop.`,"--audio-chunk-count":`Number of audio chunks the client attempted; zero means no microphone.`,"--has-recoverable-bytes":`True when exact bytes for at least one missing chunk were retained.`,"--track":`Recording stream to repair: dom or audio.`,"--assets":`Asset reservation objects as JSON: url, contentType, and byteSize.`,"--arrived":`Uploaded asset objects as JSON: url, etag, and byteSize.`,"--provenance":'Origin JSON `{"sourceRecordingId":"UUID","atMs":0}`, or null for a standalone screen.',"--json":`Complete procedure input as JSON; do not combine it with field flags.`,"auth login --token":`Existing agent token for CI or headless fallback; omit it to authenticate in a browser.`,"canvas.create --organisation-id":"Team UUID from `enhance organisation list`; omit it to create on the personal shelf.","canvas.move --organisation-id":"Destination team UUID from `enhance organisation list`, or the literal `personal`.","canvas.duplicate --organisation-id":"Destination team UUID from `enhance organisation list`, or the literal `personal`.","canvas.deletePermanently --confirmation":"Exact canvas title returned by `enhance canvas list --deleted true`.","canvas.document.save --base-version":"Current version from `canvas document get`; a stale value exits 5 with CONFLICT.","canvas.document.save --document":`Complete opaque JSON object; preserve fields you did not intend to change.`,"canvas.document.save --screen-ids":`Complete replacement manifest of screen UUIDs; omit to detach every screen.`,"canvas.participants.setAccess --person-id":"Participant person id from `enhance canvas participants list`.","canvas.participants.revoke --person-id":"Participant person id from `enhance canvas participants list`.","canvas.invites.accept --token":`Secret canvas invitation token; omit this option to read one line from stdin.`,"canvas.invites.preview --token":`Secret canvas invitation token; omit this option to read one line from stdin.`,"comment.list --query":`Text to match in comment message bodies.`,"comment.start --anchor":'JSON canvas anchor: `{"on":"canvas","point":{"x":120,"y":160}}`; node and screen anchors also accept their ids.',"comment.move --anchor":'Replacement anchor JSON; canvas example: `{"on":"canvas","point":{"x":120,"y":160}}`.',"comment.delete --message-id":`Message id to tombstone; omit this option to delete the entire thread.`,"comment.resolve --resolved":`Required target state: true resolves the thread; false reopens it.`,"organisation.people.setRole --person-id":"Team member person id from `enhance organisation people list`.","organisation.people.remove --person-id":"Team member person id from `enhance organisation people list`.","organisation.people.transferOwnership --person-id":"Current team member person id from `enhance organisation people list`.","organisation.invites.revoke --invite-id":"Team invitation id from `enhance organisation invites list`.","organisation.invites.resend --invite-id":"Team invitation id from `enhance organisation invites list`.","organisation.invites.preview --token":`Secret team invitation token; omit this option to read one line from stdin.`,"organisation.invites.accept --token":`Secret team invitation token; omit this option to read one line from stdin.`,"person.recipients.search --query":`Name or email text to match against available recipients.`,"recording.complete --canvas-id":`Existing destination canvas UUID; do not combine with --organisation-id.`,"recording.complete --organisation-id":`Team UUID for a newly created canvas; omit both destination flags for personal.`,"recording.start --page-title":`Required captured page title, or the literal null.`,"recording.appendChunk --etag":`ETag from the already-uploaded chunk at --index; omit only when abandoning that range.`,"recording.appendAudioChunk --etag":`ETag from the already-uploaded audio chunk at --index; omit only when abandoning it.`,"recordingAsset.reserve --assets":'One or more JSON objects shaped `{"url":"https://…","contentType":"image/png","byteSize":123}`.',"recordingAsset.confirm --arrived":'One or more JSON objects shaped `{"url":"https://…","etag":"…","byteSize":123}`.',"screen.create --client-token":`Client-minted capture UUID; reuse it when retrying the same screen reservation.`,"screen.create --provenance":'Required origin JSON `{"sourceRecordingId":"UUID","atMs":0}`, or the literal null.',"screen.create --route":`Required original page route, or the literal null.`,"screen.create --page-title":`Required captured page title, or the literal null.`,"fixture recording --source-url":`Required original page URL represented by this recording.`},hc=n.record(n.string(),n.unknown()),gc=e=>{let t=hc.safeParse(e);return t.success?t.data:null},_c=e=>{if(Array.isArray(e))return e.map(e=>_c(e));let t=gc(e);return t===null?e:Object.fromEntries(Object.entries(t).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,_c(t)]))},vc=e=>r(`sha256`).update(JSON.stringify(_c(e))).digest(`hex`),yc=e=>e.replaceAll(/[A-Z]/gu,e=>`-${e.toLowerCase()}`),bc=(e,t,n)=>{let r=gc(e),i=gc(r?.properties);if(i===null)return[];let a=new Set(Array.isArray(r?.required)?r.required:[]);return Object.entries(i).map(([e,r])=>{let i=gc(r),o=`--${yc(e)}`,s=n===`input`?mc[`${t} ${o}`]??mc[o]:void 0;return{name:e,required:a.has(e),meaning:s??(typeof i?.description==`string`?i.description:`${n===`input`?`Input`:`Returned`} field ${e}.`)}})},xc=(e,t)=>{let n=gc(t)?.description;return pc[e]??(typeof n==`string`&&n!==``?n:`Run the ${e} product operation.`)},Sc=(e,t)=>{let n=e.split(`.`,1)[0]??e;return e.endsWith(`.list`)?[`Choose an id from the result before another ${n} operation.`]:t===`mutation`?[`Read the affected ${n} resource to confirm the result.`]:[`Use the returned identifiers and version in the next ${n} operation.`]},Cc=e=>({summary:xc(e.id,e.meta),useWhen:e.operation===`query`?`Use when current ${e.id.split(`.`,1)[0]??`product`} state is needed before deciding or changing anything.`:`Use when the requested change exactly matches ${e.id}; read the current state first when a version or identifier may have changed.`,preconditions:[`Authenticate as the accountable Enhance person.`,`Use only resource identifiers returned by an earlier capability result or supplied by the person.`,...e.operation===`mutation`?[`Reuse clientToken only when retrying this exact mutation input.`]:[]],input:bc(e.inputJson,e.id,`input`),output:bc(e.outputJson,e.id,`output`),result:`Returns a typed ${e.id} result from the Enhance API without transport-specific prose.`,recovery:[`BAD_REQUEST: correct the named fields and call again.`,`UNAUTHORIZED: restore Enhance authentication, then retry once.`,`FORBIDDEN or NOT_FOUND: list accessible resources and choose an allowed identifier.`,`CONFLICT: read the current resource, merge the intended change, and retry with its version.`,`INTERNAL: run Enhance diagnostics, report the failure, and stop repeating the call.`],next:Sc(e.id,e.operation),examples:[{input:e.inputExample,output:e.outputExample}]}),wc=e=>n.union([n.object({ok:n.literal(!0),result:e}),n.object({ok:n.literal(!0),artifact:n.object({uri:n.string(),mimeType:n.string().min(1),bytes:n.number().int().nonnegative()})}),n.object({ok:n.literal(!1),error:n.object({code:n.string(),message:n.string(),remediation:n.string(),fields:n.array(n.object({path:n.string(),message:n.string()})).optional()})})]),Tc=e=>{let t=n.toJSONSchema(e.inputSchema,{unrepresentable:`any`}),r=n.toJSONSchema(e.outputSchema,{unrepresentable:`any`}),i=e.guide??Cc({id:e.id,operation:e.operation,meta:e.meta,inputJson:t,outputJson:r,inputExample:e.inputExample??uc(t),outputExample:e.outputExample??uc(r)});return{id:e.id,operation:e.operation,source:e.source,effect:e.effect,idempotency:e.idempotency,execution:e.execution,inputSchema:e.inputSchema,outputSchema:e.outputSchema,resultSchema:wc(e.outputSchema),guide:i,policy:e.policy,cli:e.cliPath===null?null:{path:e.cliPath},schemaDigest:vc({input:t,output:r}),guidanceDigest:vc(i),behaviorDigest:vc({id:e.id,source:e.source,effect:e.effect,idempotency:e.idempotency,execution:e.execution,input:t,output:r})}},Ec={exposure:`shared`,reason:`Authenticated product operation supported equally by CLI and MCP.`,owner:`product`},Dc={"canvas.applyOperations":{exposure:`internal`,reason:`Wrapped by bounded, intention-revealing authoring capabilities.`,owner:`product`},"canvas.realtime.ticket":{exposure:`internal`,reason:`Browser WebSocket admission is not an agent capability.`,owner:`product`},"canvas.reserveImage":{exposure:`internal`,reason:`Signed image upload reservation is wrapped by file-safe authoring.`,owner:`product`},"canvas.render.cancel":{exposure:`internal`,reason:`Render lifecycle detail is owned by higher-level render capabilities.`,owner:`product`},"canvas.render.create":{exposure:`internal`,reason:`Render lifecycle detail is owned by higher-level render capabilities.`,owner:`product`},"canvas.render.download":{exposure:`internal`,reason:`Signed downloads must be written through a protected artifact adapter.`,owner:`product`},"canvas.render.exposure":{exposure:`internal`,reason:`Signed render exposure is a transport implementation detail.`,owner:`product`},"canvas.render.get":{exposure:`internal`,reason:`Render polling is owned by higher-level render capabilities.`,owner:`product`},"canvas.render.snapshot":{exposure:`internal`,reason:`Render snapshot creation is owned by higher-level render capabilities.`,owner:`product`},"canvas.thumbnail.reportUnavailable":{exposure:`internal`,reason:`Browser thumbnail telemetry is not an agent capability.`,owner:`product`},"canvas.version.duplicate":{exposure:`internal`,reason:`Duplicating historical state is restricted to an interactive person session.`,owner:`product`},"canvas.version.restore":{exposure:`internal`,reason:`Restoring historical state is restricted to an interactive person session.`,owner:`product`},"person.createAgentToken":{exposure:`cli-transport`,reason:`Credential lifecycle remains in the interactive CLI auth surface.`,owner:`cli`},"person.listAgentTokens":{exposure:`cli-transport`,reason:`Credential lifecycle remains in the interactive CLI auth surface.`,owner:`cli`},"person.revokeAgentToken":{exposure:`cli-transport`,reason:`Credential lifecycle remains in the interactive CLI auth surface.`,owner:`cli`},"person.signIn":{exposure:`internal`,reason:`Browser sign-in protocol is wrapped by the CLI auth surface.`,owner:`product`},"person.signOut":{exposure:`internal`,reason:`Browser sign-out protocol is wrapped by the CLI auth surface.`,owner:`product`},"person.signUp":{exposure:`internal`,reason:`Browser sign-up protocol is not an agent capability.`,owner:`product`},"prototype.complete":{exposure:`internal`,reason:`Prototype upload lifecycle is wrapped by prototype publish.`,owner:`product`},"prototype.attach":{exposure:`internal`,reason:`Prototype upload lifecycle is wrapped by prototype publish.`,owner:`product`},"prototype.create":{exposure:`internal`,reason:`Prototype upload lifecycle is wrapped by prototype publish.`,owner:`product`},"prototype.createArtifact":{exposure:`internal`,reason:`Prototype upload lifecycle is wrapped by prototype publish.`,owner:`product`},"prototype.getArtifactCapabilities":{exposure:`internal`,reason:`Prototype upload lifecycle is wrapped by prototype publish.`,owner:`product`},"prototype.getPublishStatus":{exposure:`internal`,reason:`Prototype upload lifecycle is wrapped by prototype publish.`,owner:`product`},"prototype.requestRuntimeTicket":{exposure:`internal`,reason:`Runtime ticket material must never enter an agent tool result.`,owner:`product`},"prototype.reserveUploads":{exposure:`internal`,reason:`Signed uploads are wrapped by prototype publish.`,owner:`product`},"prototype.submitArtifact":{exposure:`internal`,reason:`Prototype upload lifecycle is wrapped by prototype publish.`,owner:`product`},"telemetry.lifecycle":{exposure:`internal`,reason:`Product telemetry is not an agent capability.`,owner:`product`},"telemetry.performance":{exposure:`internal`,reason:`Product telemetry is not an agent capability.`,owner:`product`},"transcript.get":{exposure:`internal`,reason:`Transcript storage details are wrapped by transcript get.`,owner:`product`}},Oc={"canvas.apply":{exposure:`shared`,reason:`Bounded canvas operation batches are a product authoring capability.`,owner:`product`},"canvas.render":{exposure:`shared`,reason:`Production-faithful canvas rendering is a product inspection capability.`,owner:`product`},"canvas.writeHtml":{exposure:`shared`,reason:`HTML-to-editable-canvas authoring is a bounded product composite.`,owner:`product`},"comment.attention":{exposure:`shared`,reason:`Finding unresolved canvas feedback is a product reading capability.`,owner:`product`},"prototype.publish":{exposure:`shared`,reason:`Packaging and publishing a prototype is a product artifact composite.`,owner:`product`},"recording.snapshot":{exposure:`shared`,reason:`Persisting an accepted recording moment is a product authoring composite.`,owner:`product`},"transcript.read":{exposure:`shared`,reason:`Transcript-led recording inspection is a product reading composite.`,owner:`product`},"auth.login":{exposure:`cli-transport`,reason:`Interactive credential acquisition belongs only to the CLI transport.`,owner:`cli`},"auth.status":{exposure:`cli-transport`,reason:`Local credential inspection belongs only to the CLI transport.`,owner:`cli`},"auth.logout":{exposure:`cli-transport`,reason:`Local credential deletion belongs only to the CLI transport.`,owner:`cli`},doctor:{exposure:`cli-transport`,reason:`Local installation diagnostics belong only to the CLI transport.`,owner:`cli`},commands:{exposure:`cli-transport`,reason:`CLI command inventory belongs only to the CLI transport.`,owner:`cli`},"fixture.screen":{exposure:`cli-development`,reason:`Development fixture creation reads local files and is not a product capability.`,owner:`development`},"fixture.recording":{exposure:`cli-development`,reason:`Development fixture creation reads local files and is not a product capability.`,owner:`development`},"fixture.world":{exposure:`cli-development`,reason:`Development fixture creation reads local files and is not a product capability.`,owner:`development`}},kc=new Set(`canvas.create,canvas.createEditableFrame,canvas.delete,canvas.deletePermanently,canvas.document.get,canvas.document.save,canvas.duplicate,canvas.get,canvas.inspect,canvas.invites.accept,canvas.invites.create,canvas.invites.list,canvas.invites.preview,canvas.invites.resend,canvas.invites.revoke,canvas.list,canvas.markViewed,canvas.move,canvas.node,canvas.participants.list,canvas.participants.revoke,canvas.participants.setAccess,canvas.realtime.activity.begin,canvas.realtime.activity.end,canvas.realtime.activity.renew,canvas.rename,canvas.render.cancelImport,canvas.render.getImport,canvas.render.importSource,canvas.restore,canvas.selection,canvas.setAccess,canvas.setReviewState,canvas.tree,canvas.version.get,canvas.version.list,canvas.version.name,canvas.version.removeName,canvas.version.updateMetadata,comment.delete,comment.edit,comment.list,comment.move,comment.react,comment.reply,comment.resolve,comment.start,organisation.create,organisation.delete,organisation.invites.accept,organisation.invites.create,organisation.invites.list,organisation.invites.preview,organisation.invites.resend,organisation.invites.revoke,organisation.list,organisation.people.add,organisation.people.list,organisation.people.remove,organisation.people.setRole,organisation.people.transferOwnership,organisation.update,person.me,person.recipients.recent,person.recipients.search,person.updateDisplayName,recording.appendAudioChunk,recording.appendChunk,recording.complete,recording.confirmUpload,recording.delete,recording.discard,recording.get,recording.list,recording.refreshUpload,recording.start,recordingAsset.confirm,recordingAsset.reserve,screen.complete,screen.create,screen.delete,transcript.retry`.split(`,`)),Ac=()=>({assertProcedureInventory:e=>{let t=new Set(e),n=new Set([...kc,...Object.keys(Dc)]),r=[],i=[];for(let e of t)n.has(e)||r.push(e);for(let e of n)t.has(e)||i.push(e);if(r.length===0&&i.length===0)return;let a=r.join(`,`),o=i.join(`,`);throw TypeError(`capability policy mismatch: unknown=${a===``?`none`:a} stale=${o===``?`none`:o}`)},forProcedure:e=>{let t=Dc[e];if(t!==void 0)return t;if(kc.has(e))return Ec;throw TypeError(`${e} has no explicit capability policy`)},forUtility:e=>{let t=Oc[e];if(t===void 0)throw TypeError(`${e} has no explicit utility policy`);return t},excludedProcedures:new Set(Object.entries(Dc).flatMap(([e,t])=>t.exposure===`shared`?[]:[e]))}),jc=[{id:`comment.attention`,cliPath:`comment attention`,operation:`query`,effect:`read`,idempotency:`none`,inputSchema:$s,outputSchema:Mi,summary:`List every open canvas comment that may need attention.`,procedures:[`comment.list`],inputExample:{canvasId:I},outputExample:{items:[],truncated:!1}},{id:`prototype.publish`,cliPath:`prototype publish`,operation:`mutation`,effect:`external`,idempotency:`composite`,inputSchema:ec,outputSchema:n.looseObject({canvasId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),version:n.number().int().positive(),openUrl:n.string().startsWith(`/c/`),next:n.array(n.string())}),summary:`Package, upload, ingest, and attach a static prototype directory.`,procedures:[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`,`prototype.attach`],inputExample:{canvasId:I,prototypeId:null,nodeId:`prototype_ready`,title:`Ready prototype`,directory:`/absolute/build`,entryPath:`index.html`,baseVersion:1,box:{x:48,y:48,width:1440,height:900}},outputExample:{canvasId:I,deploymentId:I,nodeId:`prototype_ready`,version:2,openUrl:`/c/${I}`,next:[`Open the prototype.`]}},{id:`recording.snapshot`,cliPath:`recording snapshot`,operation:`mutation`,effect:`write`,idempotency:`single`,inputSchema:tc,outputSchema:n.looseObject({jobId:n.uuid(),canvasId:n.uuid(),screenId:n.uuid(),screenNodeId:n.string().min(1),version:n.number().int().positive(),retryClientToken:n.uuid(),next:n.array(n.string())}),summary:`Persist one visually accepted recording moment as an editable canvas screen.`,procedures:[`canvas.render.snapshot`,`canvas.render.get`],inputExample:{canvasId:I,recordingId:I,atMs:1e3,timeoutMs:12e4},outputExample:{jobId:I,canvasId:I,screenId:I,screenNodeId:`screen_ready`,version:2,retryClientToken:I,next:[`Render the screen.`]}},{id:`transcript.read`,cliPath:`transcript get`,operation:`query`,effect:`read`,idempotency:`none`,inputSchema:nc,outputSchema:Ws,summary:`Read timestamped speech cues for visually verified recording selection.`,procedures:[`transcript.get`],inputExample:{canvasId:I,recordingId:I},outputExample:{state:`empty`,reason:`no-audio`}}],L=(e,t,n)=>n?{code:e,message:t,fields:n}:{code:e,message:t},R=e=>L(`INTERNAL`,e),Mc=n.object({issues:n.array(n.object({path:n.array(n.unknown()),message:n.string(),code:n.string().optional(),origin:n.string().optional(),maximum:n.number().optional(),minimum:n.number().optional(),format:n.string().optional()}))}),Nc={name:`Team name`,title:`Canvas title`,email:`Email address`,username:`Username`,password:`Password`,displayName:`Name`,confirmation:`Confirmation`,canvasId:`Canvas`,organisationId:`Team`,screenIds:`Screens`},Pc=e=>{let t=e.findLast(e=>typeof e==`string`)??`Value`,n=Nc[t];if(n!==void 0)return n;let r=t.replaceAll(/([a-z])([A-Z])/gu,`$1 $2`).toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Fc=e=>`${/^[aeiou]/iu.test(e)?`an`:`a`} ${e.toLowerCase()}`,Ic=e=>{let t=Pc(e.path);return e.code===`too_big`&&e.origin===`string`&&e.maximum!==void 0?`${t} can be up to ${String(e.maximum)} characters. Shorten it and try again.`:e.code===`too_big`&&e.maximum!==void 0?`${t} can contain up to ${String(e.maximum)} items. Remove some and try again.`:e.code===`too_small`&&e.origin===`string`&&e.minimum===1?`Enter ${Fc(t)}.`:e.code===`too_small`&&e.origin===`string`&&e.minimum!==void 0?`${t} needs at least ${String(e.minimum)} characters. Add more and try again.`:e.format===`email`||e.path.includes(`email`)?`Enter a complete email address, such as name@example.com.`:`Check ${t.toLowerCase()} and try again.`},Lc=e=>{let t=Mc.safeParse(e);return t.success?{code:`BAD_REQUEST`,message:`that request will not do`,fields:Object.fromEntries(t.data.issues.map(e=>[e.path.map(String).join(`.`),Ic(e)]))}:null},Rc=e=>Ts(e)?e.code===`INTERNAL`?{code:`INTERNAL`,message:`something went wrong on our side; quote the correlation id`}:{code:e.code,message:e.message,...e.fields&&{fields:e.fields}}:Lc(e),zc=a.context().create({errorFormatter:({shape:e,error:t,ctx:n})=>({...e,data:{...e.data,appError:Rc(t.cause),correlationId:n===void 0?null:n.requestId}})}),z=zc.router,Bc=zc.procedure,B=zc.middleware,Vc={NOT_FOUND:`NOT_FOUND`,UNAUTHORIZED:`UNAUTHORIZED`,FORBIDDEN:`FORBIDDEN`,CONFLICT:`CONFLICT`,RATE_LIMITED:`TOO_MANY_REQUESTS`,BAD_REQUEST:`BAD_REQUEST`,INTERNAL:`INTERNAL_SERVER_ERROR`},V=e=>new i({code:Vc[e.code],message:e.message,cause:e}),Hc=new Set([`canvas.render.create`,`canvas.render.importSource`,`screen.create`]),Uc=e=>{if(e.ok)return{kind:`success`,data:e.data};let t=Rc(e.error.cause);return t===null?{kind:`failure`,error:R(`the original idempotent request failed internally`)}:{kind:`failure`,error:t}},Wc=e=>{if(e.kind===`mismatch`)throw V(L(`BAD_REQUEST`,`this client token was already used with different parameters`));if(e.kind===`pending`)throw V(L(`CONFLICT`,`the request with this client token is still being resolved`));if(e.outcome.kind===`failure`)throw V(e.outcome.error);return{ok:!0,data:e.outcome.data,marker:o}},Gc=B(async({ctx:e,type:t,path:n,getRawInput:r,next:i})=>{if(t!==`mutation`||e.viewer.kind===`anonymous`||e.viewer.kind===`render`||e.idempotencyKey===null||Hc.has(n))return i();let a=await r(),o=await e.idempotency.claim({personId:e.viewer.personId,clientToken:e.idempotencyKey,procedure:n,parameters:a,createdAt:new Date});if(o.isErr())throw V(R(o.error.message));if(o.value.kind!==`started`)return Wc(o.value);let s=await i(),c=await e.idempotency.complete({personId:e.viewer.personId,clientToken:e.idempotencyKey,procedure:n,outcome:Uc(s)});if(c.isErr())throw V(R(c.error.message));return s}),Kc={BAD_REQUEST:`BAD_REQUEST`,UNAUTHORIZED:`UNAUTHORIZED`,FORBIDDEN:`FORBIDDEN`,NOT_FOUND:`NOT_FOUND`,CONFLICT:`CONFLICT`,TOO_MANY_REQUESTS:`RATE_LIMITED`},qc=e=>e instanceof i?Ts(e.cause)?{code:e.cause.code,message:e.cause.message.slice(0,200)}:{code:Kc[e.code]??`INTERNAL`,message:null}:{code:`INTERNAL`,message:null},Jc=B(async({ctx:e,path:t,type:n,next:r})=>{let i=performance.now(),a=await e.profile(async e=>({outcome:await r(),statements:e.statements,blobAttempts:e.blobAttempts,degraded:e.degraded})),o=a.outcome.ok?null:qc(a.outcome.error),s={...e.taggedFields(),event:`ProcedureCalled`,procedure:t,kind:n,durationMs:Math.round(performance.now()-i),queryCount:a.statements.length,blobCallCount:a.blobAttempts.length,blobRetryCount:a.blobAttempts.reduce((e,t)=>e+t.attempts-1,0),degraded:a.degraded.toSorted((e,t)=>e.localeCompare(t)).join(`,`),outcome:a.outcome.ok?`ok`:`error`,errorCode:o?.code??null,errorMessage:o?.message??null};o===null||o.code===`NOT_FOUND`?e.logger.info(s,`rpc`):o.code===`INTERNAL`?e.logger.error(s,`rpc`):e.logger.warn(s,`rpc`);for(let[n,r]of a.statements.entries())e.logger.debug({procedure:t,index:n,atMs:Math.round(r.atMs*100)/100,sql:r.sql},`query`);return a.outcome}),Yc=new Set([`canvas.document.get`,`canvas.render.exposure`,`prototype.requestRuntimeTicket`,`recording.get`,`recording.list`]),Xc=B(async({ctx:e,path:t,next:n})=>{if(e.viewer.kind===`render`&&!Yc.has(t))throw V(M(`FORBIDDEN`,`the render grant cannot call that procedure`));return n()}),H=Bc.use(Jc).use(Xc).use(Gc),U=H.use(B(async({ctx:e,next:t})=>{if(e.viewer.kind===`anonymous`||e.viewer.kind===`render`)throw V(M(`UNAUTHORIZED`,`this call needs a signed-in person`));return t({ctx:{...e,viewer:e.viewer}})})),Zc=H.use(B(async({ctx:e,next:t})=>{if(e.viewer.kind!==`agent`)throw V(M(`UNAUTHORIZED`,`this call needs an agent token`));return t({ctx:{...e,viewer:e.viewer}})})),Qc=H.use(B(async({ctx:e,next:t})=>{if(e.viewer.kind!==`render`)throw V(M(`UNAUTHORIZED`,`this call needs a render grant`));return t({ctx:{...e,viewer:e.viewer}})})),$c=n.object({canvasId:n.uuid()}),el=B(async({ctx:e,getRawInput:t,next:n})=>{let r=$c.safeParse(await t());if(!r.success)throw V(M(`BAD_REQUEST`,`canvasId is required`));let i=(await e.access.resolve({canvasId:r.data.canvasId,viewer:e.viewer})).match(e=>e,e=>{throw V(e)});if(!i.canRead)throw V(M(`NOT_FOUND`,`no such canvas`));return e.tag(`canvasId`,r.data.canvasId),n({ctx:{...e,canvasAccess:i}})}),W=H.use(el),G=Zc.use(el),tl=G.use(async({ctx:e,next:t})=>{if(!e.canvasAccess.canComment)throw V(M(`FORBIDDEN`,`this canvas is read-only for you`));return t({ctx:{...e,viewer:e.viewer}})}),K=W.use(async({ctx:e,next:t})=>{if(!e.canvasAccess.canComment||e.viewer.kind===`anonymous`||e.viewer.kind===`render`)throw V(e.canvasAccess.commentNeedsSignIn||e.viewer.kind===`anonymous`||e.viewer.kind===`render`?M(`UNAUTHORIZED`,`sign in to comment on this canvas`):M(`FORBIDDEN`,`this canvas is read-only for you`));return t({ctx:{...e,viewer:e.viewer}})}),nl=W.use(async({ctx:e,next:t})=>{if(!e.canvasAccess.canShare||e.viewer.kind===`anonymous`||e.viewer.kind===`render`)throw V(M(`FORBIDDEN`,`only a canvas recipient can share this`));return t({ctx:{...e,viewer:e.viewer}})}),q=W.use(async({ctx:e,next:t})=>{if(!e.canvasAccess.canManage||e.viewer.kind===`anonymous`||e.viewer.kind===`render`)throw V(M(`FORBIDDEN`,`only an owner can change this`));return t({ctx:{...e,viewer:e.viewer}})}),J=e=>e.match(e=>e,e=>{throw V(e)}),rl=[`blue`,`violet`,`green`,`amber`,`magenta`,`teal`,`red`,`orange`],il=e=>{let t=0;for(let n of e)t=t*31+(n.codePointAt(0)??0)>>>0;return rl[t%rl.length]??`blue`},al=e=>{let t={personId:e.personId,displayName:e.displayName,initials:e.initials,colour:il(e.kind===`agent`?e.tokenId:e.personId)};return e.kind===`agent`?{...t,kind:`agent`,tokenLabel:e.tokenLabel}:{...t,kind:`person`}},ol=e=>e.kind===`agent`?{personId:e.personId,tokenId:e.tokenId,mutationActor:al(e)}:null,sl=e=>e===`own`?{kind:`own`}:e===`everything`?{kind:`everything`}:{kind:`team`,organisationId:e},Y=e=>({id:e.canvas.id,title:e.canvas.title,accessState:e.canvas.accessState,organisationId:e.canvas.organisationId,sourceUrl:e.reach.canSeeRoutes?e.canvas.sourceUrl:null,unresolvedCount:e.unresolvedCount,viewerCan:{read:e.reach.canRead,comment:e.reach.canComment?`yes`:e.reach.commentNeedsSignIn?`sign-in`:`no`,share:e.reach.canShare,manage:e.reach.canManage},createdAt:e.canvas.createdAt.toISOString(),lastActivityAt:e.canvas.lastActivityAt.toISOString()}),cl=e=>{let t={...Y(e),screenCount:e.screenCount,hasRecording:e.hasRecording};return e.thumbnail===null?{...t,thumbnail:null,thumbnailFallbackReason:e.thumbnailFallbackReason}:{...t,thumbnail:{...e.thumbnail,width:528,height:312}}},ll=e=>mt.parse({id:e.id,label:e.label,component:e.component,...e.labelOrigin!==void 0&&{labelOrigin:e.labelOrigin},...e.visible!==void 0&&{visible:e.visible},...e.locked!==void 0&&{locked:e.locked},...e.constraints!==void 0&&{constraints:e.constraints},styles:{...e.styles},...e.layout!==void 0&&{layout:e.layout},...e.appearance!==void 0&&{appearance:e.appearance},...e.typography!==void 0&&{typography:e.typography},...e.additionalStyles!==void 0&&{additionalStyles:e.additionalStyles},...e.props!==void 0&&{props:{...e.props}},...e.box!==void 0&&{box:{...e.box}}}),ul=e=>K.input(er).output(tr).mutation(async({input:t,ctx:n})=>{let r=J(await e.applyOperations.execute({...t,personId:n.viewer.personId,actor:al(n.viewer)})),i=r.affectedBounds===null?[]:[`enhance canvas render --canvas ${r.canvasId} --bounds '${JSON.stringify(r.affectedBounds)}' --expected-version ${String(r.version)}`];return{...r,insertedNodeIds:[...r.insertedNodeIds],changedNodeIds:[...r.changedNodeIds],removedNodeIds:[...r.removedNodeIds],boxes:{...r.boxes},next:[`enhance canvas tree --canvas ${r.canvasId}`,...i]}}),dl=e=>K.meta({description:`Atomically insert a validated editable frame subtree beside an existing screen.`}).input(wt).output(nr).mutation(async({input:t,ctx:n})=>{let r=J(await e.createEditableFrame.execute({...t,destination:{kind:`adjacent`},source:{kind:`screen`,nodeId:t.screenNodeId},personId:n.viewer.personId,actor:al(n.viewer)}));return{...r,idMap:{...r.idMap},insertedNodeIds:[...r.insertedNodeIds],removedNodeIds:[...r.removedNodeIds],boxes:{...r.boxes},operation:{...r.operation,nodes:Object.fromEntries(Object.entries(r.operation.nodes).map(([e,t])=>[e,ll(t)])),relationships:{...r.operation.relationships}},next:[`enhance canvas tree --canvas ${r.canvasId}`,`enhance canvas render --canvas ${r.canvasId} --bounds '${JSON.stringify(r.affectedBounds)}' --expected-version ${String(r.version)}`]}}),fl=e=>U.input(g).output(h).mutation(async({input:t,ctx:n})=>Y(J(await e.create.execute({title:t.title,creatorPersonId:n.viewer.personId,organisationId:t.organisationId,sourceUrl:t.sourceUrl,origin:n.viewer.kind===`agent`?`agent`:`dashboard`})))),pl=e=>W.input(se).output(h).query(async({input:t,ctx:n})=>{let r=J(await e.get.execute({canvasId:t.canvasId,reach:n.canvasAccess,accessLevel:n.canvasAccess.accessLevel}));return n.telemetry.emit(`CanvasOpened`,{canvasId:r.canvas.id,accessState:r.canvas.accessState,isMember:r.accessLevel===null?0:1}),Y(r)}),ml=e=>q.input(xe).output(Se).mutation(async({input:t,ctx:n})=>{let r=J(await e.setAccess.execute(t));return n.telemetry.emit(`AccessStateChanged`,{canvasId:t.canvasId,fromState:n.canvasAccess.accessState,toState:t.accessState,widened:+!!r.widened}),{canvas:Y({canvas:r.canvas,accessLevel:n.canvasAccess.accessLevel,reach:n.canvasAccess,unresolvedCount:0}),widened:r.widened}}),hl=e=>W.input(Ce).output(we).mutation(async({input:t,ctx:n})=>n.viewer.kind===`anonymous`||n.viewer.kind===`render`?{lastViewedAt:null}:{lastViewedAt:J(await e.markViewed.execute({canvasId:t.canvasId,personId:n.viewer.personId})).lastViewedAt?.toISOString()??null}),gl=e=>z({applyOperations:ul(e),createEditableFrame:dl(e),create:fl(e),get:pl(e),setAccess:ml(e),markViewed:hl(e),list:U.input(le).output(de).query(async({input:t,ctx:n})=>{let r=J(await e.list.execute({...t,collection:sl(t.collection),personId:n.viewer.personId}));return{items:r.items.map(e=>cl(e)),truncated:r.truncated}}),rename:q.input(fe).output(h).mutation(async({input:t,ctx:n})=>Y({canvas:J(await e.rename.execute(t)),accessLevel:n.canvasAccess.accessLevel,reach:n.canvasAccess,unresolvedCount:0})),setReviewState:W.input(gi).output(_i).mutation(async({input:t,ctx:n})=>n.viewer.kind===`anonymous`||n.viewer.kind===`render`?{reviewState:null}:J(await e.setReviewState.execute({...t,personId:n.viewer.personId})))}),_l=e=>W.input(_n).output(yn).query(async({input:t,ctx:n})=>{let r=J(await e.getDocument.execute({canvasId:t.canvasId,withRoutes:n.canvasAccess.canSeeRoutes}));return{version:r.document.version,document:r.document.document,screens:r.screens.map(e=>({screenId:e.screenId,route:e.route,title:e.title,viewport:e.viewport,atMs:e.atMs,sourceRecordingId:e.sourceRecordingId,assetBundle:e.assetBundle===null?null:{...e.assetBundle,assets:[...e.assetBundle.assets]},download:e.download===null?null:{url:e.download.url,expiresAt:e.download.expiresAt.toISOString(),bytes:e.download.bytes}}))}}),vl=e=>K.input(bn).output(xn).mutation(async({input:t,ctx:n})=>{let r=J(await e.saveDocument.execute({canvasId:t.canvasId,personId:n.viewer.personId,baseVersion:t.baseVersion,document:t.document,screenIds:t.screenIds,actor:al(n.viewer)}));return r.outcome===`conflict`?(n.telemetry.emit(`CanvasDocumentConflict`,{canvasId:t.canvasId,serverVersion:r.version,baseVersion:t.baseVersion,versionsBehind:r.version-t.baseVersion}),r):(n.telemetry.emit(`CanvasDocumentSaved`,{canvasId:t.canvasId,version:r.version,documentBytes:JSON.stringify(t.document).length,screenCount:t.screenIds.length}),r)}),yl=e=>z({get:_l(e),save:vl(e)}),bl=e=>z({reserveImage:K.meta({description:`Reserve storage and upload instructions for one canvas image.`}).input(Sn).output(Cn).mutation(async({input:t})=>{let n=J(await e.reserveImage.execute(t));return{...n,path:wn(t.canvasId,n.assetId),upload:{...n.upload,expiresAt:n.upload.expiresAt.toISOString()}}})});var X=c((e=>{let t={withStackTrace:!1},n=(e,n,r=t)=>({data:n.isOk()?{type:`Ok`,value:n.value}:{type:`Err`,value:n.error},message:e,stack:r.withStackTrace?Error().stack:void 0});function r(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function i(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function a(e){return this instanceof a?(this.v=e,this):new a(e)}function o(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,o=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),c(`next`),c(`throw`),c(`return`,s),i[Symbol.asyncIterator]=function(){return this},i;function s(e){return function(t){return Promise.resolve(t).then(e,d)}}function c(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){o.push([e,t,n,r])>1||l(e,t)})},t&&(i[e]=t(i[e])))}function l(e,t){try{ee(r[e](t))}catch(e){f(o[0][3],e)}}function ee(e){e.value instanceof a?Promise.resolve(e.value.v).then(u,d):f(o[0][2],e)}function u(e){l(`next`,e)}function d(e){l(`throw`,e)}function f(e,t){e(t),o.shift(),o.length&&l(o[0][0],o[0][1])}}function s(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:a(e[r](t)),done:!1}:i?i(t):t}:i}}function c(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof i==`function`?i(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,i){n=e[t](n),a(r,i,n.done,n.value)})}}function a(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var l=class e{constructor(e){this._promise=e}static fromSafePromise(t){let n=t.then(e=>new h(e));return new e(n)}static fromPromise(t,n){let r=t.then(e=>new h(e)).catch(e=>new g(n(e)));return new e(r)}static fromThrowable(t,n){return(...i)=>new e(r(this,void 0,void 0,function*(){try{return new h(yield t(...i))}catch(e){return new g(n?n(e):e)}}))}static combine(e){return re(e)}static combineWithAllErrors(e){return ae(e)}map(t){return new e(this._promise.then(e=>r(this,void 0,void 0,function*(){return e.isErr()?new g(e.error):new h(yield t(e.value))})))}andThrough(t){return new e(this._promise.then(e=>r(this,void 0,void 0,function*(){if(e.isErr())return new g(e.error);let n=yield t(e.value);return n.isErr()?new g(n.error):new h(e.value)})))}andTee(t){return new e(this._promise.then(e=>r(this,void 0,void 0,function*(){if(e.isErr())return new g(e.error);try{yield t(e.value)}catch{}return new h(e.value)})))}orTee(t){return new e(this._promise.then(e=>r(this,void 0,void 0,function*(){if(e.isOk())return new h(e.value);try{yield t(e.error)}catch{}return new g(e.error)})))}mapErr(t){return new e(this._promise.then(e=>r(this,void 0,void 0,function*(){return e.isOk()?new h(e.value):new g(yield t(e.error))})))}andThen(t){return new e(this._promise.then(n=>{if(n.isErr())return new g(n.error);let r=t(n.value);return r instanceof e?r._promise:r}))}orElse(t){return new e(this._promise.then(e=>r(this,void 0,void 0,function*(){return e.isErr()?t(e.error):new h(e.value)})))}match(e,t){return this._promise.then(n=>n.match(e,t))}unwrapOr(e){return this._promise.then(t=>t.unwrapOr(e))}safeUnwrap(){return o(this,arguments,function*(){return yield a(yield a(yield*s(c(yield a(this._promise.then(e=>e.safeUnwrap()))))))})}then(e,t){return this._promise.then(e,t)}[Symbol.asyncIterator](){return o(this,arguments,function*(){let e=yield a(this._promise);return e.isErr()&&(yield yield a(u(e.error))),yield a(e.value)})}};function ee(e){return new l(Promise.resolve(new h(e)))}function u(e){return new l(Promise.resolve(new g(e)))}let d=l.fromPromise,f=l.fromSafePromise,te=l.fromThrowable,ne=e=>{let t=p([]);for(let n of e)if(n.isErr()){t=m(n.error);break}else t.map(e=>e.push(n.value));return t},re=e=>l.fromSafePromise(Promise.all(e)).andThen(ne),ie=e=>{let t=p([]);for(let n of e)n.isErr()&&t.isErr()?t.error.push(n.error):n.isErr()&&t.isOk()?t=m([n.error]):n.isOk()&&t.isOk()&&t.value.push(n.value);return t},ae=e=>l.fromSafePromise(Promise.all(e)).andThen(ie);e.Result=void 0,(function(e){function t(e,t){return(...n)=>{try{return p(e(...n))}catch(e){return m(t?t(e):e)}}}e.fromThrowable=t;function n(e){return ne(e)}e.combine=n;function r(e){return ie(e)}e.combineWithAllErrors=r})(e.Result||={});function p(e){return new h(e)}function m(e){return new g(e)}function oe(e){let t=e().next();return t instanceof Promise?new l(t.then(e=>e.value)):t.value}var h=class{constructor(e){this.value=e}isOk(){return!0}isErr(){return!this.isOk()}map(e){return p(e(this.value))}mapErr(e){return p(this.value)}andThen(e){return e(this.value)}andThrough(e){return e(this.value).map(e=>this.value)}andTee(e){try{e(this.value)}catch{}return p(this.value)}orTee(e){return p(this.value)}orElse(e){return p(this.value)}asyncAndThen(e){return e(this.value)}asyncAndThrough(e){return e(this.value).map(()=>this.value)}asyncMap(e){return l.fromSafePromise(e(this.value))}unwrapOr(e){return this.value}match(e,t){return e(this.value)}safeUnwrap(){let e=this.value;return(function*(){return e})()}_unsafeUnwrap(e){return this.value}_unsafeUnwrapErr(e){throw n("Called `_unsafeUnwrapErr` on an Ok",this,e)}*[Symbol.iterator](){return this.value}},g=class{constructor(e){this.error=e}isOk(){return!1}isErr(){return!this.isOk()}map(e){return m(this.error)}mapErr(e){return m(e(this.error))}andThrough(e){return m(this.error)}andTee(e){return m(this.error)}orTee(e){try{e(this.error)}catch{}return m(this.error)}andThen(e){return m(this.error)}orElse(e){return e(this.error)}asyncAndThen(e){return u(this.error)}asyncAndThrough(e){return u(this.error)}asyncMap(e){return u(this.error)}unwrapOr(e){return e}match(e,t){return t(this.error)}safeUnwrap(){let e=this.error;return(function*(){throw yield m(e),Error("Do not use this generator out of `safeTry`")})()}_unsafeUnwrap(e){throw n("Called `_unsafeUnwrap` on an Err",this,e)}_unsafeUnwrapErr(e){return this.error}*[Symbol.iterator](){let e=this;return yield e,e}};let se=e.Result.fromThrowable;e.Err=g,e.Ok=h,e.ResultAsync=l,e.err=m,e.errAsync=u,e.fromAsyncThrowable=te,e.fromPromise=d,e.fromSafePromise=f,e.fromThrowable=se,e.ok=p,e.okAsync=ee,e.safeTry=oe}))();const xl=`root`,Sl=e=>{let t=null;for(let n of e){if(t===null){t=n;continue}let e=Math.min(t.x,n.x),r=Math.min(t.y,n.y);t={x:e,y:r,width:Math.max(t.x+t.width,n.x+n.width)-e,height:Math.max(t.y+t.height,n.y+n.height)-r}}return t},Cl=e=>{let t=new Map;for(let[n,r]of Object.entries(e.relationships)){let e=t.get(r.parentId),i={id:n,sortKey:r.sortKey};e===void 0?t.set(r.parentId,[i]):e.push(i)}return new Map([...t].map(([e,t])=>[e,t.toSorted((e,t)=>e.sortKey===t.sortKey?e.id.localeCompare(t.id):e.sortKey.localeCompare(t.sortKey)).map(e=>e.id)]))},Z=e=>(0,X.err)(`stored canvas document is not renderable: ${e}`),wl=e=>{if(e.nodes[xl]?.id!==xl)return Z(`the root node is missing`);for(let[t,n]of Object.entries(e.nodes))if(t!==n.id)return Z(`node map key does not match ${n.id}`);return(0,X.ok)(void 0)},Tl=e=>{for(let[t,n]of Object.entries(e.relationships)){if(t===xl||e.nodes[t]===void 0)return Z(`relationship names an unknown child ${t}`);if(e.nodes[n.parentId]===void 0)return Z(`relationship names an unknown parent ${n.parentId}`)}return(0,X.ok)(void 0)},El=e=>{for(let t of Object.keys(e.nodes)){let n=new Set,r=t;for(;r!==void 0&&r!==xl;){if(n.has(r))return Z(`relationship cycle reaches ${r}`);n.add(r),r=e.relationships[r]?.parentId}if(r!==xl)return Z(`node ${t} is detached from root`)}return(0,X.ok)(void 0)},Dl=e=>wl(e).andThen(()=>Tl(e)).andThen(()=>El(e)),Ol=e=>{let t=new Map,n=r=>{let i=t.get(r);if(i!==void 0)return i;let a=e.nodes[r]?.box,o=e.relationships[r]?.parentId,s=o===void 0?{x:0,y:0}:n(o),c={x:s.x+(a?.x??0),y:s.y+(a?.y??0)};return t.set(r,c),c},r=new Map;for(let[t,i]of Object.entries(e.nodes))i.box!==void 0&&r.set(t,{...i.box,...n(t)});return r},kl=e=>{let t=Object.keys(e).length===0?gt():e,n=ht.safeParse(t);if(!n.success)return Z(`its scene shape is invalid`);let r=Dl(n.data);if(r.isErr())return(0,X.err)(r.error);let i=n.data,a=Cl(i),o=Ol(i),s=Object.values(i.nodes).map(e=>({id:e.id,label:e.label,kind:e.component,parentId:i.relationships[e.id]?.parentId??null,childCount:a.get(e.id)?.length??0,box:o.get(e.id)??null,propertySections:[...Rn(e.component)]})).toSorted((e,t)=>e.id.localeCompare(t.id)),c={};for(let e of s)e.id!==xl&&(c[e.kind]=(c[e.kind]??0)+1);return(0,X.ok)({document:i,nodes:s,children:a,bounds:Sl(s.flatMap(e=>e.box===null?[]:[e.box])),kinds:c})},Al=async(e,t)=>{let n=J(await e.readCanvas.execute(t));return{source:n,projected:J(kl(n.document).mapErr(e=>L(`INTERNAL`,e)))}},jl=e=>({inspect:G.input(Dn).output(On).query(async({input:t})=>{let{source:n,projected:r}=await Al(e,t.canvasId);return{canvasId:t.canvasId,title:n.title,version:n.version,nodeCount:Math.max(0,r.nodes.length-1),rootChildCount:r.children.get(`root`)?.length??0,bounds:r.bounds,kinds:r.kinds,next:[`enhance canvas tree --canvas ${t.canvasId}`,`enhance canvas render --canvas ${t.canvasId} --expected-version ${String(n.version)}`]}}),tree:G.input(kn).output(An).query(async({input:t})=>{let{source:n,projected:r}=await Al(e,t.canvasId);return{canvasId:t.canvasId,version:n.version,nodes:[...r.nodes]}}),node:G.input(jn).output(Mn).query(async({input:t})=>{let{source:n,projected:r}=await Al(e,t.canvasId),i=r.nodes.find(e=>e.id===t.nodeId),a=r.document.nodes[t.nodeId],o=J(i===void 0||a===void 0?(0,X.err)(L(`NOT_FOUND`,`no such canvas node`)):(0,X.ok)({summary:i,node:a}));return{canvasId:t.canvasId,version:n.version,node:{...o.summary,styles:o.node.styles,...o.node.layout!==void 0&&{layout:o.node.layout},...o.node.appearance!==void 0&&{appearance:o.node.appearance},...o.node.typography!==void 0&&{typography:o.node.typography},...o.node.additionalStyles!==void 0&&{additionalStyles:o.node.additionalStyles},props:o.node.props??{},children:[...r.children.get(t.nodeId)??[]]},next:[`enhance canvas render --canvas ${t.canvasId} --node-id ${t.nodeId} --expected-version ${String(n.version)}`]}})}),Ml=(e,t)=>e.expiresAt<=t,Nl=(e,t)=>({inviteId:e.id,email:e.email,accessLevel:e.accessLevel,sendCount:e.sendCount,lastSentAt:e.lastSentAt.toISOString(),expiresAt:e.expiresAt.toISOString(),state:Ml(e,t)?`expired`:`pending`,deliveryState:e.deliveryState,deliveryError:e.deliveryError??``}),Pl=(e,t)=>nl.input(ei).output(ti).mutation(async({input:n,ctx:r})=>{let i=J(await e.createInvite.execute({...n,invitedByPersonId:r.viewer.personId}));return r.telemetry.emit(`InviteCreated`,{canvasId:n.canvasId,accessLevel:n.accessLevel}),{invite:Nl(i.invite,new Date),...t&&{acceptToken:i.token}}}),Fl=e=>U.input(si).output(li).mutation(async({input:t,ctx:n})=>{let r=J((await n.verifiedEmails()).mapErr(e=>R(e.message))),i=J(await e.acceptInvite.execute({token:t.token,personId:n.viewer.personId,personEmails:r}));return n.telemetry.emit(`InviteAccepted`,{canvasId:i.canvasId,accessLevel:i.accessLevel}),i}),Il=(e,t=!1)=>z({create:Pl(e,t),accept:Fl(e),preview:H.input(ci).output($r).query(async({input:t})=>{let n=J(await e.previewInvite.execute(t));return{...n,expiresAt:n.expiresAt.toISOString()}}),list:q.input(ni).output(ri).query(async({input:t})=>{let n=new Date;return{items:J(await e.listInvites.execute(t)).map(e=>Nl(e,n)),truncated:!1}}),revoke:q.input(ii).output(ii.pick({inviteId:!0})).mutation(async({input:t})=>J(await e.revokeInvite.execute(t))),resend:q.input(ai).output(ti).mutation(async({input:n})=>{let r=J(await e.resendInvite.execute(n));return{invite:Nl(r.invite,new Date),...t&&{acceptToken:r.token}}})}),Ll=e=>U.input(pe).output(me).mutation(async({input:t,ctx:n})=>{let r=J(await e.remove.execute({...t,personId:n.viewer.personId}));return n.telemetry.emit(`CanvasSoftDeleted`,{canvasId:r.canvasId,threadCount:r.threadCount}),{canvasId:r.canvasId,deletedAt:r.deletedAt.toISOString()}}),Rl=e=>z({delete:Ll(e),move:q.input(he).output(ge).mutation(async({input:t,ctx:n})=>({canvas:Y(J(await e.move.execute({...t,organisationId:t.organisationId===`personal`?null:t.organisationId,personId:n.viewer.personId})))})),duplicate:q.input(_e).output(ve).mutation(async({input:t,ctx:n})=>({canvas:Y(J(await e.duplicate.execute({...t,organisationId:t.organisationId===`personal`?null:t.organisationId,personId:n.viewer.personId})))})),deletePermanently:U.input(ye).output(be).mutation(async({input:t,ctx:n})=>J(await e.removePermanently.execute({...t,personId:n.viewer.personId}))),restore:U.input(Te).output(Ee).mutation(async({input:t,ctx:n})=>J(await e.restore.execute({canvasId:t.canvasId,personId:n.viewer.personId})))}),zl=e=>({personId:e.personId,email:e.email,displayName:e.displayName,initials:e.initials,avatarUrl:e.avatarUrl,accessLevel:e.accessLevel,isPending:e.isPending,reviewState:e.reviewState,lastViewedAt:e.lastViewedAt?.toISOString()??null}),Bl=e=>z({list:q.input(di).output(fi).query(async({input:t})=>({items:J(await e.listParticipants.execute(t)).map(e=>zl(e)),truncated:!1})),setAccess:q.input(pi).output(pi.pick({personId:!0,accessLevel:!0})).mutation(async({input:t})=>(J(await e.setParticipantAccess.execute(t)),{personId:t.personId,accessLevel:t.accessLevel})),revoke:q.input(mi).output(hi).mutation(async({input:t})=>J(await e.revokeParticipant.execute(t)))}),Vl=15e3,Hl=e=>{if(e.kind!==`agent`)throw TypeError(`agent canvas procedure did not narrow its viewer`);let t=al(e);if(t.kind!==`agent`)throw TypeError(`agent canvas procedure did not narrow its viewer`);return{...t,tokenId:e.tokenId}},Ul=(e,t)=>{if(!(t||e===`reading`||e===`rendering`))throw V(L(`FORBIDDEN`,`this canvas is read-only for you`))},Wl=e=>z({begin:G.input(yr).output(br).mutation(async({input:t,ctx:n})=>{if(n.viewer.kind!==`agent`)throw TypeError(`agent identity was not narrowed`);Ul(t.phase,n.canvasAccess.canComment);let r=J(await e.begin({...t,actor:Hl(n.viewer)}));return{activityId:r.activityId,expiresAt:r.expiresAt.toISOString(),renewAfterMs:Vl}}),renew:G.input(xr).output(br).mutation(async({input:t,ctx:n})=>{if(n.viewer.kind!==`agent`)throw TypeError(`agent identity was not narrowed`);Ul(t.phase,n.canvasAccess.canComment);let r=J(await e.renew({...t,actor:Hl(n.viewer)}));return{activityId:r.activityId,expiresAt:r.expiresAt.toISOString(),renewAfterMs:Vl}}),end:G.input(Sr).output(Cr).mutation(async({input:t,ctx:n})=>{if(n.viewer.kind!==`agent`)throw TypeError(`agent identity was not narrowed`);return J(await e.end({...t,tokenId:n.viewer.tokenId})),{ended:!0}})}),Gl=(e,t)=>z({ticket:W.input(_r).output(vr).mutation(async({input:n,ctx:r})=>{let i=J(await e.issueRealtimeTicket.execute({canvasId:n.canvasId,viewer:r.viewer}));return{endpoint:t,ticket:i.ticket,protocol:rr,expiresAt:i.expiresAt.toISOString()}}),activity:Wl(e.activity)}),Kl=`root`,ql=(e,t)=>{let n=t=>{if(t===Kl)return Kl;let n=t,r=new Set;for(;n!==Kl;){if(r.has(n))return null;r.add(n);let t=e.relationships[n]?.parentId;if(t===void 0)return null;if(t===Kl)return n;n=t}return Kl},r=new Set(t.flatMap(e=>n(e)??[]));return r.size===0?null:r.size===1?r.values().next().value??null:Kl},Jl=(e,t,n)=>[`enhance canvas tree --canvas ${e}`,`enhance canvas render --canvas ${e} --expected-version ${String(t)}`,...n.map(t=>`enhance canvas node --canvas ${e} --node-id ${t}`)].slice(0,12),Yl=(e,t,n)=>kl(t.document).map(r=>{let i=new Map(r.nodes.map(e=>[e.id,e])),a=n?.selectedNodeIds??[],o=a.flatMap(e=>{let t=i.get(e);return t===void 0?[]:[t]}),s=new Set(o.map(e=>e.id)),c=a.filter(e=>!s.has(e));return{canvasId:e,status:n===null?`offline`:a.length===0?`none`:o.length===0?`stale`:`selected`,documentVersion:t.version,selectionRevision:n?.selectionRevision??null,selectionChangedAt:n?.selectionChangedAt?.toISOString()??null,selectedNodeIds:[...a],missingNodeIds:c,nodes:o,contextRootId:ql(r.document,o.map(e=>e.id)),visibleWorldBox:n?.visibleWorldBox??null,next:Jl(e,t.version,o.map(e=>e.id))}}),Xl=(e,t)=>G.input(Mr).output(Nr).query(async({input:n,ctx:r})=>{if(r.viewer.kind!==`agent`)throw TypeError(`agent identity was not narrowed`);let[i,a]=await Promise.all([e.execute({canvasId:n.canvasId,personId:r.viewer.personId}),t.execute(n.canvasId)]);return J(Yl(n.canvasId,J(a),J(i)).mapErr(e=>L(`INTERNAL`,e)))}),Zl=W.input(re).output(ie).mutation(({input:e,ctx:t})=>(t.logger.warn({event:`ThumbnailBlobUnavailable`,canvasId:e.canvasId,blobId:e.thumbnailId,clientReleaseIdentity:e.clientReleaseIdentity,attemptedOperation:e.attemptedOperation,recoveryOutcome:e.recoveryOutcome},`event`),{recorded:!0})),Ql=()=>z({reportUnavailable:Zl}),$l=e=>e.kind===`agent`?{kind:`agent`,personId:e.personId,displayName:e.displayName,initials:e.initials,tokenLabel:e.tokenLabel??`Agent`}:{kind:`person`,personId:e.personId,displayName:e.displayName,initials:e.initials},eu=e=>({id:e.id,canvasId:e.canvasId,documentVersion:e.documentVersion,origin:e.origin,restoreRole:e.restoreRole,retention:e.retention,title:e.title,description:e.description,actor:e.actor,sourceVersionEntryId:e.sourceVersionEntryId,expiresAt:e.expiresAt?.toISOString()??null,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),screenCount:e.screenCount}),tu=e=>({screenId:e.screenId,route:e.route,title:e.title,viewport:e.viewport,atMs:e.atMs,sourceRecordingId:e.sourceRecordingId,assetBundle:e.assetBundle===null?null:{...e.assetBundle,assets:[...e.assetBundle.assets]},download:e.download===null?null:{url:e.download.url,expiresAt:e.download.expiresAt.toISOString(),bytes:e.download.bytes}}),nu=e=>{if(!e.canSeeRoutes||e.viewerKind===`anonymous`||e.viewerKind===`render`)throw V(L(`NOT_FOUND`,`no such canvas`))},ru=e=>W.input(Lr).output(Rr).query(async({input:t,ctx:n})=>{if(nu({canSeeRoutes:n.canvasAccess.canSeeRoutes,viewerKind:n.viewer.kind}),n.viewer.kind===`anonymous`||n.viewer.kind===`render`)throw V(L(`NOT_FOUND`,`no such canvas`));let r=J(await e.versions.list({...t,personId:n.viewer.personId}));return n.telemetry.emit(`CanvasVersionListServed`,{entryCount:r.items.length,automaticIncluded:+!!t.includeAutomatic,hasMore:r.nextCursor===null?0:1}),{current:{documentVersion:r.current.documentVersion,updatedAt:r.current.updatedAt.toISOString()},items:r.items.map(e=>eu(e)),nextCursor:r.nextCursor,hasExpiredHistory:r.hasExpiredHistory}}),iu=e=>W.input(zr).output(Hr).query(async({input:t,ctx:n})=>{nu({canSeeRoutes:n.canvasAccess.canSeeRoutes,viewerKind:n.viewer.kind});let r=J(await e.versions.get({...t,withRoutes:n.canvasAccess.canSeeRoutes}));return r.outcome===`corrupt`?{outcome:r.outcome,entry:eu(r.entry)}:r.outcome===`ready`?{outcome:`ready`,entry:eu(r.entry),document:r.document,screens:r.screens.map(e=>tu(e))}:{outcome:`missing-resources`,entry:eu(r.entry),document:r.document,screens:r.screens.map(e=>tu(e)),missingScreenIds:[...r.missingScreenIds]}}),au=e=>K.input(Wr).output(qr).mutation(async({input:t,ctx:n})=>(nu({canSeeRoutes:n.canvasAccess.canSeeRoutes,viewerKind:n.viewer.kind}),{entry:eu(J(await e.versions.name({...t,actor:$l(n.viewer),canManageAllMetadata:n.canvasAccess.canManage})))})),ou=e=>K.input(Gr).output(qr).mutation(async({input:t,ctx:n})=>(nu({canSeeRoutes:n.canvasAccess.canSeeRoutes,viewerKind:n.viewer.kind}),{entry:eu(J(await e.versions.name({canvasId:t.canvasId,target:{kind:`version`,versionId:t.versionId},title:t.title,description:t.description,actor:$l(n.viewer),canManageAllMetadata:n.canvasAccess.canManage})))})),su=e=>K.input(Kr).output(qr).mutation(async({input:t,ctx:n})=>(nu({canSeeRoutes:n.canvasAccess.canSeeRoutes,viewerKind:n.viewer.kind}),{entry:eu(J(await e.versions.removeName({...t,requesterPersonId:n.viewer.personId,canManageAllMetadata:n.canvasAccess.canManage})))})),cu=e=>K.input(Jr).output(Yr).mutation(async({input:t,ctx:n})=>{if(nu({canSeeRoutes:n.canvasAccess.canSeeRoutes,viewerKind:n.viewer.kind}),n.viewer.kind!==`person`)throw V(L(`FORBIDDEN`,`an agent cannot restore canvas history`));let r=J(await e.versions.restore({...t,actor:$l(n.viewer)}));return n.telemetry.emit(`CanvasVersionRestored`,{documentVersion:r.version,outcome:`restored`}),r}),lu=e=>q.input(Xr).output(Zr).mutation(async({input:t,ctx:n})=>{if(n.viewer.kind!==`person`)throw V(L(`FORBIDDEN`,`an agent cannot duplicate canvas history`));return J(await e.versions.duplicate({...t,personId:n.viewer.personId,organisationId:t.organisationId===`personal`?null:t.organisationId}))}),uu=e=>z({list:ru(e),get:iu(e),name:au(e),updateMetadata:ou(e),removeName:su(e),restore:cu(e),duplicate:lu(e)}),du=e=>`rootNodeId`in e,fu=e=>`storageKey`in e,pu=(e,t)=>({canvasId:e.canvasId,requestedVersion:e.requestedVersion,loadedVersion:t.loadedVersion,target:e.target,...t.sourceState!==null&&t.sourceState!==void 0&&{sourceState:t.sourceState},bounds:t.bounds,width:t.width,height:t.height,scale:t.scale,contentType:t.contentType,bytes:t.bytes,warnings:[...t.warnings],timings:[...t.timings],...t.snapshot!==null&&t.snapshot!==void 0&&{snapshot:t.snapshot},expiresAt:t.expiresAt.toISOString()}),mu=e=>({...e,idMap:{...e.idMap},insertedNodeIds:[...e.insertedNodeIds],removedNodeIds:[...e.removedNodeIds],boxes:{...e.boxes},affectedBounds:{...e.affectedBounds},report:{...e.report,issues:[...e.report.issues]}}),hu=e=>{let t=e.conversionRequest?.source;return t?.kind===`screen`?t:{kind:`html`,label:t?.label??``}},gu=e=>{if(e.purpose===`conversion`)return null;let t=e.purpose,n={id:e.id,canvasId:e.canvasId,purpose:t,phase:e.phase,requestedVersion:e.requestedVersion,target:e.target,...e.sourceState!==null&&e.sourceState!==void 0&&{sourceState:e.sourceState},scale:e.requestedScale,format:`png`,attempt:e.attempt,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()};return e.state===`succeeded`&&e.result!==null&&fu(e.result)?{...n,state:`succeeded`,phase:`complete`,result:pu(e,e.result),failure:null}:e.state===`failed`&&e.failure!==null?{...n,state:`failed`,result:null,failure:e.failure}:e.state===`cancelled`&&e.failure?.reason===`CANCELLED`?{...n,state:`cancelled`,result:null,failure:{...e.failure,reason:`CANCELLED`}}:e.state===`expired`&&e.failure?.reason===`EXPIRED`?{...n,state:`expired`,result:null,failure:{...e.failure,reason:`EXPIRED`}}:e.state===`running`?{...n,state:`running`,result:null,failure:null}:e.state===`queued`?{...n,state:`queued`,result:null,failure:null}:null},_u=e=>{if(e.purpose!==`conversion`||e.target.kind!==`node`||e.conversionRequest===null||e.conversionRequest===void 0)return null;let t={id:e.id,canvasId:e.canvasId,source:hu(e),destination:e.conversionRequest.destination,phase:e.phase,requestedVersion:e.requestedVersion,attempt:e.attempt,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()};return e.state===`succeeded`&&e.result!==null&&du(e.result)?{...t,state:`succeeded`,phase:`complete`,result:mu(e.result),failure:null}:e.state===`failed`&&e.failure!==null?{...t,state:`failed`,result:null,failure:e.failure}:e.state===`cancelled`&&e.failure?.reason===`CANCELLED`?{...t,state:`cancelled`,result:null,failure:{...e.failure,reason:`CANCELLED`}}:e.state===`expired`&&e.failure?.reason===`EXPIRED`?{...t,state:`expired`,result:null,failure:{...e.failure,reason:`EXPIRED`}}:e.state===`running`?{...t,state:`running`,result:null,failure:null}:e.state===`queued`?{...t,state:`queued`,result:null,failure:null}:null},Q=e=>ol(e)??J((0,X.err)(L(`UNAUTHORIZED`,`this call needs an agent token`))),vu=e=>gu(e)??J((0,X.err)(L(`INTERNAL`,`render outcome is incomplete`))),yu=e=>_u(e)??J((0,X.err)(L(`INTERNAL`,`primitive import outcome is incomplete`))),bu=(e,t)=>t===`conversion`==(e.purpose===`conversion`)?e:J((0,X.err)(L(`NOT_FOUND`,`no such ${t}`))),xu=e=>G.input(zt).output(Jt).mutation(async({input:t,ctx:n})=>{let r=Q(n.viewer),i=J(await e.create.execute({canvasId:t.canvasId,purpose:`inspection`,expectedVersion:t.expectedVersion,target:t.target,sourceState:t.sourceState??null,scale:t.scale,requesterPersonId:r.personId,requesterTokenId:r.tokenId,idempotencyKey:n.idempotencyKey}));return{job:vu(i.job),alreadyExists:i.alreadyExists}}),Su=e=>Zc.input(Yt).output(Xt).query(async({input:t,ctx:n})=>{let r=J(await e.get.execute({jobId:t.jobId,actor:Q(n.viewer)}));return{job:vu(bu(r,`render`))}}),Cu=e=>tl.input(tn).output(nn).mutation(async({input:t,ctx:n})=>{let r=Q(n.viewer),i=J(await e.create.execute({canvasId:t.canvasId,purpose:`snapshot`,expectedVersion:void 0,target:{kind:`node`,nodeId:`rec_${t.recordingId}`},sourceState:{kind:`recording`,recordingId:t.recordingId,atMs:t.atMs},scale:1,requesterPersonId:r.personId,requesterTokenId:r.tokenId,idempotencyKey:n.idempotencyKey}));return{job:vu(i.job),alreadyExists:i.alreadyExists}}),wu=e=>tl.meta({description:`Import one source through the canonical editable-primitives compiler.`}).input(un).output(dn).mutation(async({input:t,ctx:n})=>{let r=Q(n.viewer),i=t.source.kind===`screen`?t.source.nodeId:t.destination.kind===`adjacent`?J((0,X.err)(L(`BAD_REQUEST`,`authored HTML requires a destination`))):t.destination.targetNodeId,a=J(await e.create.execute({canvasId:t.canvasId,purpose:`conversion`,expectedVersion:t.expectedVersion,target:{kind:`node`,nodeId:i},sourceState:null,conversionRequest:{source:t.source,destination:t.destination},scale:1,requesterPersonId:r.personId,requesterTokenId:r.tokenId,requesterActor:r.mutationActor,idempotencyKey:n.idempotencyKey}));return{job:yu(a.job),alreadyExists:a.alreadyExists}}),Tu=e=>Zc.meta({description:`Inspect the progress or committed result of a primitive import.`}).input(fn).output(pn).query(async({input:t,ctx:n})=>{let r=bu(J(await e.get.execute({jobId:t.jobId,actor:Q(n.viewer)})),`conversion`);return{job:yu(r)}}),Eu=e=>Zc.meta({description:`Cancel a queued primitive import before compilation begins.`}).input(mn).output(hn).mutation(async({input:t,ctx:n})=>{let r=Q(n.viewer),i=J(await e.get.execute({jobId:t.jobId,actor:r}));bu(i,`conversion`);let a=J(await e.cancel.execute({jobId:t.jobId,actor:r}));return{job:yu(a)}}),Du=e=>Zc.input(Zt).output(Qt).mutation(async({input:t,ctx:n})=>{let r=Q(n.viewer),i=J(await e.get.execute({jobId:t.jobId,actor:r}));return bu(i,`render`),{job:vu(J(await e.cancel.execute({jobId:t.jobId,actor:r})))}}),Ou=e=>Zc.input($t).output(en).query(async({input:t,ctx:n})=>{let r=J(await e.download.execute({jobId:t.jobId,actor:Q(n.viewer)}));return{jobId:t.jobId,download:{url:r.url,expiresAt:r.expiresAt.toISOString(),bytes:r.bytes}}}),ku=e=>z({create:xu(e),snapshot:Cu(e),importSource:wu(e),getImport:Tu(e),cancelImport:Eu(e),get:Su(e),cancel:Du(e),download:Ou(e)}),Au=e=>z({exposure:Qc.input(wr).output(Er).query(async({input:t,ctx:n})=>{let r=J(await e.expose.execute({jobId:n.viewer.jobId,canvasId:n.viewer.canvasId,requestedVersion:n.viewer.requestedVersion}));return t.jobId===r.id?r.purpose===`conversion`?r.target.kind!==`node`||r.conversionRequest===null||r.conversionRequest===void 0?J((0,X.err)(L(`INTERNAL`,`a conversion job has no source request`))):{jobId:r.id,canvasId:r.canvasId,requestedVersion:r.requestedVersion,purpose:`conversion`,target:r.target,conversion:r.conversionRequest,scale:1,format:`json`}:{jobId:r.id,canvasId:r.canvasId,requestedVersion:r.requestedVersion,purpose:r.purpose,target:r.target,...r.sourceState!==null&&r.sourceState!==void 0&&{sourceState:r.sourceState},scale:r.requestedScale,format:`png`}:J((0,X.err)(L(`NOT_FOUND`,`no such render`)))})}),ju=e=>Math.min(1,Math.max(0,e)),Mu=e=>e.target??(e.element===null?null:{version:1,kind:`element`,locator:e.element,attachment:{x:.5,y:.5},fallbackBounds:{x:ju(e.point.x),y:ju(e.point.y),width:0,height:0}}),Nu=e=>{if(e.on===`canvas`)return{on:`canvas`,point:e.point};if(e.on===`node`)return{on:`node`,nodeId:e.nodeId,point:e.point,element:null};let t=Mu(e);return{on:`screen`,nodeId:e.nodeId,screenId:e.screenId,point:e.point,element:e.element,...t!==null&&{target:t}}},Pu=(e,t)=>({kind:e.authorKind,personId:e.authorPersonId,name:e.authorName,initials:e.authorInitials,avatarUrl:t(e.authorPersonId).avatarUrl,tokenLabel:e.authorTokenLabel}),Fu=(e,t)=>{let n=new Map;for(let t of e.reactions){let e=n.get(t.emoji)??[];e.push(t.personId),n.set(t.emoji,e)}return[...n].map(([e,n])=>({emoji:e,people:n.map(e=>({personId:e,name:t(e).displayName}))}))},Iu=(e,t)=>{let[n]=e.messages;return{threadId:e.thread.id,canvasId:e.thread.canvasId,anchor:Nu(e.thread.anchor),author:Pu(n,t),messages:e.messages.map(e=>({messageId:e.id,seq:e.seq,body:e.deletedAt===null?e.body:`(deleted)`,author:Pu(e,t),createdAt:e.createdAt.toISOString(),editedAt:e.editedAt?.toISOString()??null,mentions:e.mentionedPersonIds.map(e=>({personId:e,name:t(e).displayName})),reactions:Fu(e,t)})),messageCount:e.thread.messageCount,hasMoreMessages:e.thread.messageCount>e.messages.length,isResolved:e.thread.resolvedAt!==null,resolvedAt:e.thread.resolvedAt?.toISOString()??null,resolvedBy:e.thread.resolvedByPersonId===null?null:{kind:e.thread.resolvedByTokenId===null?`person`:`agent`,personId:e.thread.resolvedByPersonId,name:t(e.thread.resolvedByPersonId).displayName,tokenLabel:e.thread.resolvedByTokenLabel},createdAt:e.thread.createdAt.toISOString(),lastMessageAt:e.thread.lastMessageAt.toISOString()}},Lu=e=>e.kind===`agent`?{tokenId:e.tokenId,tokenLabel:e.tokenLabel}:{tokenId:null,tokenLabel:null},Ru=e=>({kind:e.kind,personId:e.personId,...Lu(e),name:e.displayName,initials:e.initials}),zu=e=>{let t=e.on===`screen`?e.element:null;return t===null?{hasElementAnchor:0,anchorHasSource:0,selectorDepth:0}:{hasElementAnchor:1,anchorHasSource:t.source===null?0:1,selectorDepth:t.selector.split(`>`).length}},Bu=async(e,t)=>{let n=new Set;for(let e of t){e.thread.resolvedByPersonId!==null&&n.add(e.thread.resolvedByPersonId);for(let t of e.messages){n.add(t.authorPersonId);for(let e of t.mentionedPersonIds)n.add(e);for(let e of t.reactions)n.add(e.personId)}}let r=J(await e.read([...n])),i=new Map(r.map(e=>[e.personId,{displayName:e.displayName,avatarUrl:e.avatarUrl}]));return e=>{let t=i.get(e);if(t===void 0)throw V(R(`comment names person ${e}, who was not found`));return t}},Vu=async(e,t)=>Iu(t,await Bu(e,[t])),Hu=e=>W.input(ji).output(Mi).query(async({input:t,ctx:n})=>{if(!n.canvasAccess.canSeeComments)return{items:[],truncated:!1};let r=J(await e.list.execute(t)),i=await Bu(e.people,r.items);return{items:r.items.map(e=>Iu(e,i)),truncated:r.truncated}}),Uu=e=>K.input(Ni).output(j).mutation(async({input:t,ctx:n})=>{let r=J(await e.start.execute({canvasId:t.canvasId,clientThreadId:t.clientThreadId,anchor:t.anchor,body:t.body,mentionedPersonIds:t.mentionedPersonIds,author:Ru(n.viewer),mintMembership:n.canvasAccess.accessLevel===null}));return n.telemetry.emit(`CommentThreadStarted`,{canvasId:t.canvasId,threadId:r.thread.id,anchorKind:t.anchor.on,...zu(t.anchor),bodyLength:t.body.length}),Vu(e.people,r)}),Wu=e=>K.input(Ri).output(j).mutation(async({input:t,ctx:n})=>{let r=J(await e.resolve.execute({...t,personId:n.viewer.personId,...Lu(n.viewer)}));return r.changed&&t.resolved&&n.telemetry.emit(`CommentThreadResolved`,{canvasId:t.canvasId,threadId:r.thread.id,resolvedByKind:n.viewer.kind,secondsSinceFirstMessage:Math.round((r.thread.lastMessageAt.getTime()-r.thread.createdAt.getTime())/1e3)}),Vu(e.people,r)}),Gu=e=>z({list:Hu(e),start:Uu(e),resolve:Wu(e),react:K.input(Ii).output(j).mutation(async({input:t,ctx:n})=>Vu(e.people,J(await e.react.execute({...t,personId:n.viewer.personId})))),reply:K.input(Pi).output(j).mutation(async({input:t,ctx:n})=>{let r=J(await e.reply.execute({...t,author:Ru(n.viewer),isGuest:n.canvasAccess.accessLevel===null}));return n.telemetry.emit(`CommentReplied`,{canvasId:t.canvasId,threadId:r.thread.id,messageIndex:r.thread.messageCount}),Vu(e.people,r)}),edit:K.input(Fi).output(j).mutation(async({input:t,ctx:n})=>Vu(e.people,J(await e.edit.execute({...t,personId:n.viewer.personId})))),move:K.input(Li).output(j).mutation(async({input:t})=>Vu(e.people,J(await e.move.execute(t)))),delete:K.input(zi).output(Bi).mutation(async({input:t,ctx:n})=>J(await e.remove.execute({...t,personId:n.viewer.personId,canManage:n.canvasAccess.canManage})))}),Ku=e=>z({list:U.input(Ui).output(Wi).query(async({ctx:t})=>({items:J(await e.list.execute({personId:t.viewer.personId})),truncated:!1})),create:U.input(Gi).output(Ki).mutation(async({input:t,ctx:n})=>({organisation:J(await e.create.execute({name:t.name,personId:n.viewer.personId}))})),update:U.input(qi).output(Ki).mutation(async({input:t,ctx:n})=>({organisation:J(await e.update.execute({...t,personId:n.viewer.personId}))})),delete:U.input(Ji).output(Yi).mutation(async({input:t,ctx:n})=>J(await e.remove.execute({...t,personId:n.viewer.personId})))}),qu=(e,t)=>({inviteId:e.id,email:e.email,role:e.role,sendCount:e.sendCount,lastSentAt:e.lastSentAt.toISOString(),expiresAt:e.expiresAt.toISOString(),state:e.expiresAt<=t?`expired`:`pending`,deliveryState:e.deliveryState,deliveryError:e.deliveryError??``}),Ju=e=>U.input(ca).output(la).mutation(async({input:t,ctx:n})=>{let r=J(await e.createInvite.execute({...t,invitedByPersonId:n.viewer.personId}));return r.kind===`member`?r:{kind:`invitation`,invite:qu(r.invite,new Date)}}),Yu=e=>U.input(da).output(fa).query(async({input:t,ctx:n})=>({items:J(await e.listInvites.execute({...t,personId:n.viewer.personId})).map(e=>qu(e,new Date)),truncated:!1})),Xu=e=>U.input(pa).output(pa.pick({inviteId:!0})).mutation(async({input:t,ctx:n})=>J(await e.revokeInvite.execute({...t,personId:n.viewer.personId}))),Zu=e=>U.input(ma).output(ua).mutation(async({input:t,ctx:n})=>({invite:qu(J(await e.resendInvite.execute({...t,personId:n.viewer.personId})),new Date)})),Qu=e=>H.input(ga).output(va).query(async({input:t})=>{let n=J(await e.previewInvite.execute(t));return{...n,expiresAt:n.expiresAt.toISOString()}}),$u=e=>U.input(_a).output(ya).mutation(async({input:t,ctx:n})=>{let r=J((await n.verifiedEmails()).mapErr(e=>R(e.message)));return J(await e.acceptInvite.execute({...t,personId:n.viewer.personId,personEmails:r}))}),ed=e=>z({create:Ju(e),list:Yu(e),revoke:Xu(e),resend:Zu(e),preview:Qu(e),accept:$u(e)}),td=e=>U.input(Zi).output(Qi).query(async({input:t,ctx:n})=>({items:J(await e.listMembers.execute({organisationId:t.organisationId,personId:n.viewer.personId})),truncated:!1})),nd=e=>U.input($i).output(ea).mutation(async({input:t,ctx:n})=>J(await e.addMember.execute({organisationId:t.organisationId,personId:n.viewer.personId,email:t.email,role:t.role}))),rd=e=>U.input(ta).output(na).mutation(async({input:t,ctx:n})=>J(await e.setMemberRole.execute({...t,actorPersonId:n.viewer.personId}))),id=e=>U.input(ra).output(ia).mutation(async({input:t,ctx:n})=>J(await e.removeMember.execute({...t,actorPersonId:n.viewer.personId}))),ad=e=>U.input(aa).output(oa).mutation(async({input:t,ctx:n})=>J(await e.transferOwnership.execute({organisationId:t.organisationId,personId:n.viewer.personId,toPersonId:t.personId}))),od=e=>z({list:td(e),add:nd(e),setRole:rd(e),remove:id(e),transferOwnership:ad(e)}),sd=e=>{let[t=``,n=``,r=``,i=``,a=``]=e.split(`-`,5);return`${((Number.parseInt(t,16)^1162758195)>>>0).toString(16).padStart(8,`0`)}-${n}-5${r.slice(1)}-a${i.slice(1)}-${a}`},cd=e=>({id:e.id,preparedCanvasId:sd(e.id),displayName:e.displayName,initials:e.initials,avatarUrl:e.avatarUrl,email:e.email,createdAt:e.createdAt.toISOString()}),ld=e=>({id:e.id,label:e.label,createdAt:e.createdAt.toISOString(),lastUsedAt:e.lastUsedAt?.toISOString()??null,expiresAt:e.expiresAt?.toISOString()??null,revoked:e.revokedAt!==null}),ud=e=>({createAgentToken:U.meta({description:`Create an agent credential; the plaintext token is returned only once.`}).input(xa).output(Sa).mutation(async({input:t,ctx:n})=>{let r=J(await e.agentTokens.create({personId:n.viewer.personId,label:t.label,expiresAt:t.expiresAt===null?null:new Date(t.expiresAt)}));return{token:r.plaintext,agentToken:ld(r.token)}}),listAgentTokens:U.meta({description:`List agent credentials so unused or revoked ones can be identified.`}).input(Ca).output(wa).query(async({ctx:t})=>({items:J(await e.agentTokens.list(t.viewer.personId)).map(e=>ld(e))})),revokeAgentToken:U.meta({description:`Revoke an agent credential before its next request.`}).input(Ta).output(Ea).mutation(async({input:t,ctx:n})=>({tokenId:J(await e.agentTokens.revoke({personId:n.viewer.personId,tokenId:t.tokenId})).id,revoked:!0}))}),dd=e=>e.credential.kind===`token`?null:{kind:`oauth-agent`,tokenId:e.tokenId,tokenLabel:e.tokenLabel,clientId:e.credential.clientId,scopes:[...e.credential.scopes],expiresAt:e.credential.expiresAt.toISOString(),resource:e.credential.resource},fd=e=>H.meta({description:`Resolve the current person and authentication kind.`}).input(ka).output(Aa).query(async({ctx:t})=>{let n=t.viewer.kind===`anonymous`||t.viewer.kind===`render`?null:t.viewer.personId,r=n===null?null:await t.verifiedEmails(),i=r===null?[]:J(r.mapErr(e=>R(e.message))),a=J(await e.getMe.execute({personId:n,verifiedEmails:i})),o=a.claimedCanvasIds.length+a.claimedOrganisationIds.length;o>0&&t.telemetry.emit(`InvitationsClaimed`,{claimedCount:o,claimedCanvasCount:a.claimedCanvasIds.length,claimedOrganisationCount:a.claimedOrganisationIds.length});let s=a.person===null?null:cd(a.person);if(t.viewer.kind!==`agent`)return{person:s,authentication:{kind:t.viewer.kind===`render`?`anonymous`:t.viewer.kind}};let c=dd(t.viewer);if(c!==null)return{person:s,authentication:c};let l=J(await e.agentTokens.find({personId:t.viewer.personId,tokenId:t.viewer.tokenId}));if(l===null)throw V(R(`resolved agent token is missing`));return{person:s,authentication:{kind:`agent`,tokenId:l.id,tokenLabel:l.label,expiresAt:l.expiresAt?.toISOString()??null}}}),pd=e=>z({search:U.input(Ua).output(Wa).query(async({input:t,ctx:n})=>({recipients:J(await e.searchRecipients.execute({personId:n.viewer.personId,query:t.query}))})),recent:U.input(Ga).output(Ka).query(async({ctx:t})=>({recipients:J(await e.recentRecipients.execute({personId:t.viewer.personId}))}))}),md=e=>z({...ud(e),signUp:H.meta({description:`Create a local account when no signed-in person exists.`}).input(Fa).output(Ra).mutation(async({input:t,ctx:n})=>{let r=J(await e.signUp.execute(t)),i=n.session.issue(r.person.id,t.deliver);return{person:cd(r.person),preparedCanvasId:r.preparedCanvasId,token:i}}),signIn:H.meta({description:`Start a local session from an existing account.`}).input(Ia).output(La).mutation(async({input:t,ctx:n})=>{let r=J(await e.signIn.execute(t)),i=n.session.issue(r.id,t.deliver);return{person:cd(r),token:i}}),signOut:H.meta({description:`End the browser session attached to this request.`}).input(za).output(Ba).mutation(({ctx:e})=>(e.session.clear(),{signedOut:!0})),me:fd(e),updateDisplayName:U.meta({description:`Change the current person’s name inside Enhance.`}).input(ja).output(Ma).mutation(async({input:t,ctx:n})=>({person:cd(J(await e.updateDisplayName.execute({personId:n.viewer.personId,displayName:t.displayName})))})),recipients:pd(e)}),hd=e=>({personId:e.personId,publisher:{displayName:e.displayName,initials:e.initials,tokenId:e.tokenId,tokenLabel:e.tokenLabel}}),gd=e=>({personId:e.personId,...e.kind===`agent`&&{publisher:{displayName:e.displayName,initials:e.initials,tokenId:e.tokenId,tokenLabel:e.tokenLabel}}}),_d=e=>{if(e.kind!==`agent`)throw TypeError(`agent editor did not narrow its viewer`);return hd(e)},vd=e=>{if(e.kind!==`agent`||e.personId===void 0)throw TypeError(`agent editor did not narrow its viewer`);return e.personId},yd=e=>tl.input(Za).output(Qa).mutation(async({input:t,ctx:n})=>{let r=J(await e.publishing.create({...t,prototypeId:t.prototypeId??null,personId:vd(n.viewer)}));return{prototypeId:r.prototype.id,deploymentId:r.deployment.id,nodeId:r.prototype.nodeId,state:r.deployment.state,alreadyExists:r.alreadyExists,fileCount:r.deployment.fileCount,totalBytes:r.deployment.totalBytes}}),bd=e=>tl.input($a).output(to).mutation(async({input:t,ctx:n})=>{let r=J(await e.upload.reserve({...t,personId:vd(n.viewer)}));return{deploymentId:r.deploymentId,uploads:r.uploads.map(e=>({path:e.path,upload:{url:e.upload.url,expiresAt:e.upload.expiresAt.toISOString(),headers:e.upload.headers}})),...r.nextCursor!==null&&{nextCursor:r.nextCursor}}}),xd=e=>tl.input(no).output(ro).mutation(async({input:t,ctx:n})=>{let r=_d(n.viewer),i=J(await e.upload.complete({...t,...r}));return{canvasId:t.canvasId,prototypeId:i.prototype.id,deploymentId:i.deployment.id,nodeId:i.prototype.nodeId,version:i.version,state:`ready`,origin:e.runtimeConfig.originFor(i.deployment.id),openUrl:`/c/${t.canvasId}?prototype=${i.prototype.id}`}}),Sd=e=>W.input(io).output(ao).mutation(async({input:t})=>{let n=J(await e.runtime.requestTicket(t)),r=e.runtimeConfig.originFor(n.ticket.deploymentId);return{deploymentId:n.ticket.deploymentId,origin:r,bootUrl:`${r}/__enhance/open#ticket=${encodeURIComponent(n.token)}&deployment=${n.ticket.deploymentId}`,expiresAt:n.ticket.expiresAt.toISOString()}}),Cd=e=>U.input(ho).output(go).query(()=>({protocolVersion:1,format:`zip`,limits:e.artifactPublishing.capabilities()})),wd=e=>K.input(vo).output(xo).mutation(async({input:t,ctx:n})=>{let r=J(await e.artifactPublishing.create({...t,prototypeId:t.prototypeId??null,personId:gd(n.viewer).personId})),i={prototypeId:r.prototype.id,deploymentId:r.deployment.id,nodeId:r.prototype.nodeId,alreadyExists:r.alreadyExists,artifact:r.deployment.artifact};if(r.deployment.state!==`uploading`)return{...i,state:r.deployment.state};if(r.upload===null)throw TypeError(`an uploading artifact has no upload`);return{...i,state:r.deployment.state,upload:{...r.upload,expiresAt:r.upload.expiresAt.toISOString()}}}),Td=e=>K.input(So).output(Co).mutation(async({input:t,ctx:n})=>{let r=J(await e.artifactPublishing.submit({...t,personId:gd(n.viewer).personId}));return{deploymentId:r.id,state:r.state}}),Ed=e=>K.input(wo).output(Eo).query(async({input:t,ctx:n})=>{let r=J(await e.artifactPublishing.status({...t,personId:gd(n.viewer).personId})),i={prototypeId:r.prototype.id,deploymentId:r.deployment.id,nodeId:r.prototype.nodeId,fileCount:r.deployment.artifact.fileCount,totalBytes:r.deployment.artifact.expandedBytes,processedFiles:r.deployment.processedFiles};if(r.deployment.state!==`failed`)return{...i,state:r.deployment.state};let a=r.deployment.failure;if(a===null)throw TypeError(`a failed artifact has no failure`);return{...i,state:r.deployment.state,failure:{code:a.code,message:a.message,...a.path!==null&&{path:a.path}}}}),Dd=e=>K.input(Do).output(Oo).mutation(async({input:t,ctx:n})=>{let r=gd(n.viewer),i=J(await e.upload.complete({...t,...r})),a=e.runtimeConfig.originFor(i.deployment.id);return{canvasId:t.canvasId,prototypeId:i.prototype.id,deploymentId:i.deployment.id,nodeId:i.prototype.nodeId,version:i.version,state:`ready`,origin:a,openUrl:`/c/${t.canvasId}?prototype=${i.prototype.id}`}}),Od=e=>z({getArtifactCapabilities:Cd(e),createArtifact:wd(e),submitArtifact:Td(e),getPublishStatus:Ed(e),attach:Dd(e),create:yd(e),reserveUploads:bd(e),complete:xd(e),requestRuntimeTicket:Sd(e)}),kd=e=>({url:e.url,expiresAt:e.expiresAt.toISOString(),headers:e.headers}),Ad=e=>({url:e.url,expiresAt:e.expiresAt.toISOString(),bytes:e.bytes}),jd=e=>U.input(Bo).output(Vo).mutation(async({input:t,ctx:n})=>{let r=J(await e.start.execute({...t,ownerPersonId:n.viewer.personId}));return n.tag(`recordingId`,r.recording.id),n.telemetry.emit(`RecordingStarted`,{recordingId:r.recording.id,sourceOrigin:r.recording.sourceOrigin}),{recordingId:r.recording.id,ownerPersonId:r.recording.ownerPersonId,chunkIndex:0,upload:kd(r.upload),audioUpload:r.audioUpload===null?null:kd(r.audioUpload)}}),Md=e=>U.input(Ho).output(Uo).mutation(async({input:t,ctx:n})=>{let r=J(await e.appendChunk.execute({...t,ownerPersonId:n.viewer.personId}));return n.tag(`recordingId`,t.recordingId),n.telemetry.emit(`RecordingChunkAppended`,{recordingId:t.recordingId,chunkIndex:t.index,bytes:t.bytes,spanMs:t.lastEventMs-t.firstEventMs}),{nextChunkIndex:r.nextChunkIndex,upload:kd(r.upload)}}),Nd=e=>U.input(Wo).output(Go).mutation(async({input:t,ctx:n})=>{let r=J(await e.appendAudioChunk.execute({...t,ownerPersonId:n.viewer.personId}));return n.tag(`recordingId`,t.recordingId),n.telemetry.emit(`RecordingAudioChunkAppended`,{recordingId:t.recordingId,chunkIndex:t.index,bytes:t.bytes,spanMs:t.lastMs-t.firstMs}),{nextChunkIndex:r.nextChunkIndex,upload:kd(r.upload)}}),Pd=e=>U.input(Ko).output(Yo).mutation(async({input:t,ctx:n})=>{let r=J(await e.complete.execute({...t,ownerPersonId:n.viewer.personId})),i=r.recording;return n.tag(`recordingId`,i.id),n.telemetry.emit(`RecordingCompleted`,{recordingId:i.id,canvasId:i.canvasId,chunkCount:r.storedChunkCount,missingChunkCount:r.missingChunkCount,bytes:i.byteSize,durationMs:i.durationMs,viewportWidth:i.viewportWidth,viewportHeight:i.viewportHeight,interrupted:+!!i.interrupted,canvasWasCreated:+!!r.isNewCanvas}),{recordingId:i.id,canvasId:r.canvasId,canvasTitle:r.canvasTitle,isNewCanvas:r.isNewCanvas,storedChunkCount:r.storedChunkCount,missingChunkIndexes:r.missingChunkIndexes,missingChunkCount:r.missingChunkCount,storedAudioChunkCount:r.storedAudioChunkCount,missingAudioChunkIndexes:r.missingAudioChunkIndexes,missingAudioChunkCount:r.missingAudioChunkCount,integrity:r.integrity}}),Fd=e=>W.input(ts).output(os).query(async({input:t,ctx:n})=>{let r=J(await e.get.execute(t));return n.tag(`recordingId`,r.recording.id),{recordingId:r.recording.id,durationMs:r.recording.durationMs,viewport:r.recording.viewport,interrupted:r.recording.interrupted,integrity:r.integrity,chunks:r.chunks.map(e=>({seq:e.chunk.seq,firstEventMs:e.chunk.firstEventMs,lastEventMs:e.chunk.lastEventMs,continues:e.chunk.continues,...e.download===null?{state:`missing`}:{state:`available`,download:Ad(e.download)}})),audio:r.recording.audioMimeType===null?null:{mimeType:r.recording.audioMimeType,chunks:r.audioChunks.map(e=>({seq:e.chunk.seq,firstMs:e.chunk.firstMs,lastMs:e.chunk.lastMs,epoch:e.chunk.epoch,startsEpoch:e.chunk.startsEpoch,...e.download===null?{state:`missing`}:{state:`available`,download:Ad(e.download)}}))},assets:r.assets.map(e=>({url:e.url,contentType:e.contentType,path:_s(e.assetBundleId,e.urlHash)})),sourceUrl:r.recording.sourceUrl,missingAssetCount:r.missingAssetCount}}),Id=e=>z({start:jd(e),appendChunk:Md(e),appendAudioChunk:Nd(e),complete:Pd(e),get:Fd(e),discard:U.input(ps).output(ms).mutation(async({input:t,ctx:n})=>({recordingId:J(await e.discard.execute({...t,ownerPersonId:n.viewer.personId})).recordingId,discarded:!0})),list:W.input(ds).output(fs).query(async({input:t})=>({items:J(await e.list.execute(t)).map(e=>({recordingId:e.id,durationMs:e.durationMs,viewport:e.viewport,interrupted:e.interrupted,chunkCount:e.chunkCount,startedAt:e.startedAt.toISOString()})),truncated:!1})),delete:q.input(hs).output(gs).mutation(async({input:t})=>J(await e.remove.execute(t)))}),Ld=e=>({url:e.url,expiresAt:e.expiresAt.toISOString(),headers:e.headers}),Rd=e=>U.input(Zo).output(Qo).mutation(async({input:t,ctx:n})=>{let r=J(await e.reserveAssets.execute({...t,ownerPersonId:n.viewer.personId}));return n.tag(`recordingId`,t.recordingId),n.telemetry.emit(`RecordingAssetsReserved`,{recordingId:t.recordingId,assetCount:t.assets.length}),{reserved:r.reserved.map(e=>({url:e.url,upload:Ld(e.upload)}))}}),zd=e=>U.input($o).output(es).mutation(async({input:t,ctx:n})=>{let r=J(await e.confirmAssets.execute({...t,ownerPersonId:n.viewer.personId}));return n.tag(`recordingId`,t.recordingId),n.telemetry.emit(`RecordingAssetsConfirmed`,{recordingId:t.recordingId,assetCount:t.arrived.length,missingAssetCount:r.missingAssetCount}),{missingAssetCount:r.missingAssetCount}}),Bd=e=>z({reserve:Rd(e),confirm:zd(e)}),Vd=e=>({url:e.url,expiresAt:e.expiresAt.toISOString(),headers:e.headers}),Hd=e=>U.input(ss).output(cs).mutation(async({input:t,ctx:n})=>{let r=J(await e.refreshUpload.execute({...t,ownerPersonId:n.viewer.personId}));return n.tag(`recordingId`,t.recordingId),{upload:Vd(r.upload)}}),Ud=e=>U.input(ls).output(us).mutation(async({input:t,ctx:n})=>{let r=J(await e.confirmUpload.execute({...t,ownerPersonId:n.viewer.personId}));return n.tag(`recordingId`,t.recordingId),r}),Wd=e=>({refreshUpload:Hd(e),confirmUpload:Ud(e)}),Gd=e=>z({create:U.input(vs).output(ys).mutation(async({input:t,ctx:n})=>{let r=await e.create.execute({...t,ownerPersonId:n.viewer.personId});r.isErr()&&t.bytes>67108864&&n.telemetry.emit(`ScreenRejected`,{bytes:t.bytes,limitBytes:67108864,hasProvenance:t.provenance===null?0:1,atMs:t.provenance?.atMs??null});let i=J(r);return n.tag(`screenId`,i.screen.id),n.telemetry.emit(`ScreenCreated`,{screenId:i.screen.id,bytes:t.bytes,hasProvenance:t.provenance===null?0:1,atMs:t.provenance?.atMs??null,wasRetry:+!!i.alreadyExists}),{screenId:i.screen.id,upload:{url:i.upload.url,expiresAt:i.upload.expiresAt.toISOString(),headers:i.upload.headers},alreadyExists:i.alreadyExists,state:i.state}}),complete:U.input(bs).output(xs).mutation(async({input:t,ctx:n})=>{let r=J(await e.complete.execute({...t,ownerPersonId:n.viewer.personId}));return n.tag(`screenId`,r.id),{screenId:r.id,storedBytes:r.storedBytes,uploadedAt:r.uploadedAt.toISOString()}}),delete:U.input(Ss).output(Cs).mutation(async({input:t,ctx:n})=>J(await e.remove.execute({...t,ownerPersonId:n.viewer.personId})))}),Kd=e=>{let{name:t,...n}=e;return{...n,event:`ClientTimingReported`,signal:t,supportedClient:+(e.capabilityVersion===2),isSlow:+(e.name===`canvas_load`&&(e.outcome===`slow`||e.outcome===`timed-out`)),isDegraded:+(e.name===`canvas_load`&&(e.outcome===`degraded`||e.outcome===`timed-out`)),isJanky:+(e.name===`canvas_interaction`&&e.outcome===`janky`),isRealtimeFailure:+(e.name===`canvas_realtime`&&e.outcome===`failed`),mirroredAssetDuplicateCount:e.name===`canvas_load`?Math.max(e.mirroredAssetRequestCount-e.mirroredAssetUniqueCount,0):0}},qd=e=>e.name===`canvas_load`?e.outcome!==`ready`:e.name===`canvas_interaction`?e.outcome!==`smooth`:e.outcome!==`succeeded`,Jd=()=>H.input(Os).output(ks).mutation(({input:e,ctx:t})=>{let n=Kd(e);return qd(e)?t.logger.warn(n,`event`):t.logger.info(n,`event`),{accepted:!0}}),Yd=e=>{switch(e.name){case`authentication`:return e.state===`invalid`;case`context_lifecycle`:return e.outcome.endsWith(`failed`);case`destination_picker`:return e.outcome!==`options`;case`destination_request`:return e.outcome===`failed`;case`microphone_session`:return e.outcome===`still-active`;case`microphone_permission`:return[`denied`,`refused`,`no-device`,`in-use`,`unavailable`].includes(e.outcome);case`recording_cleanup`:return e.outcome!==`released`;case`recording_transition`:return e.state===`failed`||e.state===`cancelled`;case`screen_preview`:return e.outcome!==`ready`;case`synthetic_stage`:return e.outcome===`failed`}},Xd=e=>{let{name:t,...n}=e;return{...n,event:`ExtensionLifecycle`,signal:t,supportedClient:+(e.capabilityVersion===2)}},Zd=()=>z({lifecycle:H.input(Fs).output(Is).mutation(({input:e,ctx:t})=>{let n=Xd(e);return Yd(e)?t.logger.warn(n,`event`):t.logger.info(n,`event`),{accepted:!0}})}),Qd=e=>z({get:W.meta({description:`Read timestamped speech cues as candidate moments; render and inspect candidate PNGs before snapshotting.`}).input(Rs).output(Ws).query(async({input:t,ctx:n})=>J(await e.get.execute({...t,canRetry:n.canvasAccess.canManage}))),retry:q.meta({description:`Retry a failed transcription for one recording.`}).input(Gs).output(Ks).mutation(async({input:t})=>J(await e.retry.execute(t)))}),$d={shouldExposeInviteTokens:!1,realtimeEndpoint:`ws://localhost:3000/v1/canvas-realtime`},ef=(e,t=$d)=>z({canvas:z({...gl(e.canvas)._def.record,...bl(e.canvas)._def.record,...Rl(e.canvas)._def.record,...jl(e.render),selection:Xl(e.canvas.selection,e.render.readCanvas),realtime:Gl(e.canvas,t.realtimeEndpoint),document:yl(e.canvas),version:uu(e.canvas),render:z({...ku(e.render)._def.record,...Au(e.render)._def.record}),thumbnail:Ql(),participants:Bl(e.canvas),invites:Il(e.canvas,t.shouldExposeInviteTokens)}),comment:Gu(e.comment),organisation:z({...Ku(e.organisation)._def.record,people:od(e.organisation),invites:ed(e.organisation)}),person:md(e.person),prototype:Od(e.prototype),recording:z({...Id(e.recording)._def.record,...Wd(e.recording)}),recordingAsset:Bd(e.recording),screen:Gd(e.screen),transcript:Qd(e.transcript),telemetry:z({...Zd()._def.record,performance:Jd()})}),$={execute:()=>{throw Error(`The schema-only router must never execute an API handler.`)}},tf={organisation:{list:$,listMembers:$,addMember:$,create:$,update:$,remove:$,setMemberRole:$,removeMember:$,transferOwnership:$,createInvite:$,listInvites:$,revokeInvite:$,resendInvite:$,previewInvite:$,acceptInvite:$},canvas:{applyOperations:$,createEditableFrame:$,create:$,get:$,list:$,rename:$,setAccess:$,remove:$,move:$,duplicate:$,removePermanently:$,markViewed:$,setReviewState:$,restore:$,versions:{list:$.execute,get:$.execute,name:$.execute,removeName:$.execute,restore:$.execute,duplicate:$.execute},getDocument:$,saveDocument:$,reserveImage:$,listParticipants:$,setParticipantAccess:$,revokeParticipant:$,createInvite:$,listInvites:$,revokeInvite:$,resendInvite:$,acceptInvite:$,previewInvite:$,issueRealtimeTicket:$,activity:{begin:()=>$.execute(),renew:()=>$.execute(),end:()=>$.execute()},selection:$},comment:{start:$,reply:$,edit:$,move:$,react:$,resolve:$,remove:$,list:$,people:{read:()=>$.execute()}},person:{signUp:$,signIn:$,getMe:$,updateDisplayName:$,searchRecipients:$,recentRecipients:$,agentTokens:{create:()=>$.execute(),list:()=>$.execute(),find:()=>$.execute(),revoke:()=>$.execute()}},prototype:{publishing:{create:$.execute},artifactPublishing:{capabilities:$.execute,create:$.execute,submit:$.execute,status:$.execute},upload:{reserve:$.execute,complete:$.execute},runtime:{requestTicket:$.execute,consumeTicket:$.execute,readFile:$.execute},runtimeConfig:{originFor:()=>$.execute(),webOrigin:`https://unused.invalid`,bridgeScriptUrl:`https://unused.invalid/prototype-bridge.js`,secureCookies:!0}},recording:{start:$,reserveAssets:$,confirmAssets:$,appendChunk:$,appendAudioChunk:$,complete:$,refreshUpload:$,confirmUpload:$,discard:$,get:$,list:$,remove:$},render:{create:$,get:$,cancel:$,download:$,expose:$,readCanvas:$},screen:{create:$,complete:$,remove:$},transcript:{get:$,retry:$}},nf=()=>ef(tf),rf=n.record(n.string(),n.unknown()),af={canvasId:`00000000-0000-4000-8000-000000000010`,source:{kind:`html`,html:`<div></div>`,label:`Example`},destination:{kind:`insert-children`,targetNodeId:`root`}},of=(e,t)=>{let n=rf.safeParse(e);if(!n.success)throw TypeError(`${t} is not an object`);return n.data},sf=(e,t,n)=>{if(!(typeof e==`object`&&e||typeof e==`function`))throw TypeError(`${n} is not reflectable`);return Reflect.get(e,t)},cf=(e,t)=>t===`query`?`read`:/(?:\.delete(?:Permanently)?|\.discard|\.remove(?:Name)?|\.revoke)$/u.test(e)?`delete`:`write`,lf=(e,t)=>{let r=sf(e[t],`_def`,`${t} definition`),i=n.array(n.unknown()).safeParse(sf(r,`inputs`,`${t} internals`));if(!i.success)throw TypeError(`${t} has no input schema`);let a=i.data[0];if(!(a instanceof n.ZodType))throw TypeError(`${t} has no input schema`);let o=sf(r,`output`,`${t} internals`);if(!(o instanceof n.ZodType))throw TypeError(`${t} has no output schema`);return{input:a,output:o}},uf=()=>{let e=nf(),n=of(Reflect.get(e,`_def`),`router internals`),r=of(n.procedures,`router procedures`),i=t({router:e}),a=Ac();a.assertProcedureInventory(i.map(([e])=>e));let o=i.map(([e,t])=>{if(t.type===null)throw TypeError(`${e} has no operation type`);let n=lf(r,e),i=a.forProcedure(e);return Tc({id:e,operation:t.type,source:`router`,effect:cf(e,t.type),idempotency:t.type===`query`?`none`:`single`,execution:{kind:`remote`,procedure:e},inputSchema:n.input,outputSchema:n.output,meta:t.meta,policy:i,cliPath:i.exposure===`shared`?e.replaceAll(`.`,` `):null,...e===`canvas.render.importSource`&&{inputExample:af}})}),s=[...rc,...jc].map(e=>Tc({id:e.id,operation:e.operation,source:`composite`,effect:e.effect,idempotency:e.idempotency,execution:{kind:`composite`,procedures:e.procedures},inputSchema:e.inputSchema,outputSchema:e.outputSchema,meta:{description:e.summary},policy:a.forUtility(e.id),cliPath:e.cliPath,inputExample:e.inputExample,outputExample:e.outputExample}));return[...o,...s].toSorted((e,t)=>e.id.localeCompare(t.id))};var df=class extends e{requestedCode;constructor(e){super(`CLI process adapter intercepted an exit`,{exitCode:e,cause:null}),this.name=`ProcessExitError`,this.requestedCode=e}};const ff=e=>e.toLocaleLowerCase(`en-AU`).replaceAll(/[^a-z0-9]+/gu,` `).trim(),pf=(e,t)=>{let n=ff(t),r=ff(e.id);if(n===r)return 1e4;let i=new Set(r.split(` `)),a=ff([e.guide.summary,e.guide.useWhen,...e.guide.preconditions,...e.guide.input.map(e=>`${e.name} ${e.meaning}`),...e.guide.output.map(e=>`${e.name} ${e.meaning}`),...e.guide.next].join(` `)),o=n.split(` `).filter(e=>e!==``),s=r.startsWith(n)?1e3:0;for(let e of o)i.has(e)?s+=100:r.includes(e)&&(s+=40),a.includes(e)&&(s+=10);return s},mf=e=>{let t=e.guide.examples[0];if(t===void 0)throw TypeError(`${e.id} has no capability example`);return t},hf=e=>({id:e.id,operation:e.operation,effect:e.effect,idempotency:e.idempotency,summary:e.guide.summary,useWhen:e.guide.useWhen,preconditions:e.guide.preconditions,inputSchema:n.toJSONSchema(e.inputSchema,{unrepresentable:`any`}),exampleInput:mf(e).input,output:e.guide.output,result:e.guide.result,recovery:e.guide.recovery,next:e.guide.next,schemaDigest:e.schemaDigest,guidanceDigest:e.guidanceDigest,behaviorDigest:e.behaviorDigest}),gf=e=>({id:e.id,operation:e.operation,effect:e.effect,summary:e.guide.summary,useWhen:e.guide.useWhen}),_f=e=>({search:t=>{let n=e.filter(e=>t.operation===`any`||e.operation===t.operation).map(e=>({capability:e,score:pf(e,t.query)})).filter(e=>e.score>0).toSorted((e,t)=>{let n=t.score-e.score;return n===0?e.capability.id.localeCompare(t.capability.id):n});return{matches:n.slice(0,t.limit).map(({capability:e})=>gf(e)),totalMatches:n.length,truncated:n.length>t.limit}},describe:t=>{let n=e.find(e=>e.id===t);return n===void 0?null:hf(n)}}),vf=(e,t)=>e.filter(e=>t.includes(e.policy.exposure)),yf=e=>vf(e,[`shared`]),bf=new Set([`FORBIDDEN`,`NOT_FOUND`,`CONFLICT`,`RATE_LIMITED`]),xf=e=>{switch(e){case`BAD_REQUEST`:return`Run the command with '--help', then rewrite every rejected argument.`;case`UNAUTHORIZED`:return`Run 'enhance auth login' and complete authentication in the browser.`;case`FORBIDDEN`:return`Run 'enhance canvas list --scope mine' and choose a target you can change.`;case`NOT_FOUND`:return`List the resource again and retry with an identifier from that result.`;case`CONFLICT`:return`Read the resource again before retrying the change.`;case`RATE_LIMITED`:return`Wait for the server retry window, then retry once.`;case`INTERNAL`:return`Run 'enhance doctor', report the result, and stop.`}},Sf=n.object({data:n.looseObject({appError:n.unknown()})}),Cf=e=>{let t=Sf.safeParse(e);return ws.safeParse(t.success?t.data.data.appError:null)},wf=(e,t)=>{if(e instanceof qs){let t=e.fields===void 0?void 0:Object.entries(e.fields).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({path:e,message:t}));return{code:e.code,message:e.message,remediation:e.remediation,...t!==void 0&&{fields:t}}}if(e instanceof s){let t=Cf(e);if(t.success){let e=t.data.fields===void 0?void 0:Object.entries(t.data.fields).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({path:e,message:t}));return{code:t.data.code,message:t.data.message,remediation:xf(t.data.code),...e!==void 0&&{fields:e}}}}if(e instanceof df){let e=t?.trim();return{code:`BAD_REQUEST`,message:e===void 0||e===``?`The command line is malformed.`:e,remediation:`Run 'enhance --help' and use one of the complete command paths shown there.`}}return{code:`INTERNAL`,message:`The CLI failed before it received a usable result.`,remediation:`Run 'enhance doctor', report the result, and stop.`}},Tf=(e,t,n)=>t?2:n instanceof Js?6:e.code===`BAD_REQUEST`?3:e.code===`UNAUTHORIZED`?4:bf.has(e.code)?5:1,Ef=/(?<![-\w@])enhance(?=(?:-mcp)?(?:[^-\w]|$))/gu,Df=(e,t)=>e.replaceAll(Ef,()=>t),Of=e=>typeof e==`object`&&!!e&&!Array.isArray(e),kf=(e,t)=>typeof e==`string`?Df(e,t):Array.isArray(e)?e.map(e=>kf(e,t)):Of(e)?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,kf(n,t)])):e,Af=(e,t)=>typeof e==`string`?Df(e,t):Of(e)?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,e===`next`?kf(n,t):n])):e,jf=(e,t)=>({...e,message:Df(e.message,t),remediation:Df(e.remediation,t),...e.fields!==void 0&&{fields:e.fields.map(e=>({...e,message:Df(e.message,t)}))}});export{pn as $,Vo as A,Aa as B,qs as C,ys as D,xs as E,go as F,hr as G,Sa as H,Eo as I,$n as J,Jn as K,po as L,Oo as M,xo as N,Uo as O,lo as P,dn as Q,uo as R,Js as S,ws as T,Ki as U,Da as V,br as W,yn as X,Wn as Y,xn as Z,Qs as _,vf as a,Xt as at,tc as b,df as c,Ac as d,Pt as et,Tc as f,Zs as g,Xs as h,wf as i,en as it,oo as j,Yo as k,uf as l,pc as m,Af as n,Jt as nt,yf as o,ht as ot,mc as p,tr as q,Tf as r,nn as rt,_f as s,h as st,jf as t,T as tt,nf as u,$s as v,Ws as w,nc as x,ec as y,Co as z};
|
package/dist/main.mjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{A as e,C as t,D as n,E as r,G as i,J as a,K as o,O as s,S as c,T as l,U as u,W as d,X as f,Y as p,Z as ee,c as m,d as te,et as ne,i as h,k as re,l as ie,m as ae,n as g,o as oe,ot as se,p as _,r as v,s as ce,st as le,t as ue,tt as de,u as fe}from"./cli-output-identity.lib-COXLA7bt.mjs";import{a as pe,c as me,d as he,f as ge,i as y,l as b,n as _e,o as ve,r as ye,s as be,t as xe,u as Se}from"./mutation-key.adapter-BhdfFChs.mjs";import{t as Ce}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{Command as we}from"commander";import{createCli as Te,parseRouter as Ee}from"trpc-cli";import{z as x}from"zod";import{hostname as De,tmpdir as Oe}from"node:os";import S from"node:process";import{createInterface as ke}from"node:readline";import{chmodSync as Ae,existsSync as je,lstatSync as Me,mkdirSync as Ne,readFileSync as Pe,readdirSync as Fe,statSync as C,unlinkSync as Ie,writeFileSync as w}from"node:fs";import T from"node:path";import{createHash as Le,randomUUID as E}from"node:crypto";import{readFile as Re}from"node:fs/promises";import{proxify as ze}from"trpc-cli/dist/proxify.js";const Be=()=>({rotation:0,flipHorizontal:!1,flipVertical:!1,horizontal:{mode:`fixed`,value:0},vertical:{mode:`fixed`,value:0},position:`absolute`,clipContent:!1}),D=`root`,Ve=e=>`a${String(e).padStart(4,`0`)}`,He=()=>({version:2,nodes:{[D]:{id:D,label:`Canvas`,component:`root`,styles:{}}},relationships:{}}),Ue=(e,t)=>({...e,nodes:{...e.nodes,[t.id]:t},relationships:{...e.relationships,[t.id]:{parentId:D,sortKey:Ve(Object.keys(e.relationships).length)}}}),We=(e,t)=>Ue(e,{id:t.id,label:t.label,component:`screen`,props:{capture:{viewport:t.viewport,atMs:0,screenId:t.screenId}},styles:{},box:{...t.at,...t.viewport}}),Ge=e=>`${JSON.stringify(e)}\n`,Ke=e=>{if(e<1)throw RangeError(`a chunk has to be able to hold at least one character`);let t=``,n=[],r=!1,i=!1,a=()=>{let e={body:t,continues:r,eventCount:n.length-+!!r,firstEventMs:n.length===0?0:Math.min(...n),lastEventMs:n.length===0?0:Math.max(...n)};return r=!t.endsWith(`
|
|
3
|
+
`),t=``,n=r?[n.at(-1)??0]:[],e};return{pending:()=>t.length,add:r=>{let o=[],s=Ge(r.event);for(n.push(r.atMs),i=!0;t.length+s.length>=e;){let n=e-t.length;t+=s.slice(0,n),s=s.slice(n),o.push(a())}return t+=s,o},drain:()=>!i||t.length>0?[a()]:[]}},qe=(e,t)=>{let n=Ke(t);return[...e.flatMap(e=>n.add(e)),...n.drain()]},O=[`recording.start`,`recording.appendChunk`,`recording.complete`],Je=t=>async n=>{let r=e.parse(await t.mutate(O[0],{sourceUrl:n.sourceUrl,viewport:n.viewport,pageTitle:n.pageTitle,audio:null})),i=r.upload;try{let e=qe(n.entries,8388608);for(let[n,a]of e.entries()){let e=new TextEncoder().encode(a.body),o=await t.upload({url:i.url,headers:i.headers,body:e});i=s.parse(await t.mutate(O[1],{recordingId:r.recordingId,index:n,firstEventMs:a.firstEventMs,lastEventMs:a.lastEventMs,eventCount:a.eventCount,continues:a.continues,bytes:e.byteLength,etag:o})).upload}let a=Math.max(0,...n.entries.map(e=>e.atMs));return re.parse(await t.mutate(O[2],{recordingId:r.recordingId,durationMs:a,viewport:n.viewport,sourceUrl:n.sourceUrl,interrupted:!1,...n.canvasId!==void 0&&{canvasId:n.canvasId},audioChunkCount:0,hasRecoverableBytes:!1}))}catch{throw new c(`Recording ${r.recordingId} began, but not every chunk was committed.`,`Run 'enhance recording discard --recording-id ${r.recordingId}' to remove the incomplete attempt before retrying the fixture.`)}},Ye=[`screen.create`,`screen.complete`],Xe=e=>async t=>{let i=n.parse(await e.mutate(Ye[0],{clientToken:t.clientToken,provenance:t.provenance,route:t.route,pageTitle:t.pageTitle,viewport:t.viewport,bytes:t.body.byteLength}));try{let n=await e.upload({url:i.upload.url,headers:i.upload.headers,body:t.body}),a=r.parse(await e.mutate(Ye[1],{screenId:i.screenId,etag:n}));return{screenId:a.screenId,route:t.route,title:t.pageTitle,viewport:t.viewport,atMs:t.provenance?.atMs??null,sourceRecordingId:t.provenance?.sourceRecordingId??null,assetBundle:null,download:null,storedBytes:a.storedBytes}}catch{throw new c(`Screen ${i.screenId} was reserved, but its upload did not complete.`,`Retry 'enhance fixture screen' with the same --client-token ${t.clientToken}.`)}},k=[`organisation.create`,`canvas.create`,`screen.create`,`screen.complete`,`canvas.document.get`,`canvas.document.save`],Ze=(e,t)=>async n=>{let r=u.parse(await e.mutate(k[0],{name:n.organisationName})).organisation,i=le.parse(await e.mutate(k[1],{title:n.canvasTitle,organisationId:r.id,sourceUrl:null}));try{let a=[];for(let e of n.screens)a.push(await t(e));let o=f.parse(await e.query(k[4],{canvasId:i.id})),s=He();for(let[e,t]of a.entries())s=We(s,{id:`fixture-screen-${String(e+1)}`,label:`Fixture screen ${String(e+1)}`,screenId:t.screenId,viewport:n.screens[e]?.viewport??{width:1440,height:900},at:{x:48+e*48,y:48+e*48}});let l=ee.parse(await e.mutate(k[5],{canvasId:i.id,baseVersion:o.version,document:s,screenIds:a.map(e=>e.screenId)}));if(l.outcome===`conflict`)throw new c(`World canvas ${i.id} was created, but another writer changed its document.`,`Read 'enhance canvas document get --canvas-id ${i.id}' before adding the screens.`);return{organisationId:r.id,canvasId:i.id,screenIds:a.map(e=>e.screenId),documentVersion:l.version}}catch(e){throw e instanceof c?e:new c(`Organisation ${r.id} and canvas ${i.id} exist, but the world is incomplete.`,`Inspect 'enhance canvas get --canvas-id ${i.id}' before retrying any missing steps.`)}},Qe=async(e,n)=>{if(e!==void 0&&e!==``)return e.trim();if(S.stdin.isTTY)throw new t(`BAD_REQUEST`,`A token is required and interactive prompting is disabled.`,`Pass '--token <token>' or pipe one line to '${n}'.`);let r=ke({input:S.stdin,crlfDelay:1/0});for await(let e of r){r.close();let t=e.trim();if(t!==``)return t;break}throw new t(`BAD_REQUEST`,`A token is required.`,`Pass '--token <token>' or pipe one line to '${n}'.`)},$e=async e=>{if(e!==void 0)return e.trim();if(S.stdin.isTTY)return null;let t=ke({input:S.stdin,crlfDelay:1/0});for await(let e of t){t.close();let n=e.trim();return n===``?null:n}return null},et=(e,t,n)=>{let r=e.command(`auth`).description(`Store and inspect the agent credential.`);r.command(`login`).description(`Authenticate in a browser, then store a revocable agent credential.`).option(`--token <token>`,`Use an existing agent token instead of browser authentication.`).option(`--no-open`,`Print the authorization URL without opening the browser.`).action(async e=>{let r=await $e(e.token);if(r!==null){n.result(await t.loginWithToken(r));return}n.result(await t.loginWithBrowser({label:`CLI on ${De()}`.slice(0,120),openBrowser:e.open,onReady:e=>{n.result({status:`waiting_for_browser`,url:e})}}))}),r.command(`status`).description(`Resolve the stored token to its person, label, and expiry.`).action(async()=>{n.result(await t.status())}),r.command(`logout`).description(`Delete the local credential file; this does not revoke the server token.`).action(async()=>{n.result(await t.logout())})},tt=x.array(a).min(1).max(o),nt=e=>{if(!e.startsWith(`@`))return e;let n=e.slice(1);if(n===``)throw new t(`BAD_REQUEST`,`--operations @ must name a JSON file.`,`Pass --operations @/absolute/path/layout.json or an inline JSON array.`);let r=T.resolve(n);try{let e=C(r);if(!e.isFile()||e.size>1048576)throw Error(`invalid size`);return Pe(r,`utf8`)}catch{throw new t(`BAD_REQUEST`,`Could not read a bounded operations file at ${r}.`,`Use a regular JSON file no larger than 1 MiB.`)}},rt=e=>{try{return JSON.parse(nt(e))}catch(e){throw e instanceof t?e:new t(`BAD_REQUEST`,`--operations must be one valid JSON array.`,`Pass inline JSON or @/absolute/path/layout.json; run 'enhance canvas apply --help' for examples.`)}},it=e=>{let n=rt(e),r=tt.safeParse(n);if(!r.success){let e=r.error.issues[0];throw new t(`BAD_REQUEST`,`The canvas operation batch is invalid${e===void 0||e.path.length===0?``:` at ${e.path.join(`.`)}`}.`,`Correct the named operation; run 'enhance canvas apply --help' for the supported vocabulary.`)}return r.data},A=x.uuid(),at=/^\/c\/([^/]+)\/?$/u,ot=e=>{try{let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`)return null;let n=at.exec(t.pathname.toLowerCase()),r=A.safeParse(n?.[1]);return r.success?r.data:null}catch{return null}},j=e=>{let n=e.trim(),r=A.safeParse(n);if(r.success)return r.data;let i=ot(n);if(i!==null)return i;throw new t(`BAD_REQUEST`,`The canvas reference is neither a canvas URL nor a UUID.`,`Paste an HTTP(S) URL shaped https://app.example/c/<UUID>, or pass the bare canvas UUID.`)},M=(e,t)=>{let n=e.find(e=>e.id===t);if(n===void 0)throw TypeError(`${t} is missing from the capability catalogue`);return n},st=x.coerce.number().int().positive(),ct=e=>{let n=st.safeParse(e);if(n.success)return n.data;throw new t(`BAD_REQUEST`,`--base-version is invalid.`,`Run 'enhance canvas apply --help'.`)},lt=(e,n)=>{let r=x.uuid().nullable().safeParse(n??null);if(!r.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact operation batch.`);return e.mutationKey.select(r.data,!1),e.mutationKey.current(`canvas.applyOperations`,{})},ut=(e,t)=>{e.command(`apply`).description(`Apply an atomic canvas edit batch and return its affected bounds.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact version returned by canvas inspect or tree.`).requiredOption(`--operations <json-or-@path>`,`JSON operation array inline, or @path to a JSON file.`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this exact batch.`).addHelpText(`after`,[``,`Supported operations: insertNode, insertText, insertPrototype, setText, setBox, setLabel, setVisibility, setLocked, setConstraints, setStyles, setAppearance, setLayout, setTypography, setAdditionalStyles, setProps, setParentage, move, remove.`,`Example:`,` enhance canvas apply --canvas <url-or-id> --base-version 3 --operations '[{"op":"insertText","nodeId":"txt_summary","parentId":"root","text":"Checkout needs an address.","box":{"x":120,"y":594,"width":720,"height":80},"styles":{"font-size":24}}]'`].join(`
|
|
4
|
+
`)).action(async e=>{lt(t,e.clientToken);let n=await t.invocation.invoke({capability:M(t.catalog(),`canvas.apply`),arguments:{canvasId:j(e.canvas),baseVersion:ct(e.baseVersion),operations:[...it(e.operations)]},clientToken:e.clientToken??null});t.output.result(n)})},N=1e3,dt=x.coerce.number().int().positive(),ft=x.coerce.number().min(.1).max(4),pt=x.uuid(),mt=x.union([x.string(),x.number(),x.null()]),ht=x.record(x.string(),mt),gt=x.array(x.object({nodeId:x.string().min(1).max(200),textContent:x.string().max(1e5)})).min(1).max(N),_t=x.array(x.object({nodeId:x.string().min(1).max(200),name:x.string().max(500)})).min(1).max(N),vt=x.array(x.object({nodeIds:x.array(x.string().min(1).max(200)).min(1).max(100),styles:ht})).min(1).max(100),yt=x.array(x.object({id:x.string().min(1).max(200),parentId:x.string().min(1).max(200).optional()})).min(1).max(100),bt=x.array(x.union([x.object({nodeId:x.string().min(1).max(200),before:x.string().min(1).max(200)}),x.object({nodeId:x.string().min(1).max(200),after:x.string().min(1).max(200)}),x.object({nodeId:x.string().min(1).max(200),parentId:x.string().min(1).max(200),index:x.number().int().nonnegative().optional()})])).min(1).max(100),xt=x.array(x.string().min(1).max(200)).min(1).max(N),St=x.coerce.number().int().min(0).max(20),Ct=e=>{try{return JSON.parse(e)}catch{return}},wt=e=>{if(e===void 0)return null;let n=de.safeParse(Ct(e));if(n.success)return n.data;throw new t(`BAD_REQUEST`,`--bounds must be a positive world rectangle.`,`Pass JSON with x, y, width and height.`)},Tt=e=>e===void 0?[]:e.split(`,`).map(e=>e.trim()).filter(e=>e!==``).slice(0,100),Et=(e,n)=>{e.command(`begin`).description(`Start visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--phase <phase>`,`reading, writing, creating, deleting, or rendering.`).option(`--node-ids <ids>`,`Comma-separated stable node ids.`).option(`--bounds <json>`,`Optional world rectangle for not-yet-created content.`).action(async e=>{let r=i.safeParse(e.phase);if(!r.success)throw new t(`BAD_REQUEST`,`--phase is invalid.`,`Use reading, writing, creating, deleting, or rendering.`);let a=j(e.canvas),o=d.parse(await n.remote.mutate(`canvas.realtime.activity.begin`,{canvasId:a,phase:r.data,nodeIds:Tt(e.nodeIds),bounds:wt(e.bounds)}));n.output.result({...o,next:[`enhance canvas work update --canvas ${a} --activity-id ${o.activityId} --phase ${r.data}`,`enhance canvas finish-working-on-nodes --canvas ${a} --activity-id ${o.activityId}`]})})},Dt=(e,t)=>{e.command(`update`).description(`Move visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by work begin.`).requiredOption(`--phase <phase>`,`Current agent phase.`).option(`--node-ids <ids>`,`Comma-separated current stable node ids.`).option(`--bounds <json>`,`Optional current world rectangle.`).action(async e=>{t.output.result(d.parse(await t.remote.mutate(`canvas.realtime.activity.renew`,{canvasId:j(e.canvas),activityId:pt.parse(e.activityId),phase:i.parse(e.phase),nodeIds:Tt(e.nodeIds),bounds:wt(e.bounds)})))})},Ot=(e,n)=>{e.command(`finish-working-on-nodes`).description(`End visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by canvas work begin.`).action(async e=>{if(!await Se(n.remote).finish(j(e.canvas),pt.parse(e.activityId)))throw new t(`NOT_FOUND`,`The activity could not be finished.`,`It may already have expired; run canvas work begin for new work.`);n.output.result({ended:!0,activityId:e.activityId})})},kt=(e,t)=>{let n=e.command(`work`).description(`Manage visible agent activity.`);Et(n,t),Dt(n,t),Ot(e,t)},At=/^(?:align|bottom|column-gap|display|flex|gap|height|justify|left|order|overflow|padding|position|right|row-gap|top|transform|width)/u,P=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e!=`string`)return null;let t=/^(-?\d+(?:\.\d+)?)(?:px)?$/u.exec(e.trim());return t===null?null:Number(t[1])},jt=(e,t)=>{let n=P(e);return n===null?[`100%`,`fill`].includes(String(e))?{mode:`fill`}:[`fit-content`,`auto`,`hug`].includes(String(e))?{mode:`hug`}:t:{mode:`fixed`,value:Math.max(0,n)}},Mt=(e,t,n)=>{let r=e[t],[i=n.top,a=i,o=i,s=a]=typeof r==`string`?r.split(/\s+/u).map(e=>P(e)??0):typeof r==`number`?[r]:[];return{top:Math.max(0,P(e[`${t}-top`])??i),right:Math.max(0,P(e[`${t}-right`])??a),bottom:Math.max(0,P(e[`${t}-bottom`])??o),left:Math.max(0,P(e[`${t}-left`])??s)}},Nt=(e,t)=>{switch(e){case`center`:case`start`:case`stretch`:return e;case`end`:case`flex-end`:return`end`;case`flex-start`:return`start`;default:return t}},Pt=(e,t)=>{switch(e){case`center`:case`space-around`:case`space-between`:case`space-evenly`:case`start`:return e;case`end`:case`flex-end`:return`end`;case`flex-start`:return`start`;default:return t}},Ft=()=>({direction:`column`,alignItems:`start`,alignContent:`start`,justifyContent:`start`,gap:0,rowGap:0,columnGap:0,wrap:`nowrap`,padding:{top:0,right:0,bottom:0,left:0}}),It=(e,t)=>{let n=t.display;if([`block`,`none`].includes(String(n)))return;let r=[`flex`,`inline-flex`].includes(String(n));if(e===void 0&&!r)return;let i={...e??Ft()},a=t[`flex-direction`];return i.direction=a===void 0?i.direction:String(a).startsWith(`row`)?`row`:`column`,i.alignItems=Nt(t[`align-items`],i.alignItems),i.justifyContent=Pt(t[`justify-content`],i.justifyContent),i.alignContent=Pt(t[`align-content`],i.alignContent===`stretch`?`start`:i.alignContent??`start`),i.gap=Math.max(0,P(t.gap)??i.gap),i.rowGap=Math.max(0,P(t[`row-gap`])??i.rowGap??i.gap),i.columnGap=Math.max(0,P(t[`column-gap`])??i.columnGap??i.gap),i.wrap=t[`flex-wrap`]===`wrap`?`wrap`:i.wrap??`nowrap`,i.padding=Mt(t,`padding`,i.padding),i},Lt=(e,t)=>{let n=P(t[`flex-grow`]),r=P(t[`flex-shrink`]),i=P(t.order);return{horizontal:jt(t.width,e.horizontal),vertical:jt(t.height,e.vertical),...t[`align-self`]!==void 0&&{alignSelf:Nt(t[`align-self`],`start`)},...n!==null&&{flexGrow:Math.max(0,n)},...r!==null&&{flexShrink:Math.max(0,r)},...t[`flex-basis`]!==void 0&&{flexBasis:P(t[`flex-basis`])??`auto`},...i!==null&&{order:Math.round(i)}}},Rt=(e,t)=>{if(Object.keys(t).every(e=>!At.test(e)))return null;let n=e.box??{x:0,y:0,width:1,height:1},r=e.layout??{...Be(),horizontal:{mode:`fixed`,value:n.width},vertical:{mode:`fixed`,value:n.height}},i=/rotate\(\s*(-?\d+(?:\.\d+)?)deg\s*\)/u.exec(String(t.transform??``))?.[1],a=`${String(t.overflow??``)} ${String(t[`overflow-x`]??``)} ${String(t[`overflow-y`]??``)}`,o=It(r.container,t),s=t.position;return{...r,...Lt(r,t),rotation:i===void 0?r.rotation:Number(i),position:s===`absolute`?`absolute`:[`relative`,`flow`].includes(String(s))?`flow`:r.position,clipContent:/\b(?:clip|hidden)\b/u.test(a)||r.clipContent,...o===void 0?{container:void 0}:{container:o}}},zt=(e,t)=>{if(e.box===void 0)return null;let n=P(t.left),r=P(t.top),i=P(t.width),a=P(t.height);return n===null&&r===null&&i===null&&a===null?null:{op:`setBox`,nodeId:e.id,box:{x:n??e.box.x,y:r??e.box.y,width:Math.max(1,i??e.box.width),height:Math.max(1,a??e.box.height)}}},Bt=/^(?:align|bottom|column-gap|display|flex|gap|height|justify|left|margin|order|overflow|padding|position|right|row-gap|top|transform|width)/u,Vt=e=>e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),Ht=e=>!/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu.test(e),Ut=(e,n)=>{let r=new Map((e.additionalStyles?.declarations??[]).map(e=>[e.property,e])),i=!1;for(let[e,a]of Object.entries(n)){if(p.safeParse({[e]:a}).success||Bt.test(e))continue;if(i=!0,a===null){r.delete(e);continue}let n=String(a);if(!Ht(n))throw new t(`BAD_REQUEST`,`Style ${e} contains executable CSS.`,`Remove imports, expressions, and executable URL schemes.`);r.set(e,{id:r.get(e)?.id??`css-${e}`.slice(0,200),property:e,value:n,enabled:!0})}let a=[];for(let e of r.values()){if(a.length>=128)break;a.push(e)}return i?{op:`setAdditionalStyles`,nodeId:e.id,additionalStyles:{declarations:a}}:null},Wt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[Vt(e),t])),Gt=(e,t)=>{let n=Wt(t),r=[],i=zt(e,n);i!==null&&r.push(i);let a=Object.fromEntries(Object.entries(n).filter(([e,t])=>p.safeParse({[e]:t}).success));Object.keys(a).length>0&&r.push({op:`setStyles`,nodeId:e.id,styles:p.parse(a)});let o=Rt(e,n);o!==null&&r.push({op:`setLayout`,nodeId:e.id,layout:o});let s=Ut(e,n);return s!==null&&r.push(s),n.display===`none`&&r.push({op:`setVisibility`,nodeId:e.id,visible:!1}),r},Kt=(e,n)=>{let r=e[n];if(r!==void 0)return r;throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use current stable node ids.`)},qt=(e,n)=>{let r=n.flatMap(t=>t.nodeIds.flatMap(n=>Gt(Kt(e,n),t.styles)));if(r.length===0)throw new t(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return r},Jt=x.uuid().nullable(),F=(e,n,r)=>{let i=e.safeParse(n);if(i.success)return i.data;throw new t(`BAD_REQUEST`,`${r} is invalid.`,`Run the command with --help.`)},I=e=>F(dt,e,`--base-version`),L=(e,n,r)=>{let i=Jt.safeParse(n??null);if(!i.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying the exact same command.`);e.mutationKey.select(i.data,r)},R=(e,t)=>e.mutationKey.current(`canvas.applyOperations`,{purpose:t}),z=async(e,n,r)=>{let i=f.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:n}));if(!i.success)throw new t(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(i.data.version!==r)throw new t(`CONFLICT`,`Canvas version ${String(i.data.version)} no longer matches --base-version ${String(r)}.`,`Run 'enhance canvas tree --canvas ${n}' and recompute against version ${String(i.data.version)}.`);let a=se.safeParse(i.data.document);if(a.success)return a.data;throw new t(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},B=async(e,t,n,r)=>(L(e,t.clientToken,!1),b(e.remote).execute({canvasId:j(t.canvas),mutationId:R(e,n),baseVersion:I(t.baseVersion),operations:[...r]})),Yt=(e,n,r)=>{if(!e.startsWith(`@`))return e;let i=e.slice(1);if(i===``)throw new t(`BAD_REQUEST`,`${r} @ must name a file.`,`Pass ${r} @/absolute/path/to/file or an inline value.`);let a=T.resolve(i);try{let e=C(a);if(!e.isFile()||e.size>n)throw Error(`invalid size`);return Pe(a,`utf8`)}catch{throw new t(`BAD_REQUEST`,`Could not read a bounded file at ${a}.`,`Use a regular UTF-8 file no larger than ${String(n)} bytes.`)}},V=(e,n,r)=>{let i=(()=>{try{return JSON.parse(Yt(e,1048576,r))}catch(e){throw e instanceof t?e:new t(`BAD_REQUEST`,`${r} must be valid JSON.`,`Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`)}})(),a=n.safeParse(i);if(a.success)return a.data;let o=a.error.issues[0];throw new t(`BAD_REQUEST`,`${r} is invalid${o===void 0||o.path.length===0?``:` at ${o.path.join(`.`)}`}.`,o?.message??`Correct the JSON shape and retry.`)},Xt=(e,t)=>{e.command(`set-text-content`).description(`Set Text node values.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,textContent} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.updates,gt,`--updates`).map(e=>({op:`setText`,nodeId:e.nodeId,text:e.textContent}));t.output.result(await B(t,e,`set-text-content`,n))})},Zt=(e,t)=>{e.command(`rename-nodes`).description(`Rename layers.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,name} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.updates,_t,`--updates`).map(e=>({op:`setLabel`,nodeId:e.nodeId,label:e.name,labelOrigin:`user`}));t.output.result(await B(t,e,`rename-nodes`,n))})},Qt=(e,t)=>{e.command(`delete-nodes`).description(`Delete node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.nodeIds,xt,`--node-ids`);t.output.result(await B(t,e,`delete-nodes`,n.map(e=>({op:`remove`,nodeId:e}))))})},$t=(e,t)=>{e.command(`update-styles`).description(`Update visual and layout styles.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeIds,styles} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=await z(t,j(e.canvas),I(e.baseVersion)),r=V(e.updates,vt,`--updates`);t.output.result(await B(t,e,`update-styles`,qt(n.nodes,r)))})},en=(e,t)=>{Xt(e,t),Zt(e,t),Qt(e,t),$t(e,t)},H=e=>e.space===`display-p3`?`color(display-p3 ${String(e.red)} ${String(e.green)} ${String(e.blue)} / ${String(e.alpha)})`:`rgba(${String(Math.round(e.red*255))}, ${String(Math.round(e.green*255))}, ${String(Math.round(e.blue*255))}, ${String(e.alpha)})`,U=e=>{if(!e.visible)return null;if(e.kind===`solid`)return H(e.color);if(e.kind===`image`)return`url(${JSON.stringify(e.assetId)})`;let t=e.stops.map(e=>`${H(e.color)} ${String(e.position*100)}%`).join(`, `);return e.kind===`linear-gradient`?`linear-gradient(${String(e.angle)}deg, ${t})`:`radial-gradient(at ${String(e.center.x*100)}% ${String(e.center.y*100)}%, ${t})`},tn=e=>{if(e.kind===`blur`)return`blur(${String(e.value)}px)`;if(e.kind===`hue-rotate`)return`hue-rotate(${String(e.value)}deg)`;let t=[`grayscale`,`invert`,`sepia`].includes(e.kind)?`${String(e.value*100)}%`:String(e.value);return`${e.kind}(${t})`},nn=e=>e?.flatMap(e=>{let t=U(e);return t===null?[]:[t]})??[],rn=e=>{if(e?.visible!==!0)return{};let t=U(e.paint);return{"border-width":[e.width.top,e.width.right,e.width.bottom,e.width.left].map(e=>`${String(e)}px`).join(` `),"border-style":e.style,...t!==null&&{"border-color":t}}},an=e=>{if(e?.visible!==!0)return{};let t=U(e.paint);return{"outline-width":`${String(e.width)}px`,"outline-offset":`${String(e.offset)}px`,"outline-style":e.style,...t!==null&&{"outline-color":t}}},on=e=>{let t=e.shadows?.filter(e=>e.visible).map(e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${H(e.color)}`),n=e.filters?.filter(e=>e.visible).map(tn),r=e.backdropFilters?.filter(e=>e.visible).map(tn);return{...t!==void 0&&t.length>0&&{"box-shadow":t.join(`, `)},...n!==void 0&&n.length>0&&{filter:n.join(` `)},...r!==void 0&&r.length>0&&{"backdrop-filter":r.join(` `)}}},sn=e=>{if(e===void 0)return{};let t=nn(e.fills),n=e.radius;return{...e.opacity!==void 0&&{opacity:e.opacity},...e.blendMode!==void 0&&{"mix-blend-mode":e.blendMode},...t.length>0&&{background:t.join(`, `)},...n!==void 0&&{"border-radius":[n.topLeft,n.topRight,n.bottomRight,n.bottomLeft].map(e=>`${String(e)}px`).join(` `)},...rn(e.border),...an(e.outline),...on(e)}},cn=e=>e===void 0?{}:{"font-family":[e.family,...e.fallbackFamilies].join(`, `),"font-size":`${String(e.size)}px`,"font-weight":e.weight,"font-style":e.style,"line-height":e.lineHeight.mode===`normal`?`normal`:`${String(e.lineHeight.value)}px`,"letter-spacing":`${String(e.letterSpacing)}px`,"text-align":e.align,"text-transform":e.transform,"text-decoration-line":e.decoration.line,"text-decoration-style":e.decoration.style,"white-space":e.wrapping},W=e=>e===`start`?`flex-start`:e===`end`?`flex-end`:e,ln=(e,t)=>e.mode===`fixed`?`${String(e.value)}px`:e.mode===`fill`?`100%`:`${String(t)}px`,un=(e,t)=>({position:e.position===`absolute`?`absolute`:`relative`,...e.position===`absolute`&&{left:`${String(t.x)}px`,top:`${String(t.y)}px`},width:ln(e.horizontal,t.width),height:ln(e.vertical,t.height),...e.clipContent===!0&&{overflow:`hidden`}}),dn=e=>{let t=[...e.rotation===0?[]:[`rotate(${String(e.rotation)}deg)`],...e.flipHorizontal===!0?[`scaleX(-1)`]:[],...e.flipVertical===!0?[`scaleY(-1)`]:[]];return t.length===0?{}:{transform:t.join(` `)}},fn=e=>{if(typeof e!=`object`)return e===`auto`?e:`${String(e)}px`;let t=`${String(e.ratio*100)}%`,n=e.offset??0;return n===0?t:`calc(${t} ${n<0?`-`:`+`} ${String(Math.abs(n))}px)`},pn=e=>({...e.alignSelf!==void 0&&{"align-self":W(e.alignSelf===`auto`?`start`:e.alignSelf)},...e.flexGrow!==void 0&&{"flex-grow":e.flexGrow},...e.flexShrink!==void 0&&{"flex-shrink":e.flexShrink},...e.flexBasis!==void 0&&{"flex-basis":fn(e.flexBasis)},...e.order!==void 0&&{order:e.order}}),mn=e=>{let t=e.container;return t===void 0?{}:{display:`flex`,"flex-direction":t.direction,"align-items":W(t.alignItems),"align-content":W(t.alignContent??`start`),"justify-content":W(t.justifyContent),gap:`${String(t.gap)}px`,"row-gap":`${String(t.rowGap??t.gap)}px`,"column-gap":`${String(t.columnGap??t.gap)}px`,"flex-wrap":t.wrap??`nowrap`,padding:[t.padding.top,t.padding.right,t.padding.bottom,t.padding.left].map(e=>`${String(e)}px`).join(` `)}},hn=e=>{let t=Object.fromEntries((e.additionalStyles?.declarations??[]).filter(e=>e.enabled).map(e=>[e.property,e.value])),n=e.layout===void 0||e.box===void 0?{}:{...un(e.layout,e.box),...dn(e.layout),...pn(e.layout),...mn(e.layout)};return{...e.styles,...t,...cn(e.typography),...sn(e.appearance),...n,...e.visible===!1&&{display:`none`}}},gn=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),_n=(e,n)=>{let r=e.nodes[n];if(r===void 0)throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use a current stable node id.`);return r},G=(e,t)=>{let n=e.props?.[t];return typeof n==`string`?n:``},vn=e=>`{${JSON.stringify(e)}}`,yn=(e,t,n,r)=>{let i=_n(e,t),a=` `.repeat(n),o=[`data-node-id=${JSON.stringify(i.id)}`,`data-name=${JSON.stringify(i.label)}`,`style={${JSON.stringify(hn(i))}}`];if(i.locked===!0&&o.push(`data-locked="true"`),i.component===`image`)return`${a}<img ${o.join(` `)} alt=${JSON.stringify(G(i,`alt`))} src=${JSON.stringify(G(i,`src`))} />`;if(i.component===`svg`)return`${a}<div ${o.join(` `)} data-component="svg" />`;let s=i.component===`text`?`span`:`div`,c=i.component===`text`?vn(G(i,`text`)):``,l=(n>=r?[]:gn(e,t)).map(t=>yn(e,t,n+1,r));return c===``&&l.length===0?`${a}<${s} ${o.join(` `)} />`:[`${a}<${s} ${o.join(` `)}>`,...c===``?[]:[`${a} ${c}`],...l,`${a}</${s}>`].join(`
|
|
5
|
+
`)},bn=(e,t,n)=>yn(e,t,0,n),xn=(e,t)=>t.map(t=>{let n=_n(e,t);return{nodeId:t,name:n.label,component:n.component,box:n.box,css:hn(n),layout:n.layout,appearance:n.appearance,typography:n.typography}}),Sn={topic:`canvas-agent-authoring`,workflow:[`Run canvas inspect, then canvas tree, before editing.`,`Render the target before changing it and inspect the PNG.`,`Write small visual groups incrementally with write-html.`,`Use duplicate-nodes, set-text-content, update-styles, and move-nodes instead of rewriting existing structure.`,`Use flex, padding, and gap as the primary layout tools. Avoid margin, grid, tables, and inline layout.`,`Every write requires the exact version returned by the latest read.`,`Inspect the review PNG returned by write-html and correct visual discrepancies.`,`Automatic commands show and clear their work indicator. Finish a manual work lease explicitly.`],html:{modes:[`insert-children`,`replace`],rules:[`Use inline styles and concrete CSS values.`,`Use layer-name for meaningful hierarchy names.`,`One call should add roughly one visual group.`,`Styled text controls become a frame plus an editable text child.`,`Scripts, event handlers, embedded documents, executable URLs, and CSS imports are rejected.`]},completion:[`The hierarchy is natural and uses the fewest useful editable primitives.`,`The affected version and node ids match the intended change.`,`The post-write PNG has been inspected.`,`Text, layout, paint, effects, and additional CSS remain editable in the ordinary inspector.`]},Cn=async(e,t)=>{let n=f.parse(await e.remote.query(`canvas.document.get`,{canvasId:t}));return{held:n,document:se.parse(n.document)}},wn=(e,t)=>{e.command(`guide`).description(`Agent design workflow.`).action(()=>{t.output.result(Sn)}),e.command(`get-jsx`).description(`Read concise subtree JSX.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-id <id>`,`Stable subtree root id.`).option(`--depth <integer>`,`Maximum descendant depth from 0 to 20.`,`8`).action(async e=>{let n=j(e.canvas),{held:r,document:i}=await Cn(t,n);t.output.result({canvasId:n,version:r.version,nodeId:e.nodeId,jsx:bn(i,e.nodeId,F(St,e.depth,`--depth`)),warning:`This is a structural reading projection. Use canvas render as the pixel authority.`})}),e.command(`get-computed-styles`).description(`Read effective node CSS.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).action(async e=>{let n=j(e.canvas),{held:r,document:i}=await Cn(t,n),a=V(e.nodeIds,xt,`--node-ids`);t.output.result({canvasId:n,version:r.version,nodes:xn(i,a)})})},K=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),Tn=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),q=(e,n)=>{let r=e.nodes[n];if(r!==void 0)return r;throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use a current stable node id.`)},En=(e,t)=>{let n=new Set,r=t=>{for(let i of K(e,t))n.add(i),r(i)};return r(t),n},Dn=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},On=e=>{let t=0;return n=>(t+=1,`${Dn(e)}_${Dn(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},kn=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of K(e,t))r(n)};return r(t),n},An=(e,t,n)=>Object.fromEntries(kn(e,t).map(t=>[t,n(q(e,t).label)])),jn=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=q(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let p=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??p}}},Mn=e=>{let{document:n,input:r,inputIndex:i,nextId:a}=e,o=q(n,r.id);if(r.id===`root`)throw new t(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let s=n.relationships[r.id];if(s===void 0)throw new t(`BAD_REQUEST`,`Canvas node ${r.id} is detached.`,`Choose a reachable node from canvas tree.`);let c=r.parentId??s.parentId;if(!Tn(n.nodes[c]))throw new t(`BAD_REQUEST`,`Canvas node ${c} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let l=An(n,r.id,a),u={document:n,rootId:r.id,parentId:c,inputIndex:i,sourceSortKey:s.sortKey,map:l},d=kn(n,r.id).map(e=>jn(u,e)),f=l[r.id];if(f===void 0)throw Error(`Missing duplicate root id for ${r.id}`);return{operations:d,summary:{sourceId:r.id,newId:f,name:o.label,component:o.component,descendantIdMap:Object.fromEntries(Object.entries(l).filter(([e])=>e!==r.id))}}},Nn=(e,n,r)=>{if(n.length===0)throw new t(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let i=On(r),a=n.map((t,n)=>Mn({document:e,input:t,inputIndex:n,nextId:i}));return{operations:a.flatMap(e=>e.operations),duplicatedNodes:a.map(e=>e.summary)}},Pn=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,K(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),Fn=(e,t)=>{let n=(t.children.get(e.parentId)??[]).filter(t=>t!==e.nodeId);return{parentId:e.parentId,index:Math.max(0,Math.min(e.index??n.length,n.length))}},In=(e,n)=>{let r=`before`in e?e.before:e.after;if(r===e.nodeId||n.document.nodes[r]===void 0)throw new t(`BAD_REQUEST`,`Sibling ${r} is not a valid move target.`,`Choose another current sibling node.`);let i=n.parentOf.get(r);if(i===void 0)throw new t(`BAD_REQUEST`,`Sibling ${r} is detached.`,`Choose a reachable sibling from canvas tree.`);let a=(n.children.get(i)??[]).filter(t=>t!==e.nodeId).indexOf(r);return{parentId:i,index:`before`in e?a:a+1}},Ln=(e,t)=>`parentId`in e?Fn(e,t):In(e,t),Rn=(e,n,r)=>{if(e.nodeId===`root`||r.document.nodes[e.nodeId]===void 0)throw new t(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(En(r.document,e.nodeId).has(n.parentId)||!Tn(r.document.nodes[n.parentId]))throw new t(`BAD_REQUEST`,`Canvas node ${n.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},zn=(e,t,n)=>{let r=n.parentOf.get(e.nodeId);r!==void 0&&(n.children.set(r,(n.children.get(r)??[]).filter(t=>t!==e.nodeId)),n.affected.add(r));let i=[...n.children.get(t.parentId)??[]];i.splice(t.index,0,e.nodeId),n.children.set(t.parentId,i),n.parentOf.set(e.nodeId,t.parentId),n.affected.add(t.parentId);let a=i[t.index-1];return{op:`move`,nodeId:e.nodeId,parentId:t.parentId,...a!==void 0&&{afterId:a}}},Bn=(e,n)=>{if(n.length===0)throw new t(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let r=Pn(e),i=[];return{operations:n.map(e=>{let t=Ln(e,r);return Rn(e,t,r),i.push({nodeId:e.nodeId,...t}),zn(e,t,r)}),moves:i,affectedParents:Array.from(r.affected,e=>({parentId:e,children:[...r.children.get(e)??[]]}))}},Vn=(e,t)=>{e.command(`duplicate-nodes`).description(`Deep-clone node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--nodes <json-or-@path>`,`Array of {id,parentId?} requests.`).option(`--id-prefix <prefix>`,`Stable namespace for cloned ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{L(t,e.clientToken,!1);let n=j(e.canvas),r=I(e.baseVersion),i=await z(t,n,r),a=R(t,`duplicate-nodes`),o=Nn(i,V(e.nodes,yt,`--nodes`),e.idPrefix??`copy_${a.replaceAll(`-`,``)}`),s=await b(t.remote).execute({canvasId:n,mutationId:a,baseVersion:r,operations:[...o.operations]});t.output.result({duplicatedNodes:o.duplicatedNodes,apply:s})})},Hn=(e,t)=>{e.command(`move-nodes`).description(`Reorder or reparent nodes.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--moves <json-or-@path>`,`Sequential before, after, or parent/index moves.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{L(t,e.clientToken,!1);let n=j(e.canvas),r=I(e.baseVersion),i=Bn(await z(t,n,r),V(e.moves,bt,`--moves`)),a=await b(t.remote).execute({canvasId:n,mutationId:R(t,`move-nodes`),baseVersion:r,operations:[...i.operations]});t.output.result({moves:i.moves,affectedParents:i.affectedParents,apply:a})})},Un=(e,t)=>{Vn(e,t),Hn(e,t)},Wn=262144,Gn=e=>{let n=Yt(e,Wn,`--html`);if(Buffer.byteLength(n,`utf8`)>Wn)throw new t(`BAD_REQUEST`,`--html exceeds 262144 bytes.`,`Write one visual group at a time, as taught by canvas guide.`);return n},Kn=new Set([`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`]),qn=(e,n)=>{e.command(`write-html`).description(`Compile HTML/CSS primitives.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--target-node-id <id>`,`Container receiving children, or node to replace.`).requiredOption(`--html <html-or-@path>`,`Inline HTML fragment or @path to a UTF-8 file.`).option(`--mode <mode>`,`insert-children or replace.`,`insert-children`).option(`--id-prefix <prefix>`,`Stable namespace for generated node ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact write and review.`).option(`--output <path>`,`Write the review PNG to this path.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--scale <number>`,`Review pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--timeout-ms <integer>`,`Review render polling deadline.`,`120000`).addHelpText(`after`,`
|
|
6
|
+
Write one visual group at a time. Use flex, padding and gap; use targeted commands for later edits. Inspect the returned PNG.
|
|
7
|
+
`).action(async e=>{if(![`insert-children`,`replace`].includes(e.mode))throw new t(`BAD_REQUEST`,`--mode must be insert-children or replace.`,`Choose one of the two documented modes.`);L(n,e.clientToken,!0);let r=e.mode===`replace`?`replace`:`insert-children`;n.output.result(await n.invocation.invoke({capability:M(n.catalog(),`canvas.writeHtml`),arguments:{canvasId:j(e.canvas),targetNodeId:e.targetNodeId,mode:r,html:Gn(e.html),...e.idPrefix!==void 0&&{idPrefix:e.idPrefix},baseVersion:I(e.baseVersion),renderOutputPath:e.output??null,overwriteRender:e.force===!0,renderScale:F(ft,e.scale,`--scale`),renderTimeoutMs:F(dt,e.timeoutMs,`--timeout-ms`)},clientToken:e.clientToken??null}))})},Jn=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),Yn=(e,t)=>typeof t==`number`&&!Kn.has(e)?`${String(t)}px`:String(t),Xn=e=>Object.entries(e).filter(([,e])=>e!==null).map(([e,t])=>{let n=Jn(e);return`${n}:${Yn(n,t??``)}`}).join(`;`).replaceAll(`&`,`&`).replaceAll(`"`,`"`),Zn=e=>e.length===0?0:Math.max(...e.map(e=>e.x+e.width))+80,Qn=(e,n)=>{e.command(`create-artboard`).description(`Create a top-level frame.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--name <name>`,`Meaningful layer name.`).requiredOption(`--styles <json-or-@path>`,`CSSProperties with width and height.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact creation and review.`).option(`--output <path>`,`Review PNG path.`).option(`--force`,`Replace an existing review PNG.`,!1).action(async e=>{let r=V(e.styles,ht,`--styles`);if(r.width===void 0||r.height===void 0)throw new t(`BAD_REQUEST`,`--styles must include width and height.`,`Use explicit whole-pixel dimensions such as 1440px and 900px.`);L(n,e.clientToken,!0);let i=j(e.canvas),a=I(e.baseVersion),o=await z(n,i,a),s=Object.entries(o.relationships).flatMap(([e,t])=>{let n=o.nodes[e]?.box;return n!==void 0&&t.parentId===`root`?[n]:[]}),c={display:`flex`,flexDirection:`column`,...r,left:Zn(s),top:0,position:`absolute`},l=e.name.replaceAll(`&`,`&`).replaceAll(`"`,`"`);n.output.result(await me(n.remote,n.render).execute({canvasId:i,targetNodeId:`root`,mode:`insert-children`,html:`<div layer-name="${l}" data-enhance-kind="frame" style="${Xn(c)}"></div>`,idPrefix:`artboard_${n.mutationKey.current(`canvas.render.importSource`,{canvasId:i})}`,baseVersion:a,renderClientToken:n.mutationKey.current(`canvas.render.create`,{purpose:`create-artboard-review`}),renderOutputPath:e.output??null,overwriteRender:e.force===!0,renderScale:1,renderTimeoutMs:12e4}))})},$n=(e,t)=>{qn(e,t),Qn(e,t)},er=(e,t)=>{wn(e,t),$n(e,t),en(e,t),Un(e,t),kt(e,t)},tr=x.coerce.number().int().positive(),nr=x.coerce.number().int().nonnegative(),rr=x.coerce.number().min(ne).max(4),J=(e,n,r,i=`canvas render`)=>{let a=e.safeParse(n);if(!a.success)throw new t(`BAD_REQUEST`,`${r} is invalid.`,`Run 'enhance ${i} --help'.`);return a.data},ir=e=>{if(e===void 0)return null;try{let t=de.safeParse(JSON.parse(e));if(t.success)return t.data}catch{}throw new t(`BAD_REQUEST`,`--bounds must be a finite positive world rectangle.`,`Pass JSON such as '{"x":0,"y":0,"width":800,"height":600}'.`)},ar=(e,t)=>e===void 0?t===null?{kind:`content`}:{kind:`bounds`,bounds:t}:{kind:`node`,nodeId:e},or=e=>{if(!(typeof e!=`string`||!e.startsWith(`rec_`)))return x.uuid().safeParse(e.slice(4)).data},sr=(e,n)=>{let r=x.uuid().nullable().safeParse(n??null);if(!r.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact render.`);return e.mutationKey.select(r.data,!1),e.mutationKey.current(`canvas.render.create`,{})},cr=async(e,n)=>{if(e.canvas===void 0)throw new t(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);if(e.nodeId!==void 0&&e.bounds!==void 0)throw new t(`BAD_REQUEST`,`--node-id and --bounds cannot be combined.`,`Choose one focused target, or omit both to render all authored content.`);if(e.atMs!==void 0&&e.nodeId===void 0)throw new t(`BAD_REQUEST`,`--at-ms requires --node-id.`,"Render the stable recording node returned by `enhance canvas tree`.");let r=e.atMs===void 0?null:or(e.nodeId);if(r===void 0&&e.atMs!==void 0)throw new t(`BAD_REQUEST`,`--at-ms requires a stable recording node id such as rec_<recording-uuid>.`,"Run `enhance canvas tree --canvas <url-or-id>` and choose a recording node.");sr(n,e.clientToken);let i=await n.invocation.invoke({capability:M(n.catalog(),`canvas.render`),arguments:{canvasId:j(e.canvas),expectedVersion:e.expectedVersion===void 0?null:J(tr,e.expectedVersion,`--expected-version`),target:ar(e.nodeId,ir(e.bounds)),sourceState:r==null?null:{kind:`recording`,recordingId:r,atMs:J(nr,e.atMs??``,`--at-ms`)},scale:J(rr,e.scale,`--scale`),outputPath:e.output??null,overwrite:e.force===!0,timeoutMs:J(tr,e.timeoutMs,`--timeout-ms`)},clientToken:e.clientToken??null});n.output.result(i)},lr=e=>{let n=e.options.find(e=>e.long===`--canvas-id`);n!==void 0&&(n.makeOptionMandatory(!1),e.option(`--canvas <url-or-id>`,`Pasted Enhance canvas URL or bare canvas UUID.`),e.hook(`preAction`,e=>{let n=e.getOptionValue(`canvas`),r=e.getOptionValue(`canvasId`);if(n!==void 0&&r!==void 0)throw new t(`BAD_REQUEST`,`--canvas and --canvas-id cannot be combined.`,`Pass the pasted URL or UUID through --canvas.`);let i=n??r;if(typeof i!=`string`)throw new t(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);e.setOptionValueWithSource(`canvasId`,j(i),`cli`)}))},ur=(e,t)=>{e.option(`--canvas <url-or-id>`,`Canvas URL or UUID to render.`).option(`--node-id <id>`,`Render one stable canvas node instead of all authored content.`).option(`--bounds <json>`,`Render an explicit rectangle in canvas world coordinates.`).option(`--expected-version <integer>`,`Refuse pixels from any other document version.`).option(`--at-ms <integer>`,`Pause a recording node at this millisecond; inspect the PNG before snapshotting it.`).option(`--scale <number>`,`Output pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--output <path>`,`Write the PNG to this path instead of a protected temporary file.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--timeout-ms <integer>`,`Local polling deadline in milliseconds.`,`120000`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this render request.`).addHelpText(`after`,`
|
|
8
|
+
For transcript-led selection, inspect nearby --at-ms renders and reject transitions or duplicate states before running recording snapshot.
|
|
9
|
+
`).action(async e=>cr(e,t))},dr=(e,t)=>{let n=e.commands.find(e=>e.name()===`canvas`);if(n===void 0)throw TypeError(`the API router did not supply canvas commands`);let r=n.commands.find(e=>e.name()===`render`);if(r===void 0)throw TypeError(`the API router did not supply canvas render`);let i=he(t.remote,be(t.configDirectory),t.now,t.output.result);ut(n,t),er(n,{...t,render:i});for(let e of[`inspect`,`tree`,`node`,`selection`]){let t=n.commands.find(t=>t.name()===e);t!==void 0&&lr(t)}ur(r,t)},fr={"canvas.createEditableFrame":`Insert editable primitives beside a source screen.`,"canvas.create":`Create a canvas and return its id.`,"canvas.get":`Read one canvas and viewer access.`,"canvas.setAccess":`Change canvas link access.`,"canvas.markViewed":`Mark a canvas as viewed.`,"canvas.list":`Find canvases by shelf, title, access, or state.`,"canvas.rename":`Rename a canvas.`,"canvas.setReviewState":`Change your canvas review state.`,"canvas.delete":`Move a canvas to its recoverable bin.`,"canvas.move":`Move a canvas between shelves.`,"canvas.duplicate":`Copy a canvas into a shelf.`,"canvas.deletePermanently":`Permanently delete a binned canvas.`,"canvas.restore":`Restore a binned canvas.`,"canvas.inspect":`Summarize a canvas and suggest inspection commands.`,"canvas.tree":`List canvas node ids, hierarchy, kinds, and boxes.`,"canvas.node":`Read one canvas node and its children.`,"canvas.selection":`Read the person’s current live browser selection.`,"canvas realtime":`Canvas presence and activity.`,"canvas document":`Read or replace a canvas document.`,"canvas version":`Retained canvas history.`,"canvas render":`Create and inspect faithful canvas renders.`,"canvas participants":`List and change canvas participants.`,"canvas invites":`Invite people to a canvas.`},pr=(e,t=!1)=>{let n=Symbol(`explicit-null`),r=e.parseArg;return r===void 0?()=>!1:(e.argParser((e,i)=>{if(t&&e===`null`)return n;try{return r(e,i)}catch(t){try{return r(JSON.stringify(e),i)}catch{throw t}}}),e=>e===n)},mr=()=>({exit:e=>{throw new m(e)}}),hr={canvas:`Canvases: create, find, share, and manage review surfaces.`,"canvas render":`Render production-faithful canvas pixels after inspecting exact structure and geometry.`,"canvas version":`Inspect and name retained canvas history.`,"canvas document":`Read or replace the opaque document stored on a canvas.`,"canvas invites":`Invite people to a canvas and manage pending invitations.`,"canvas participants":`List and change the people who can reach a canvas.`,comment:`Comment threads and replies anchored to canvas content.`,organisation:`Teams the authenticated person belongs to or creates.`,"organisation invites":`Invite people to a team and manage pending invitations.`,"organisation people":`Team roster membership and roles.`,person:`The current person, sharing recipients, and agent tokens.`,"person recipients":`People available when choosing sharing recipients.`,recording:`Recorded walkthroughs, chunks, recovery, and completion.`,"recording-asset":`External page assets mirrored for durable replay.`,screen:`Captured pages uploaded for placement on a canvas.`},gr=new Set([`canvas.invites.accept`,`canvas.invites.preview`,`organisation.invites.accept`,`organisation.invites.preview`]),_r=new Set([`canvas.create --organisation-id`,`canvas.create --source-url`,`recording.start --audio`,`recording.start --page-title`,`screen.create --page-title`,`screen.create --provenance`,`screen.create --route`]),vr=new Set([`comment.resolve --resolved`,`recording.start --page-title`,`recording.start --viewport`,`screen.create --page-title`,`screen.create --provenance`,`screen.create --route`,`screen.create --viewport`]),yr=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,Y=e=>{let t=yr(Reflect.get(e,`__trpcCli`)),n=t===null?void 0:t.path;return typeof n==`string`?n:null},br=(e,t,n,r)=>{let i=t.long,a=Y(e)??r.join(` `),o=a===``||i===void 0?void 0:_[`${a} ${i}`];if(o!==void 0)return o;if(i!==void 0&&_[i]!==void 0)return _[i];let s=(n.split(/Any of:|One of:/u,1)[0]?.trim()??``).split(`;`).map(e=>e.trim()).filter(e=>e!==``&&[`Format:`,`Pattern:`,`Min length:`,`Max length:`].every(t=>!e.startsWith(t))).join(`; `);return s===``?`Value for ${i??t.attributeName()} on ${e.name()}.`:s},xr=(e,n,r)=>{let i=mr();e.exitOverride(e=>i.exit(e.exitCode)),e.configureOutput({writeOut:e=>n.output.logger.info?.(e),writeErr:e=>n.output.logger.error?.(e)}),e.showHelpAfterError(!1).showSuggestionAfterError(!1);let a=[],o=[];for(let t of e.options){let n=Y(e)??r.join(` `);vr.has(`${n} ${t.long??``}`)&&o.push({flag:t.long??``,name:t.attributeName()});let i=_r.has(`${n} ${t.long??``}`),s=pr(t,i);i&&a.push({name:t.attributeName(),matches:s}),t.description=br(e,t,t.description,r)}a.length>0&&e.hook(`preAction`,e=>{for(let t of a)t.matches(e.getOptionValue(t.name))&&e.setOptionValueWithSource(t.name,null,`cli`)}),o.length>0&&e.hook(`preAction`,e=>{if(e.getOptionValueSource(`json`)===`cli`)return;let n=o.find(({name:t})=>e.getOptionValueSource(t)!==`cli`);if(n!==void 0)throw new t(`BAD_REQUEST`,`${n.flag} is required unless --json supplies the complete input.`,`Pass ${n.flag} explicitly, including false or null when that is the intended value.`)})},Sr=(e,n,r,i)=>{(r!==null&&i.mutationPaths.has(r)||n[0]===`fixture`)&&(e.options.every(e=>e.long!==`--client-token`)&&e.option(`--client-token <uuid>`,_[`--client-token`]),e.hook(`preAction`,e=>{let r=e.getOptionValue(`clientToken`),a=x.uuid().nullable().safeParse(r??null);if(!a.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact command.`);i.mutationKey.select(a.data,n[0]===`fixture`)}))},Cr=(e,t,n)=>{n===null||!gr.has(n)||(e.options.find(e=>e.long===`--token`)?.makeOptionMandatory(!1),e.hook(`preAction`,async e=>{let n=e.getOptionValue(`token`);if(n===void 0&&e.getOptionValue(`json`)!==void 0)return;let r=await Qe(typeof n==`string`?n:void 0,`enhance ${t.join(` `)}`);e.setOptionValueWithSource(`token`,r,`cli`)}))},wr=(e,t,n,r)=>{let i=hr[t.join(` `)];i===void 0?n!==null&&e.description(ae[n]??r.get(n)??`Run the ${n} API operation.`):e.description(i);let a=fr[t.join(` `)]??(n===null?void 0:fr[n]);a!==void 0&&e.summary(a)},Tr=(e,t,n=[])=>{xr(e,t,n);for(let r of e.commands){let e=[...n,r.name()],i=Y(r);Sr(r,e,i,t),wr(r,e,i,t.descriptions),Cr(r,e,i),Tr(r,t,e)}},Er=te().excludedProcedures,Dr=new Set([`canvas thumbnail`,`telemetry`]),Or=e=>{let t=Reflect.get(e,`__trpcCli`);if(typeof t!=`object`||!t)return null;let n=Reflect.get(t,`path`);return typeof n==`string`?n:null},kr=(e,t=[])=>{let n=e.commands.filter(e=>{let n=Or(e),r=[...t,e.name()].join(` `);return!Dr.has(r)&&(n===null||!Er.has(n))});Reflect.set(e,`commands`,n);for(let e of n)kr(e,[...t,e.name()])},Ar=e=>{let t=Reflect.get(e,`__trpcCli`);if(typeof t!=`object`||!t)return null;let n=Reflect.get(t,`path`);return typeof n==`string`?n:null},jr=(e,t=[])=>e.commands.filter(e=>e.name()!==`help`).flatMap(e=>{let n=[...t,e.name()],r=Ar(e);return[{path:n.join(` `),procedure:r,description:e.description(),kind:r===null?e.commands.length>0?`namespace`:`utility`:`derived`,helpCharacters:e.helpInformation().length},...jr(e,n)]}),Mr=(e,t,n)=>{e.command(`commands`).description(`Emit the command inventory as NDJSON without walking the help tree.`).option(`--namespace <path>`,`Keep commands at or below this space-separated path.`).option(`--capabilities`,`Emit the transport-neutral capability inventory.`,!1).option(`--reference`,`Emit complete shared capability contracts for documentation.`,!1).action(r=>{if(r.reference){let e=oe(n()),r=ce(e);t.result({items:e.map(e=>r.describe(e.id)),truncated:!1});return}if(r.capabilities){t.result({items:Ce(n()),truncated:!1});return}let i=r.namespace?.trim(),a=jr(e).filter(e=>i===void 0||e.path===i||e.path.startsWith(`${i} `));t.result({items:a,truncated:!1})})},Nr=(e,t,n,r)=>{let i=e.commands.find(e=>e.name()===`comment`);if(i===void 0)throw TypeError(`derived comment namespace is missing`);i.command(`attention`).description(`List every open comment needing attention; source metadata is included when a capture has it.`).argument(`<canvas-url-or-id>`,`A pasted Enhance canvas URL shaped /c/<UUID>, or a bare canvas UUID.`).action(async e=>{r.result(await t.invoke({capability:M(n(),`comment.attention`),arguments:{canvasId:j(e)},clientToken:null}))})},Pr=(e,t)=>{let{version:n,credentials:r,remote:i,output:a}=t;e.command(`doctor`).description(`Check the installed binary, API reachability, and credential file without changes.`).action(async()=>{let[e,t]=await Promise.all([i.health(),r.read()]);a.result({status:t!==null&&e.reachable?`ok`:`degraded`,binary:S.argv[1]??`enhance`,version:n,api:e,credential:{path:r.path,present:t!==null}})})},Fr=e=>x.coerce.number().int().positive().parse(e),Ir=x.record(x.string(),x.unknown()),Lr=(e,t)=>{let n=Ir.safeParse(e);if(!n.success)return 0;let r=n.data.atMs;if(typeof r==`number`&&Number.isFinite(r))return Math.max(0,Math.round(r));let i=n.data.timestamp;return typeof i==`number`&&Number.isFinite(i)?Math.max(0,Math.round(i-t)):0},Rr=async e=>{let t=(await Re(e,`utf8`)).split(`
|
|
10
|
+
`).filter(e=>e.trim()!==``).map(e=>JSON.parse(e)),n=t.map(e=>Ir.safeParse(e).data?.timestamp).find(e=>typeof e==`number`&&Number.isFinite(e));return t.map(e=>({atMs:Lr(e,n??0),event:e}))},zr=async e=>({clientToken:e.clientToken??E(),body:await Re(e.file),route:e.route??null,pageTitle:e.pageTitle??T.basename(e.file),viewport:{width:e.width,height:e.height},provenance:null}),X=e=>e.option(`--width <pixels>`,`Captured viewport width.`,Fr,1440).option(`--height <pixels>`,`Captured viewport height.`,Fr,900),Br=(e,t,n)=>{X(e.command(`screen`).description(`Upload one captured page and return its reusable screen id.`).requiredOption(`--file <path>`,`File containing the captured HTML bytes.`).option(`--client-token <uuid>`,`Stable UUID to reuse when retrying the same upload.`).option(`--route <url>`,`Original browser route, when it is safe to retain.`).option(`--page-title <title>`,`Captured page title.`)).action(async e=>{n.result(await t(await zr(e)))})},Vr=(e,t,n)=>{X(e.command(`recording`).description(`Upload NDJSON rrweb events as a walkthrough; chunk offsets start at the first event.`).requiredOption(`--file <path>`,'NDJSON with one rrweb event per line; minimum example: `{"type":2,"timestamp":1000}`.').requiredOption(`--source-url <url>`,`Required route the recording represents.`).option(`--page-title <title>`,`Title for a newly created walkthrough canvas.`).option(`--canvas-id <uuid>`,`Existing canvas to receive the walkthrough.`)).action(async e=>{n.result(await t({entries:await Rr(e.file),sourceUrl:e.sourceUrl,pageTitle:e.pageTitle??null,viewport:{width:e.width,height:e.height},...e.canvasId!==void 0&&{canvasId:e.canvasId}}))})},Hr=(e,t,n)=>{X(e.command(`world`).description(`Create a team, a canvas, and zero or more attached screen fixtures.`).requiredOption(`--organisation-name <name>`,`Name of the team to create.`).requiredOption(`--canvas-title <title>`,`Title of the canvas to create.`).option(`--screen <path...>`,`Captured HTML files to upload and attach.`)).action(async e=>{let r=[],i=e.screen??[];for(let t of i)r.push(await zr({file:t,width:e.width,height:e.height}));n.result(await t({organisationName:e.organisationName,canvasTitle:e.canvasTitle,screens:r}))})},Ur=(e,t,n)=>{let r=e.command(`fixture`).description(`Build deterministic product fixtures.`);Br(r,t.screen,n),Vr(r,t.recording,n),Hr(r,t.world,n)},Wr=e=>x.coerce.number().parse(e),Gr=e=>x.coerce.number().positive().parse(e),Kr=e=>x.coerce.number().int().positive().parse(e),qr=(e,t,n,r)=>{(e.commands.find(e=>e.name()===`prototype`)??e.command(`prototype`).description(`Publish static frontend prototypes.`)).command(`publish`).description(`Package and publish an unpacked static build directory. The CLI creates the upload artifact.`).requiredOption(`--canvas-id <uuid>`,`Canvas that receives the prototype.`).requiredOption(`--directory <path>`,`Unpacked static build directory; do not pass a ZIP file.`).requiredOption(`--title <title>`,`Label above the prototype frame.`).requiredOption(`--base-version <number>`,`Current canvas document version.`,Kr).option(`--prototype-id <uuid>`,`Existing prototype identity to publish a new deployment.`).option(`--client-token <uuid>`,`Stable retry token for this exact build.`).option(`--node-id <id>`,`Stable canvas node id for a new prototype.`).option(`--entry <path>`,`HTML entry relative to the uploaded directory.`,`index.html`).option(`--x <pixels>`,`Canvas x coordinate.`,Wr,48).option(`--y <pixels>`,`Canvas y coordinate.`,Wr,48).option(`--width <pixels>`,`Prototype viewport width.`,Gr,1440).option(`--height <pixels>`,`Prototype viewport height.`,Gr,900).action(async e=>{let i=e.clientToken??E();r.result(await t.invoke({capability:M(n(),`prototype.publish`),arguments:{canvasId:e.canvasId,prototypeId:e.prototypeId??null,nodeId:e.nodeId??`proto_${i.replaceAll(`-`,``)}`,title:e.title,directory:e.directory,entryPath:e.entry,baseVersion:e.baseVersion,box:{x:e.x,y:e.y,width:e.width,height:e.height}},clientToken:i}))})},Jr=(e,n,r)=>{let i=(r?x.coerce.number().int().positive():x.coerce.number().int().nonnegative()).safeParse(e);if(!i.success)throw new t(`BAD_REQUEST`,`${n} is invalid.`,`Run 'enhance recording snapshot --help'.`);return i.data},Yr=(e,n)=>{let r=e.commands.find(e=>e.name()===`recording`);if(r===void 0)throw TypeError(`the API router did not supply recording commands`);r.command(`snapshot`).description(`Persist one visually accepted recording moment as an ordinary screen and frame.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID containing the recording.`).requiredOption(`--recording-id <uuid>`,`Recording UUID returned by recording list.`).requiredOption(`--at-ms <integer>`,`Accepted recording timestamp in milliseconds.`).option(`--timeout-ms <integer>`,`Local polling deadline in milliseconds.`,`120000`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this exact snapshot.`).addHelpText(`after`,`
|
|
11
|
+
Preview first: canvas render --node-id rec_<recording-uuid> --at-ms <integer>, then inspect its PNG. This command persists the accepted moment.
|
|
12
|
+
`).action(async e=>{let r=x.uuid().nullable().safeParse(e.clientToken??null),i=x.uuid().safeParse(e.recordingId);if(!r.success||!i.success)throw new t(`BAD_REQUEST`,`The recording id or client token is not a UUID.`,"Use the recording id from `recording list`; mint one client token per accepted moment.");n.output.result(await n.invocation.invoke({capability:M(n.catalog(),`recording.snapshot`),arguments:{canvasId:j(e.canvas),recordingId:i.data,atMs:Jr(e.atMs,`--at-ms`,!1),timeoutMs:Jr(e.timeoutMs,`--timeout-ms`,!0)},clientToken:r.data}))})},Xr=(e,n,r)=>{if(e!==`canvas.document.save`||typeof r!=`object`||!r||!(`outcome`in r)||r.outcome!==`conflict`)return r;throw new t(`CONFLICT`,`The canvas document changed before this save landed.`,`Run 'enhance canvas document get --canvas-id ${typeof n==`object`&&n&&`canvasId`in n&&typeof n.canvasId==`string`?n.canvasId:`<canvas-id>`}', merge your change into that document, then retry with its version.`)},Zr=(e,t)=>ze(e,e=>({[e]:{query:async n=>t.query(e,n),mutate:async n=>Xr(e,n,await t.mutate(e,n))}})),Qr=(e,n)=>{let r=e.commands.find(e=>e.name()===`transcript`);if(r===void 0)throw TypeError(`the API router did not supply transcript commands`);r.command(`get`).description(`Read timestamped speech cues as candidate moments; render and inspect candidate PNGs before snapshotting.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID containing the recording.`).requiredOption(`--recording-id <uuid>`,`Recording UUID returned by recording list.`).action(async e=>{let r=x.uuid().safeParse(e.recordingId);if(!r.success)throw new t(`BAD_REQUEST`,`--recording-id must be a UUID.`,"Use the recording id returned by `enhance recording list`.");n.output.result(await n.invocation.invoke({capability:M(n.catalog(),`transcript.read`),arguments:{canvasId:j(e.canvas),recordingId:r.data},clientToken:null}))})},$r={jsonInput:`auto`,prompts:!1,logger:`ndjson`,errorMapping:`stable-exit-codes`},ei=e=>{let t=e.state;return{logger:e.output.logger,prompts:$r.prompts,process:mr(),formatError:e=>{let n=h(e,t.pendingParserMessage);return t.exitCode=v(n,!1,e),t.pendingParserMessage=null,JSON.stringify(n)}}},ti=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,ni=e=>{let t=ti(e),n=t===null?void 0:t.description;return typeof n==`string`&&n!==``?n:null},ri=e=>{let t=Ee({router:e});return{descriptions:new Map(t.flatMap(([e,t])=>{let n=ni(t.meta);return n===null?[]:[[e,n]]})),mutationPaths:new Set(t.flatMap(([e,t])=>t.type===`mutation`?[e]:[]))}},ii=()=>{let e=null;return()=>(e??=ie(),e)},ai=(e,t,n)=>{let r=Xe(t.remote),i=ve({remote:t.remote,mutationKey:t.mutationKey,configDirectory:t.configDirectory,now:()=>new Date,progress:t.output.result});et(e,ge(t.credentials,t.remote,pe(t.remote)),t.output),Nr(e,i,n,t.output),Pr(e,{version:t.version,credentials:t.credentials,remote:t.remote,output:t.output}),Ur(e,{screen:r,recording:Je(t.remote),world:Ze(t.remote,r)},t.output),Mr(e,t.output,n),dr(e,{remote:t.remote,mutationKey:t.mutationKey,invocation:i,catalog:n,output:t.output,configDirectory:t.configDirectory,now:()=>new Date}),Yr(e,{invocation:i,catalog:n,output:t.output}),qr(e,i,n,t.output),Qr(e,{invocation:i,catalog:n,output:t.output})},oi=e=>{let t=fe(),n=ii(),{descriptions:r,mutationPaths:i}=ri(t),a=Te({router:Zr(t,e.remote),name:e.commandName,version:e.version,description:`Operate Enhance as the authenticated person.`,jsonInput:$r.jsonInput}),o=ei(e),s=a.buildProgram(o);if(!(s instanceof we))throw TypeError(`trpc-cli did not return a Commander program`);kr(s),ai(s,e,n),Tr(s,{descriptions:r,mutationPaths:i,mutationKey:e.mutationKey,output:e.output}),s.description(`Operate Enhance as the authenticated person.`);let c=e.state;return{program:s,run:async()=>{try{await a.run(o,s)}catch(t){if(!(t instanceof m))throw t;if(t.requestedCode!==0&&c.pendingParserMessage!==null){let n=h(t,c.pendingParserMessage);c.exitCode=v(n,!0),c.pendingParserMessage=null,e.output.failure(n)}throw t}}}},si=e=>S.exit(e),Z=36e5,Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ci=e=>{if(Array.isArray(e))return e.map(e=>JSON.stringify(e));if(!Q(e)||!Array.isArray(e.items))return[JSON.stringify(e)];let t=e.items;if(t.length===0)return[JSON.stringify(e)];let n=e.truncated===!0;return t.map(e=>JSON.stringify(Q(e)?{...e,truncated:n}:{value:e,truncated:n}))},li=e=>{let t=`${e.join(`
|
|
13
|
+
`)}\n`;if(!(t.length>25e3||e.some(e=>e.length>2e3))){S.stdout.write(t);return}let n=Le(`sha256`).update(t).digest(`hex`).slice(0,16),r=T.join(Oe(),`enhance-${n}.ndjson`);w(r,t,{mode:384}),S.stdout.write(`${JSON.stringify({path:r,characters:t.length,records:e.length})}\n`)},ui=e=>{try{let t=new URL(e),n=new Set;for(let e of t.searchParams.keys())n.add(e.toLowerCase());return n.has(`x-amz-signature`)||n.has(`x-amz-credential`)||n.has(`x-amz-algorithm`)}catch{return!1}},$=e=>typeof e==`string`?ui(e):Array.isArray(e)?e.some(e=>$(e)):Q(e)?Object.values(e).some(e=>$(e)):!1,di=e=>{Ne(e,{recursive:!0,mode:448}),Ae(e,448)},fi=e=>{if(!je(e))return;let t=Date.now()-Z,n=Fe(e,{withFileTypes:!0});for(let r of n){if(!r.isFile()||!r.name.startsWith(`result-`))continue;let n=T.join(e,r.name);Me(n).mtimeMs<t&&Ie(n)}},pi=e=>({...e,sensitive:!0,cleanup:`unlink-after-use`,deleteAfter:new Date(Date.now()+Z).toISOString()}),mi=(e,t)=>{let n=ci(e),r=`${n.join(`
|
|
14
|
+
`)}\n`;di(t);let i=T.join(t,`result-${E()}.ndjson`);w(i,r,{mode:384,flag:`wx`}),S.stdout.write(`${JSON.stringify(pi({path:i,characters:r.length,records:n.length,reason:`signed-url`}))}\n`)},hi=e=>Q(e)?typeof e.token==`string`?{field:`token`,value:e.token}:typeof e.acceptToken==`string`?{field:`acceptToken`,value:e.acceptToken}:null:null,gi=(e,t,n)=>{let r=`${t.value}\n`;di(n);let i=T.join(n,`result-${E()}.token`);w(i,r,{mode:384,flag:`wx`});let a=Object.fromEntries(Object.entries(e).filter(([e])=>e!==t.field));S.stdout.write(`${JSON.stringify({...a,secret:pi({path:i,field:t.field,characters:r.length})})}\n`)},_i=e=>e.includes(`Usage:`)||e.includes(`Options:`)||e.includes(`Commands:`),vi=l.omit({fields:!0}).extend({remediation:x.string(),fields:x.array(x.object({path:x.string(),message:x.string()})).optional()}),yi=e=>{try{let t=JSON.parse(e),n=vi.safeParse(t);return n.success?{code:n.data.code,message:n.data.message,remediation:n.data.remediation,...n.data.fields!==void 0&&{fields:n.data.fields}}:null}catch{return null}},bi=(e,t)=>{if(typeof e==`string`&&_i(e)){S.stdout.write(e);return}let n=hi(e);if(n!==null&&Q(e)){gi(e,n,t);return}if($(e)){mi(e,t);return}li(ci(e))},xi=e=>{S.stderr.write(`${JSON.stringify(e)}\n`)},Si=(e,t,n=`enhance`)=>{let r=e,i=T.join(t,`sensitive`);return fi(i),{result:e=>{bi(g(e,n),i)},failure:e=>{xi(ue(e,n))},logger:{info:(...e)=>{bi(g(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(g(e.map(String).join(``),n)),i=yi(t);i===null?r.pendingParserMessage=t:xi(i)}}}};(async()=>{let e={exitCode:1,pendingParserMessage:null},t=Si(e,y.configDirectory,y.commandName),n=ye(y.configDirectory),r=xe(),i=oi({version:`0.1.7-dev.sha-e8d495edd470`,credentials:n,remote:_e(y.apiUrl,n,r),mutationKey:r,output:t,state:e,configDirectory:y.configDirectory,commandName:y.commandName});try{await i.run()}catch(n){n instanceof m&&si(n.requestedCode===0?0:e.exitCode),t.failure(h(n,null)),si(1)}})();export{};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{f as e,l as t}from"./cli-output-identity.lib-COXLA7bt.mjs";import{a as n,f as r,i,n as a,o,r as s,t as c}from"./mutation-key.adapter-BhdfFChs.mjs";import{t as l}from"./mcp-server.adapter-CH7nbGxy.mjs";import{z as u}from"zod";import d from"node:process";import{serveStdio as f}from"@modelcontextprotocol/server/stdio";const p=new Set([`auth.login`,`auth.logout`,`auth.status`,`doctor`]),m=u.object({openBrowser:u.boolean()}),h=async e=>{let t=r(e.credentials,e.remote,n(e.remote));switch(e.capability){case`auth.login`:{let n=m.parse(e.arguments);return t.loginWithBrowser({label:`Agent plugin`,openBrowser:n.openBrowser,onReady:()=>null})}case`auth.logout`:return t.logout();case`auth.status`:return await e.credentials.read()===null?{authenticated:!1}:t.status();case`doctor`:{let[t,n]=await Promise.all([e.remote.health(),e.credentials.read()]);return{status:n!==null&&t.reachable?`ok`:`degraded`,runtimeVersion:e.version,api:{reachable:t.reachable,status:t.status},credential:{present:n!==null}}}default:throw TypeError(`${e.capability} has no MCP transport execution`)}},g=(e,t,n,r)=>{let i=a(e,t,c());return{invoke:async s=>{if(p.has(s.capability.id))return h({capability:s.capability.id,arguments:s.arguments,credentials:t,remote:i,version:r});let l=c();return o({remote:a(e,t,l),mutationKey:l,configDirectory:n}).invoke(s)}}},_=u.object({authenticated:u.literal(!1)}),v=u.object({authenticated:u.literal(!0),personId:u.uuid(),displayName:u.string().min(1),tokenId:u.uuid(),tokenLabel:u.string().min(1),expiresAt:u.iso.datetime().nullable()}),y=u.object({openBrowser:u.boolean().default(!0).describe(`Open the system browser for the human sign-in and wait for completion.`)}),b=u.strictObject({}),x=u.union([_,v]),S=u.object({loggedOut:u.boolean()}),C=u.object({status:u.enum([`ok`,`degraded`]),runtimeVersion:u.string().min(1),api:u.object({reachable:u.boolean(),status:u.number().int().nullable()}),credential:u.object({present:u.boolean()})}),w=e=>({summary:e.summary,useWhen:e.useWhen,preconditions:[`Run through the local Enhance MCP runtime, which owns the user-scoped credential.`,`Keep credential values outside model-visible input and output.`],input:[],output:[],result:e.result,recovery:[`BAD_REQUEST: correct the named option and call again.`,`UNAUTHORIZED: start browser sign-in and let the person complete consent.`,`FORBIDDEN: leave the credential unchanged and report the governing account policy.`,`INTERNAL: call doctor, report the failing boundary, and stop repeating the call.`],next:e.next,examples:[{input:e.exampleInput,output:e.exampleOutput}]}),T=t=>e({...t,source:`composite`,idempotency:t.operation===`query`?`none`:`single`,execution:{kind:`composite`,procedures:[]},meta:{description:t.guide.summary},policy:{exposure:`mcp-transport`,reason:`The local MCP runtime owns its own authentication and installation diagnostics.`,owner:`mcp`},cliPath:null,inputExample:t.guide.examples[0]?.input,outputExample:t.guide.examples[0]?.output}),E=[T({id:`auth.login`,operation:`mutation`,effect:`external`,inputSchema:y,outputSchema:v,guide:w({summary:`Open browser sign-in and store a revocable user-scoped Enhance credential.`,useWhen:`Use when Enhance is not authenticated or its credential was revoked.`,result:`Waits for browser consent, stores the credential locally, and returns safe identity metadata.`,next:[`Call auth.status, then read the target canvas.`],exampleInput:{openBrowser:!0},exampleOutput:{authenticated:!0,personId:`00000000-0000-4000-8000-000000000001`,displayName:`Ada`,tokenId:`00000000-0000-4000-8000-000000000002`,tokenLabel:`Agent plugin`,expiresAt:null}})}),T({id:`auth.logout`,operation:`mutation`,effect:`delete`,inputSchema:b,outputSchema:S,guide:w({summary:`Remove the user-scoped local Enhance credential.`,useWhen:`Use only when the person asks to disconnect this local agent host.`,result:`Reports whether a local credential was removed without returning its value.`,next:[`Call auth.status to confirm the local runtime is disconnected.`],exampleInput:{},exampleOutput:{loggedOut:!0}})}),T({id:`auth.status`,operation:`query`,effect:`read`,inputSchema:b,outputSchema:x,guide:w({summary:`Check whether the local Enhance MCP runtime is authenticated.`,useWhen:`Use before a workflow or after login, logout, expiry, or an authorization failure.`,result:`Returns safe identity metadata or authenticated false, never a credential value.`,next:[`When unauthenticated, call auth.login; otherwise continue with the requested workflow.`],exampleInput:{},exampleOutput:{authenticated:!1}})}),T({id:`doctor`,operation:`query`,effect:`read`,inputSchema:b,outputSchema:C,guide:w({summary:`Check MCP runtime identity, API reachability, and credential presence without changes.`,useWhen:`Use after repeated connection, authentication, or compatibility failure.`,result:`Returns bounded diagnostics without machine paths, credentials, or customer data.`,next:[`Follow the failing boundary; do not repeat a mutation while diagnostics are degraded.`],exampleInput:{},exampleOutput:{status:`ok`,runtimeVersion:`0.1.7`,api:{reachable:!0,status:200},credential:{present:!0}}})})].toSorted((e,t)=>e.id.localeCompare(t.id)),D=()=>E,O=s(i.configDirectory),k=g(i.apiUrl,O,i.configDirectory,`0.1.7-dev.sha-e8d495edd470`),A=[...t(),...D()];f(()=>l({version:`0.1.7-dev.sha-e8d495edd470`,name:i.mcpServiceName,commandName:i.commandName,invocation:k,catalog:A,exposures:[`shared`,`mcp-transport`]}),{legacy:`serve`,onerror:()=>d.stderr.write(`${i.mcpServiceName} transport failure\n`)});export{};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{C as e,a as t,i as n,l as r,n as i,s as a,t as o}from"./cli-output-identity.lib-COXLA7bt.mjs";import{z as s}from"zod";import{createHash as c,randomUUID as l}from"node:crypto";import{readFile as u,rm as d}from"node:fs/promises";import{McpServer as f}from"@modelcontextprotocol/server";const p=e=>e.replaceAll(/\s+/gu,` `).trim(),m=e=>{let t=`${e.id} [${e.effect}] — `,n=p(e.guide.summary),r=180-t.length;return`${t}${n.slice(0,r)}`},h=(e,t)=>{let n=e.toSorted((e,t)=>e.id.localeCompare(t.id)).map(e=>m(e)),r=c(`sha256`).update(n.join(`
|
|
3
|
+
`)).digest(`hex`),i=[`Enhance MCP ${t} — ${String(n.length)} capabilities — sha256:${r}`,...n].join(`
|
|
4
|
+
`);if(Buffer.byteLength(i)>24576)throw RangeError(`the complete capability catalogue exceeds 24 KiB`);return{digest:r,text:i}},g=(e,t,n=`enhance`)=>{let r=h(e,t),a=String(i(r.text,n));return{register:t=>{t.registerTool(`capability.catalogue`,{title:`Scan every Enhance capability`,description:`Return the complete bounded capability inventory when the task is broad, uncertain, or capability.search does not find the right words. Call capability.describe with one exact id before invoking it.`,inputSchema:s.strictObject({}),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":e.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":e.length}},()=>({content:[{type:`text`,text:a}]}))}}},_=s.object({ok:s.literal(!1),error:s.object({code:s.string(),message:s.string(),remediation:s.string(),fields:s.array(s.object({path:s.string(),message:s.string()})).optional()})}),v=s.object({ok:s.literal(!0),artifact:s.object({uri:s.string(),mimeType:s.string(),bytes:s.number().int().nonnegative()})}),y=s.object({id:s.string(),operation:s.enum([`query`,`mutation`]),effect:s.enum([`read`,`write`,`delete`,`external`]),idempotency:s.enum([`none`,`single`,`composite`]),summary:s.string(),useWhen:s.string(),preconditions:s.array(s.string()),inputSchema:s.unknown(),exampleInput:s.unknown(),output:s.array(s.object({name:s.string(),required:s.boolean(),meaning:s.string()})),result:s.string(),recovery:s.array(s.string()),next:s.array(s.string()),schemaDigest:s.string(),guidanceDigest:s.string(),behaviorDigest:s.string()}),b=y.pick({id:!0,operation:!0,effect:!0,summary:!0,useWhen:!0}),x=s.union([s.object({ok:s.literal(!0),result:s.unknown()}),v,_]),S=s.union([s.object({ok:s.literal(!0),result:s.object({matches:s.array(b),totalMatches:s.number().int().nonnegative(),truncated:s.boolean()})}),_]),C=s.union([s.object({ok:s.literal(!0),result:y}),_]),w=s.object({capability:s.string().min(1).describe(`Exact capability id returned by capability.search or capability.catalogue.`)}),T=(t,n)=>({register:r=>{r.registerTool(`capability.describe`,{title:`Load one Enhance capability contract`,description:`Load the exact input schema, example, preconditions, result guidance, recovery, and next steps for one id returned by capability.search or capability.catalogue.`,inputSchema:w,outputSchema:C,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},({capability:r})=>{let i=t.describe(r);return i===null?n.failure(new e(`BAD_REQUEST`,`Unknown shared capability: ${r}.`,`Call capability.search or capability.catalogue and use an exact id from its results.`,{capability:`No shared capability has this id.`})):n.inline(i)})}}),E=/(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu,D=/[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu,O=e=>JSON.stringify(e),k=(e,t=``)=>typeof e==`string`?D.test(e)||E.test(t)&&!t.endsWith(`Id`):Array.isArray(e)?e.some(e=>k(e,t)):typeof e!=`object`||!e?!1:Reflect.get(e,`sensitive`)===!0||Object.entries(e).some(([e,t])=>k(t,e)),A=async(e,t,n)=>{if(typeof t!=`object`||!t)return null;let r=Reflect.get(t,`path`);if(typeof r!=`string`)return null;let i=Reflect.get(t,`contentType`);if(typeof i!=`string`||!i.startsWith(`image/`)||Reflect.get(t,`sensitive`)!==!0)return null;let a=await u(r),o=l(),s=`enhance://artifact/${o}`;if(n===`embedded`){await d(r,{force:!0});let e={ok:!0,artifact:{uri:s,mimeType:i,bytes:a.byteLength}};return{content:[{type:`text`,text:O(e)},{type:`image`,data:a.toString(`base64`),mimeType:i}],structuredContent:e}}e.registerResource(`artifact-${o}`,s,{title:`Enhance artifact`,mimeType:i},e=>({contents:[{uri:e.href,mimeType:i,blob:a.toString(`base64`)}]}));let c={ok:!0,artifact:{uri:s,mimeType:i,bytes:a.byteLength}};return{content:[{type:`text`,text:O(c)},{type:`resource_link`,name:`Enhance artifact`,uri:s,mimeType:i}],structuredContent:c}},j=(e,t,n)=>{let r=l(),i=`enhance://result/${r}`,a=Buffer.byteLength(t);if(n===`embedded`){let e={ok:!0,artifact:{uri:i,mimeType:`application/json`,bytes:a}};return{content:[{type:`text`,text:O(e)},{type:`resource`,resource:{uri:i,mimeType:`application/json`,text:t}}],structuredContent:e}}e.registerResource(`result-${r}`,i,{title:`Protected Enhance result`,mimeType:`application/json`},e=>({contents:[{uri:e.href,mimeType:`application/json`,text:t}]}));let o={ok:!0,artifact:{uri:i,mimeType:`application/json`,bytes:a}};return{content:[{type:`text`,text:O(o)},{type:`resource_link`,name:`Protected Enhance result`,uri:i,mimeType:`application/json`}],structuredContent:o}},M=t=>new e(`BAD_REQUEST`,`Input validation error.`,`Call capability.search again and rewrite every rejected input field.`,Object.fromEntries(t.issues.map(e=>[e.path.length===0?`input`:e.path.join(`.`),e.message]))),N=(e=`enhance`)=>({success:async(t,n,r)=>{let a=i(n,e),o=await A(t,a,r);if(o!==null)return o;let s=O(a);if(Buffer.byteLength(s)>2e4||k(a))return j(t,s,r);let c={ok:!0,result:a};return{content:[{type:`text`,text:O(c)}],structuredContent:c}},inline:t=>{let n={ok:!0,result:i(t,e)};return{content:[{type:`text`,text:O(n)}],structuredContent:n}},failure:t=>{let r={ok:!1,error:o(n(t instanceof s.ZodError?M(t):t,null),e)};return{content:[{type:`text`,text:O(r)}],structuredContent:r,isError:!0}}}),P=s.object({query:s.string().trim().min(1).max(200).describe(`Plain-language task, domain, or exact capability id to discover.`),operation:s.enum([`any`,`query`,`mutation`]).default(`any`).describe(`Limit matches to reads or mutations when the intended effect is known.`),limit:s.number().int().min(1).max(10).default(5).describe(`Maximum contracts to return.`)}),F=s.object({capability:s.string().min(1).describe(`Exact query id returned by capability.describe.`),input:s.record(s.string(),s.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`)}),I=s.object({capability:s.string().min(1).describe(`Exact mutation id returned by capability.describe.`),input:s.record(s.string(),s.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`),clientToken:s.uuid().optional().describe(`Stable UUID reused only when retrying this exact mutation input.`)}),L=(t,n,r)=>{let i=t.find(e=>e.id===n);if(i===void 0)throw new e(`BAD_REQUEST`,`Unknown shared capability: ${n}.`,`Call capability.search or capability.catalogue and use an exact id from its results.`,{capability:`No shared capability has this id.`});if(i.operation!==r){let t=i.operation===`query`?`capability.query`:`capability.mutate`;throw new e(`BAD_REQUEST`,`${n} is a ${i.operation}, not a ${r}.`,`Call ${t} with the same capability and input.`,{capability:`Use ${t} for this capability.`})}return i},R=(e,t,n,r)=>{e.registerTool(`capability.search`,{title:`Discover Enhance capabilities`,description:`Search the Enhance capability catalogue for a specific likely action. Returns only the most relevant summaries; use capability.catalogue when the request is broad or the matches look wrong, then call capability.describe before invoking.`,inputSchema:P,outputSchema:S,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":t.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":t.length}},async({query:e,operation:t,limit:i})=>r.inline(n.search({query:e,operation:t,limit:i})))},z=(e,t,n,r)=>{e.registerTool(`capability.query`,{title:`Run a discovered Enhance query`,description:`Run one read-only capability using the exact id and input loaded by capability.describe. Search and describe first whenever the contract is not already present in the conversation.`,inputSchema:F,outputSchema:x,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a})=>{try{return await r.results.success(e,await n.invoke({capability:L(t,i,`query`),arguments:a,clientToken:null}),r.delivery)}catch(e){return r.results.failure(e)}})},B=(e,t,n,r)=>{e.registerTool(`capability.mutate`,{title:`Run a discovered Enhance mutation`,description:`Run one state-changing capability using the exact id and input loaded by capability.describe. Search and describe first, respect its preconditions, and reuse clientToken only when retrying the identical mutation.`,inputSchema:I,outputSchema:x,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a,clientToken:o})=>{try{return await r.results.success(e,await n.invoke({capability:L(t,i,`mutation`),arguments:a,clientToken:o??null}),r.delivery)}catch(e){return r.results.failure(e)}})},V=e=>{let n=new f({name:e.name??`enhance-mcp`,version:e.version},{capabilities:{tools:{listChanged:!1},resources:{listChanged:!0}}}),i=t(e.catalog??r(),e.exposures??[`shared`]),o=a(i),s=e.delivery??`linked`,c=N(e.commandName);g(i,e.version,e.commandName).register(n),R(n,i,o,c),T(o,c).register(n);let l={delivery:s,results:c};return z(n,i,e.invocation,l),B(n,i,e.invocation,l),n};export{V as t};
|
package/dist/mcp.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{l as e,o as t}from"./cli-output-identity.lib-COXLA7bt.mjs";import{t as n}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{t as r}from"./mcp-server.adapter-CH7nbGxy.mjs";export{e as createCapabilityCatalogAdapter,r as createEnhanceMcpServer,n as toCapabilityInventory,t as toSharedCapabilities};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{$ as e,B as t,C as n,F as r,H as i,I as a,L as o,M as s,N as c,P as l,Q as u,R as ee,S as te,V as ne,W as re,X as ie,_ as ae,at as d,b as oe,g as se,h as ce,it as le,j as ue,nt as de,ot as fe,q as pe,rt as me,v as he,w as ge,x as _e,y as ve,z as ye}from"./cli-output-identity.lib-COXLA7bt.mjs";import{z as f}from"zod";import{homedir as be,tmpdir as xe}from"node:os";import p from"node:process";import{chmodSync as m,createReadStream as h,createWriteStream as Se,mkdirSync as Ce,writeFileSync as we}from"node:fs";import g from"node:path";import{createHash as _,randomBytes as v,randomUUID as y}from"node:crypto";import{setTimeout as Te}from"node:timers/promises";import{chmod as b,mkdir as Ee,mkdtemp as De,readFile as Oe,realpath as ke,rename as Ae,rm as x,stat as S,unlink as C,writeFile as je}from"node:fs/promises";import{Readable as Me,Transform as w}from"node:stream";import{pipeline as Ne}from"node:stream/promises";import{ZipFile as Pe}from"yazl";import{createTRPCUntypedClient as Fe,httpLink as Ie}from"@trpc/client";import{spawn as Le}from"node:child_process";import{createServer as Re}from"node:http";const ze=/^enh_[\w-]{43}$/,T=e=>{let r=t.parse(e);if(r.authentication.kind!==`agent`||r.person===null)throw new n(`UNAUTHORIZED`,`The credential is missing, expired, revoked, or invalid.`,`Run 'enhance auth login' and complete authentication in the browser.`);return{authenticated:!0,personId:r.person.id,displayName:r.person.displayName,tokenId:r.authentication.tokenId,tokenLabel:r.authentication.tokenLabel,expiresAt:r.authentication.expiresAt}},Be=(e,t,r)=>({loginWithToken:async r=>{if(!ze.test(r))throw new n(`BAD_REQUEST`,`Agent tokens begin with enh_ and contain 32 base64url bytes.`,`Pass a manual token from Settings to 'enhance auth login' through stdin.`);let i=T(await t.queryWithToken(`person.me`,{},r));return await e.write(r),i},loginWithBrowser:async a=>{let o=ne.parse(await t.authenticationConfig());if(o.method===`token`)throw new n(`BAD_REQUEST`,`Browser authentication is not configured for this Enhance environment.`,`Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.`);let s=await r.authorize({issuer:o.issuer,clientId:o.clientId,scope:o.scope,openBrowser:a.openBrowser,onReady:a.onReady}),c=i.parse(await t.mutateWithToken(`person.createAgentToken`,{label:a.label,expiresAt:null},s)),l=T(await t.queryWithToken(`person.me`,{},c.token));return await e.write(c.token),l},status:async()=>{if(await e.read()===null)throw new n(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return T(await t.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),Ve=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),He=e=>{if(e.byteLength<24||Ve.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)}},Ue=async(e,t)=>{let r=le.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!r.success)throw new n(`INTERNAL`,`The API returned an invalid render download response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");let i=await e.download(r.data.download.url),a=He(i);if(a===null||i.byteLength!==t.result.bytes||a.width!==t.result.width||a.height!==t.result.height)throw new n(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return i},E=[`canvas.render.create`,`canvas.render.get`],D=e=>new n(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),We=e=>{let t=e.failure;if(t===null)return D(`render job`);let r=t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,i=t.reason===`VERSION_CHANGED`?`Run 'enhance canvas inspect --canvas ${e.canvasId}', then render its returned version.`:t.reason===`TARGET_NOT_FOUND`?`Run 'enhance canvas tree --canvas ${e.canvasId}' and choose a current node id.`:t.retryable?"Retry the render. If it repeats, run `enhance doctor` and report the job id.":`Change the target or scale using the failure details, then retry.`;return new n(r,t.message,i,{jobId:e.id,reason:t.reason,phase:t.phase})},Ge=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Ke=async(e,t)=>{let n=d.safeParse(await e.query(E[1],{jobId:t}));if(!n.success)throw D(`render status`);return n.data.job},qe=async(e,t)=>{let r=Date.now(),i=0,a=``,o=t.initial;for(;o.state===`queued`||o.state===`running`;){let s=Date.now(),c=`${o.state}:${o.phase}`;if((c!==a||s-i>=5e3)&&(t.progress({event:`render.progress`,jobId:o.id,state:o.state,phase:o.phase,elapsedMs:s-r,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),i=s,a=c),s>=t.deadline)throw new n(`INTERNAL`,`Render ${o.id} did not finish before the local timeout.`,`Retry the exact command with --client-token ${t.retryClientToken} and a larger --timeout-ms. If the render remains unavailable, run \`enhance doctor\` and report the job id.`,{jobId:o.id,phase:o.phase});await Ge(250),o=await Ke(e,o.id)}if(o.state!==`succeeded`)throw We(o);return o},Je=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]},Ye=(e,t)=>({jobId:e.id,canvasId:e.canvasId,requestedVersion:e.requestedVersion,loadedVersion:e.result.loadedVersion,target:e.target,sourceState:e.result.sourceState??null,bounds:e.result.bounds,width:e.result.width,height:e.result.height,scale:e.result.scale,contentType:e.result.contentType,bytes:e.result.bytes,warnings:e.result.warnings,path:t.path,sensitive:!0,cleanup:t.temporary?`unlink-after-use`:`caller-owned`,...t.deleteAfter!==null&&{deleteAfter:t.deleteAfter.toISOString()},next:Je(e)}),Xe=async(e,t)=>{let n=de.safeParse(await e.remote.mutate(E[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,format:`png`}));if(!n.success)throw D(`render creation`);let r=await qe(e.remote,{initial:n.data.job,deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress}),i=await Ue(e.remote,r),a=e.files.write({body:i,outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()});return Ye(r,a)},O=(e,t,n,r=()=>null)=>({execute:async i=>Xe({remote:e,files:t,now:n,progress:r},i)}),k={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},A=async e=>{try{return await e(),!0}catch{return!1}},Ze=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await A(async()=>e.mutate(k.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 A(async()=>e.mutate(k.end,{canvasId:i.canvasId,activityId:n})))}}},j=e=>({begin:async t=>{try{let n=re.safeParse(await e.mutate(k.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?Ze(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>A(async()=>e.mutate(k.end,{canvasId:t,activityId:n}))}),Qe=new Set([`insertPrototype`,`insertText`,`setBox`]),$e=e=>Qe.has(e.op),et=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,tt=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],nt=e=>[...new Set(e.operations.flatMap(e=>tt(e)))].slice(0,100),rt=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:$e(e)?e.box:null,it=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}},M=async(e,t)=>{let r=await e.mutate(`canvas.applyOperations`,t),i=pe.safeParse(r);if(!i.success)throw new n(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return i.data},N=e=>({execute:async(t,n)=>{if(n?.activity===!1)return M(e,t);let r=await j(e).begin({canvasId:t.canvasId,phase:et(t),nodeIds:nt(t),bounds:it(t.operations.flatMap(e=>{let t=rt(e);return t===null?[]:[t]}))});try{return await M(e,t)}finally{await r?.finish()}}}),P=e=>new n(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),at=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),ot=e=>{let t=e.failure;return new n(t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`CONVERSION_FAILED`?`BAD_REQUEST`:`INTERNAL`,t.message,t.retryable?"Retry the exact write. If it repeats, run `enhance doctor` and report the job id.":`Inspect the current canvas tree and correct the HTML or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},st=async(t,n)=>{let r=e.safeParse(await t.query(`canvas.render.getImport`,{jobId:n}));if(!r.success)throw P(`HTML import status`);return r.data.job},ct=async(e,t,r)=>{let i=Date.now()+r,a=t;for(;a.state===`queued`||a.state===`running`;){if(Date.now()>=i)throw new n(`INTERNAL`,`HTML import ${a.id} did not finish before the local timeout.`,"Retry the exact command with a larger --timeout-ms. If the queue remains stuck, run `enhance doctor`.",{jobId:a.id,phase:a.phase});await at(250),a=await st(e,a.id)}if(a.state!==`succeeded`)throw ot(a);return a},lt=async(e,t)=>{let n=u.safeParse(await e.mutate(`canvas.render.importSource`,{canvasId:t.canvasId,expectedVersion:t.baseVersion,source:{kind:`html`,html:t.html,label:`Agent-authored HTML`,...t.idPrefix!==void 0&&{idPrefix:t.idPrefix}},destination:{kind:t.mode,targetNodeId:t.targetNodeId}}));if(!n.success)throw P(`HTML import creation`);return ct(e,n.data.job,t.renderTimeoutMs)},ut=(e,t,r)=>({state:`failed`,mutationCommitted:!0,requestedVersion:r,...e instanceof n?{code:e.code,message:e.message,remediation:e.remediation,...e.fields!==void 0&&{fields:e.fields}}:{code:`INTERNAL`,message:`The post-write review render failed.`,remediation:`Read the current canvas version, then render the affected area again.`},next:[`enhance canvas inspect --canvas ${t.canvasId}`,`enhance canvas render --canvas ${t.canvasId} --expected-version ${String(r)}`,`Do not replay the committed write with a new mutation id.`]}),dt=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 ut(e,t,n.result.version)}},ft=async(e,t)=>{let n=ie.safeParse(await e.query(`canvas.document.get`,{canvasId:t.canvasId}));if(!n.success)throw P(`canvas document`);let r=fe.safeParse(n.data.document);if(!r.success)throw P(`editable canvas document`);return t.result.insertedNodeIds.map(e=>{let t=r.data.nodes[e];return{id:e,name:t?.label??``,component:t?.component??``}})},pt=async(e,t,n,r)=>({canvasId:t.canvasId,mutationCommitted:!0,mode:t.mode,targetNodeId:t.targetNodeId,previousVersion:n.result.previousVersion,version:n.result.version,createdNodes:await ft(e,n),removedNodeIds:n.result.removedNodeIds,affectedBounds:n.result.affectedBounds,review:r,next:[`enhance canvas tree --canvas ${t.canvasId}`,`Inspect the review PNG before continuing.`]}),F=(e,t)=>({execute:async n=>{let r=await j(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await lt(e,n);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await dt(t,n,i);return await pt(e,n,i,a)}finally{await r?.finish()}}}),I=(e,t,r)=>{try{we(e,t,{flag:r?`w`:`wx`,mode:384}),m(e,384)}catch(t){let r=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new n(r,r===`CONFLICT`?`Refusing to replace ${e}.`:`Could not write ${e}.`,r===`CONFLICT`?`Choose another --output path or pass --force deliberately.`:`Create the parent directory and verify it is writable, then retry.`)}},L=e=>({write:t=>{if(t.outputPath!==null){let e=g.resolve(t.outputPath);return I(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=g.join(e,`sensitive`);Ce(n,{recursive:!0,mode:448}),m(n,448);let r=g.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return I(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),R=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`,`prototype.attach`],z=e=>new n(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),mt=async(e,t)=>{let r=Date.now()+3e5,i=50;for(;Date.now()<r;){let r=a.safeParse(await e.query(R[3],t));if(!r.success)throw z(`status`);if(r.data.state===`ready`||r.data.state===`failed`)return r.data;if(r.data.state===`abandoned`)throw new n(`NOT_FOUND`,`Prototype deployment ${t.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);await Te(i),i=Math.min(i*2,1e3)}throw Error(`prototype ingestion is still running`)},ht=async(e,t,n,r)=>{let i=c.safeParse(await e.mutate(R[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 z(`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`)&&!ye.safeParse(await e.mutate(R[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId})).success)throw z(`artifact submission`);return i.data},gt=e=>{if(e.state!==`failed`)return;let{failure:t}=e;throw new n(`BAD_REQUEST`,t.message,`Fix the build and publish it with a new client token.`,t.path===void 0?void 0:{path:t.path})},_t=async(e,t,i)=>{let a=r.safeParse(await e.query(R[0],{}));if(!a.success)throw z(`capabilities`);let o=await t.package({directory:i.directory,entryPath:i.entryPath,limits:a.data.limits}),c={deploymentId:null};try{let t=await ht(e,i,o,e=>{c.deploymentId=e}),n=await mt(e,{canvasId:i.canvasId,deploymentId:t.deploymentId});gt(n);let r=s.safeParse(await e.mutate(R[4],{canvasId:i.canvasId,deploymentId:t.deploymentId,baseVersion:i.baseVersion}));if(!r.success)throw z(`attachment`);return{...r.data,fileCount:n.fileCount,totalBytes:n.totalBytes,alreadyExists:t.alreadyExists,next:[r.data.openUrl,`enhance canvas render --canvas ${i.canvasId} --node-id ${r.data.nodeId} --expected-version ${String(r.data.version)}`]}}catch(e){throw e instanceof n&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||c.deploymentId===null?e:new te(`Prototype deployment ${c.deploymentId} was created, but publishing did not complete.`,`Retry 'enhance prototype publish' with the same --client-token ${i.clientToken}.`)}finally{await o.dispose()}},vt=(e,t)=>({execute:async n=>_t(e,t,n)}),yt=[`transcript.get`],bt=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),xt=e=>({execute:async t=>{let r=ge.safeParse(await e.query(yt[0],t));if(!r.success)throw new n(`INTERNAL`,`The API returned an invalid transcript response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data.state===`ready`?{...r.data,guidance:`Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.`,next:bt(t.canvasId,t.recordingId,r.data.cues.map(e=>e.startMs))}:r.data}}),B=[`canvas.render.get`,`canvas.render.snapshot`],St=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),Ct=e=>new n(e.failure?.reason===`VERSION_CHANGED`?`CONFLICT`:e.failure?.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:e.failure?.reason===`TARGET_INVALID`||e.failure?.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,e.failure?.message??`The snapshot job ended without a result.`,`Run 'enhance canvas tree --canvas ${e.canvasId}' and retry the exact snapshot if its recording node still exists.`,{jobId:e.id,phase:e.phase}),wt=async(e,t)=>{let r=d.safeParse(await e.query(B[0],{jobId:t}));if(!r.success)throw new n(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return r.data.job},Tt=async(e,t,r,i)=>{let a=Date.now()+r.timeoutMs,o=Date.now(),s=t,c=0,l=``;for(;s.state===`queued`||s.state===`running`;){let t=Date.now(),u=`${s.state}:${s.phase}`;if((u!==l||t-c>=5e3)&&(i({event:`snapshot.progress`,jobId:s.id,state:s.state,phase:s.phase,elapsedMs:t-o,timeoutMs:r.timeoutMs,retryClientToken:r.retryClientToken}),c=t,l=u),t>=a)throw new n(`INTERNAL`,`Snapshot ${s.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${r.retryClientToken} and a larger --timeout-ms.`,{jobId:s.id,phase:s.phase});await St(),s=await wt(e,s.id)}if(s.state!==`succeeded`||s.result.snapshot===void 0)throw Ct(s);return{...s,result:{...s.result,snapshot:s.result.snapshot}}},Et=async(e,t,r)=>{let i=me.safeParse(await e.mutate(B[1],{canvasId:r.canvasId,recordingId:r.recordingId,atMs:r.atMs}));if(!i.success)throw new n(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");let a=await Tt(e,i.data.job,r,t),o=a.result.snapshot;return{jobId:a.id,canvasId:a.canvasId,...o,warnings:a.result.warnings,retryClientToken:r.retryClientToken,next:[`enhance canvas node --canvas ${a.canvasId} --node-id ${o.screenNodeId}`,`enhance canvas render --canvas ${a.canvasId} --node-id ${o.screenNodeId} --expected-version ${String(o.version)}`]}},Dt=(e,t)=>({execute:async n=>Et(e,t,n)}),V=new Date(`1980-01-01T00:00:00.000Z`),H=33188,U=(e,t)=>new n(`BAD_REQUEST`,e,t),Ot=(e,t)=>{let n=_(`sha256`),r=0;return new w({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()}})},kt=e=>{let t=o.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),n=Buffer.from(JSON.stringify(t),`utf8`);if(n.byteLength>e.limits.manifestBytes)throw U(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,ue,{mtime:V,mode:H,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},At=async e=>{let t=new Pe,n=_(`sha256`),r=new w({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=Ne(t.outputStream,r,Se(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=kt({zip:t,completed:i,...e}))};for(let n of e.files)t.addReadStreamLazy(n.path,{size:n.bytes,mtime:V,mode:H,compress:!0,forceDosTimestamp:!0},e=>{e(null,h(n.absolutePath).pipe(Ot(n,s)))});if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let c=await S(e.artifactPath);if(c.size>e.limits.artifactBytes)throw U(`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`)}},jt={".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`},Mt=e=>jt[g.extname(e).toLowerCase()]??`application/octet-stream`,W=async e=>{try{return await S(e)}catch{return null}},Nt=e=>Buffer.byteLength(e,`utf8`),G=(e,t)=>new n(`BAD_REQUEST`,e,t),K=(e,t)=>{if(!ee.safeParse(e).success)throw G(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(Nt(e)>t.pathBytes)throw G(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},q=async(e,t,n,r)=>{let i=await ke(t);if(n.has(i))throw G(`Cannot package the circular directory link at ${t}.`,`Pass a directory tree that can be read once from top to bottom.`);let a=new Set(n).add(i),{readdir:o}=await import(`node:fs/promises`),s=await o(t,{withFileTypes:!0}),c=[],l=s.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of l){let i=g.join(t,n.name),o=await W(i);if(o?.isDirectory()===!0){c.push(...await q(e,i,a,r));continue}if(o?.isFile()!==!0)throw G(`Cannot read ${i} as a prototype file.`,`Pass a directory containing only regular files and directory links.`);let s=g.relative(e,i).split(g.sep).join(`/`).normalize(`NFC`);K(s,r),c.push({absolutePath:i,path:s,bytes:Number(o.size),contentType:Mt(i)})}return c},Pt=(e,t,n)=>{if(e.length===0)throw G(`The prototype build is empty.`,`Build the app before publishing it.`);if(e.length>n.fileCount)throw G(`The prototype has ${String(e.length)} files.`,`This environment currently accepts ${String(n.fileCount)} files per deployment.`);let r=new Set,i=0;for(let t of e){let e=l(t.path);if(r.has(e))throw G(`The prototype path ${t.path} collides by case or Unicode normalization.`,`Rename one of the colliding files so the build is portable.`);if(r.add(e),t.bytes>n.fileBytes)throw G(`The prototype file ${t.path} is too large.`,`This environment accepts ${String(n.fileBytes)} bytes in one runtime file.`);if(i+=t.bytes,i>n.expandedBytes)throw G(`The prototype build is too large.`,`This environment accepts ${String(n.expandedBytes)} expanded bytes.`)}let a=e.find(e=>e.path===t);if(a===void 0)throw G(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw G(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},Ft=async e=>{let t=g.resolve(e.directory),r=await W(t);if(r===null)throw new n(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!r.isDirectory())throw G(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let i=e.entryPath.split(g.sep).join(`/`).normalize(`NFC`);K(i,e.limits);let a=await q(t,t,new Set,e.limits);Pt(a,i,e.limits);let o=await De(g.join(xe(),`enhance-prototype-artifact-`)),s=g.join(o,`artifact.zip`);try{let t=await At({artifactPath:s,files:a,entryPath:i,limits:e.limits});return{identity:{protocolVersion:1,format:`zip`,bytes:t.bytes,sha256:t.sha256,fileCount:t.manifest.files.length,expandedBytes:t.manifest.files.reduce((e,t)=>e+t.bytes,0)},manifest:t.manifest,open:()=>h(s),dispose:async()=>x(o,{recursive:!0})}}catch(e){throw await x(o,{recursive:!0}),e}},It=()=>({package:Ft}),J=e=>O(e.remote,L(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Lt=async(e,t)=>{let n=ce.parse(t);return N(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Rt=async(e,t,n)=>{let r=se.parse(t);return J(e).execute({...r,retryClientToken:n})},zt=async(e,t)=>{let n=ae.parse(t);return F(e.remote,J(e)).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},Bt=async(e,t)=>{let n=he.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},Vt=async(e,t,n)=>{let r=ve.parse(t);return vt(e.remote,It()).execute({...r,clientToken:n})},Ht=async(e,t,n)=>{let r=oe.parse(t);return Dt(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},Ut=async(e,t)=>{let n=_e.parse(t);return xt(e.remote).execute(n)},Wt=async(e,t,n,r)=>{switch(t){case`canvas.apply`:return Lt(e,n);case`canvas.render`:return Rt(e,n,r);case`canvas.writeHtml`:return zt(e,n);case`comment.attention`:return Bt(e,n);case`prototype.publish`:return Vt(e,n,r);case`recording.snapshot`:return Ht(e,n,r);case`transcript.read`:return Ut(e,n);default:throw TypeError(`${t} has no composite execution`)}},Gt=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??y();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Wt(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),Y=`/callback`,Kt=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),qt=e=>{let t=p.platform===`darwin`?{executable:`open`,arguments:[e]}:p.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=Le(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},Jt=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==Y){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)},Yt=e=>{let t=Kt(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},Xt=async e=>{let t=Promise.withResolvers(),n=Re((n,r)=>{Jt({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)}${Y}`,a=Yt({...e,redirectUri:i});e.onReady(a),e.openBrowser&&qt(a);let o=setTimeout(()=>{t.reject(Error(`browser authorization timed out`))},12e4);try{return{code:await t.promise,redirectUri:i}}finally{clearTimeout(o),await new Promise(e=>{n.close(()=>{e()})})}},X=e=>({authorize:async t=>{try{let n=v(32).toString(`base64url`),r=_(`sha256`).update(n).digest(`base64url`),i=v(32).toString(`base64url`),a=await Xt({...t,challenge:r,state:i});return await e.exchangeOauthCode({issuer:t.issuer,clientId:t.clientId,code:a.code,redirectUri:a.redirectUri,verifier:n})}catch(e){throw new n(`UNAUTHORIZED`,e instanceof Error?`Browser authentication failed: ${e.message}.`:`Browser authentication failed.`,`Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.`)}}}),Z=e=>e===void 0||e===``?void 0:e,Zt=((e,t,n)=>{let r=Z(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=Z(e.ENHANCE3_API_URL),a=g.join(t,`.config`,n.configDirectoryName),o=Z(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&&g.resolve(o)!==g.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}})(p.env,be(),{apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`}),Qt=f.object({token:f.string().startsWith(`enh_`)}),$t=e=>{let t=g.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await Oe(t,`utf8`));return Qt.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Ee(e,{recursive:!0,mode:448}),await b(e,448);let r=g.join(e,`credentials.${String(p.pid)}.tmp`);await je(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await Ae(r,t),await b(t,384)},remove:async()=>{try{return await C(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},en=f.object({access_token:f.string().min(1)}),Q=(e,t,n=null)=>Fe({links:[Ie({url:`${e}/trpc`,headers:{...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),tn=async e=>{let t=await fetch(e);if(!t.ok)throw new n(t.status===404||t.status===403?`NOT_FOUND`:`INTERNAL`,`Render download answered HTTP ${String(t.status)}.`,`The result may have expired. Request a new render.`);return new Uint8Array(await t.arrayBuffer())},nn=async e=>{let t=await fetch(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new n(`BAD_REQUEST`,`This Enhance API does not support browser authentication.`,`Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.`):new n(`INTERNAL`,`CLI authentication discovery answered HTTP ${String(t.status)}.`,`Run 'enhance doctor', report the result, and stop.`);return t.json()},rn=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await fetch(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw Error(`OAuth discovery answered HTTP ${String(n.status)}`);return n.json()},an=async e=>{let t=await fetch(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 Error(`token exchange answered HTTP ${String(t.status)}`);return en.parse(await t.json()).access_token},on=async e=>{try{let t=await fetch(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status}}catch{return{url:e,reachable:!1,status:null}}},sn=(e,t,r)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>nn(i),oauthMetadata:rn,exchangeOauthCode:an,query:async(e,n)=>Q(i,await t.read()).query(e,n),queryWithToken:async(e,t,n)=>Q(i,n).query(e,t),mutate:async(e,n)=>Q(i,await t.read(),r.current(e,n)).mutation(e,n),mutateWithToken:async(e,t,n)=>Q(i,n).mutation(e,t),download:tn,upload:async e=>{let t=!(e.body instanceof Uint8Array),r=t?Me.toWeb(e.body):e.body,i={method:`PUT`,headers:e.headers,body:r,...t&&{duplex:`half`}},a=await fetch(e.url,i);if(!a.ok)throw new n(`INTERNAL`,`Signed upload answered HTTP ${String(a.status)}.`,`Retry the fixture command with the same source file.`);let o=a.headers.get(`etag`);if(o===null||o===``)throw new n(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return o.replaceAll(`"`,``)},health:async()=>on(i)}},$=e=>Array.isArray(e)?e.map(e=>$(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,$(t)])),cn=(e,t,n)=>_(`sha256`).update(`${e}\0${t}\0${JSON.stringify($(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),ln=()=>{let e=y(),t=!1;return{current:(n,r)=>t?cn(e,n,r):e,select:(n,r)=>{e=n??y(),t=r}}};export{X as a,F as c,O as d,Be as f,Zt as i,N as l,sn as n,Gt as o,$t as r,L as s,ln as t,j as u};
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@enhance-eng/enhance-dev",
|
|
3
|
+
"version": "0.1.7-dev.sha-e8d495edd470",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "Development command-line interface for Enhance.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"enhance",
|
|
8
|
+
"agent",
|
|
9
|
+
"cli"
|
|
10
|
+
],
|
|
11
|
+
"homepage": "https://enhance3.karunalabs.ai/docs",
|
|
12
|
+
"license": "UNLICENSED",
|
|
13
|
+
"author": "Enhance",
|
|
14
|
+
"sideEffects": false,
|
|
15
|
+
"type": "module",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": "./dist/main.mjs",
|
|
18
|
+
"./mcp": "./dist/mcp.mjs"
|
|
19
|
+
},
|
|
20
|
+
"bin": {
|
|
21
|
+
"enhance-dev": "dist/main.mjs",
|
|
22
|
+
"enhance-dev-mcp": "dist/mcp-main.mjs"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"!dist/*.map"
|
|
27
|
+
],
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@modelcontextprotocol/core": "2.0.0",
|
|
30
|
+
"@modelcontextprotocol/node": "2.0.0",
|
|
31
|
+
"@modelcontextprotocol/server": "2.0.0",
|
|
32
|
+
"@trpc/client": "11.18.0",
|
|
33
|
+
"@trpc/server": "11.18.0",
|
|
34
|
+
"commander": "^14.0.0",
|
|
35
|
+
"trpc-cli": "0.16.0",
|
|
36
|
+
"yazl": "3.3.1",
|
|
37
|
+
"zod": "^4.4.3"
|
|
38
|
+
},
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=24"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public",
|
|
44
|
+
"registry": "https://registry.npmjs.org"
|
|
45
|
+
}
|
|
46
|
+
}
|