@enhance-eng/enhance-dev 0.1.15-dev.sha-09805341372a → 0.1.16-dev.sha-342a11e485fa
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.mjs
CHANGED
|
@@ -11,7 +11,7 @@ Edit shapes (combine related edits in one array):
|
|
|
11
11
|
Move destinations also accept {"kind":"after","nodeId":"other"} or {"kind":"parent","parentId":"screen","index":0}.
|
|
12
12
|
Use input-version IDs. Duplicate mappings are returned for a subsequent call.
|
|
13
13
|
`).action(async e=>{let n=V(e.edits,ie,`--edits`);t.output.result(await I(t,e,n))})},Vt=(e,t)=>{Bt(e,t),It(e,t),Lt(e,t),Rt(e,t),zt(e,t)},Ht=new Set([`flex-grow`,`flex-shrink`,`order`,`aspect-ratio`]),H=e=>e===`start`||e===`end`?`flex-${e}`:e,Ut=e=>{let t=`${String(e.ratio*100)}%`,n=e.offset??0;return n===0?t:`calc(${t} ${n<0?`-`:`+`} ${String(Math.abs(n))}px)`},Wt=(e,t)=>{let n=e[t],r=e[t===`min`?`minParent`:`maxParent`];if(r===void 0)return n;let i=Ut(r);return n===void 0?i:`${t===`min`?`max`:`min`}(${String(n)}px, ${i})`},Gt=(e,t,n)=>{if(t===void 0)return{};if(t.mode===`fixed`)return{[e]:t.value};let r={};for(let n of[`min`,`max`]){let i=Wt(t,n);i!==void 0&&(r[`${n}-${e}`]=i)}if(t.mode===`hug`)return{[e]:`max-content`,...r};let i=t.offset??0,a=i===0?`100%`:`calc(100% + ${String(i)}px)`;return{[e]:n&&i===0?`auto`:a,...r}},Kt=(e,t)=>{let n=e.box;if(n===void 0)return{};let r=d(e),i=e.layout?.position??y(e,`position`),o=i===void 0||[`absolute`,`fixed`].includes(i),s=e=>(e===`horizontal`?[`left`,`right`,`inset`,`inset-inline`,`inset-inline-start`,`inset-inline-end`]:[`top`,`bottom`,`inset`,`inset-block`,`inset-block-start`,`inset-block-end`]).some(e=>r[e]!==void 0),c=n=>a(e,n,t).some(t=>r[t]!==void 0||e.additionalStyles?.declarations.some(e=>e.property.toLowerCase()===t)===!0);return{...r[`box-sizing`]===void 0&&{"box-sizing":`border-box`},...o&&r.position===void 0&&{position:`absolute`},...o&&!s(`horizontal`)&&{left:n.x},...o&&!s(`vertical`)&&{top:n.y},...o&&e.layout?.horizontal===void 0&&!c(`horizontal`)&&{width:n.width},...o&&e.layout?.vertical===void 0&&!c(`vertical`)&&{height:n.height}}},qt=e=>{if(e.gridColumns!==void 0)return`repeat(${String(e.gridColumns)}, minmax(0, 1fr))`;if(e.gridAutoRepeat!==void 0)return`repeat(${e.gridAutoRepeat.mode}, minmax(${String(e.gridAutoRepeat.minimum)}px, 1fr))`},Jt=e=>{let t=e.layout,n=t?.container,r=t?.clipContent===void 0?{}:{overflow:t.clipContent?`hidden`:`visible`};if(n===void 0)return r;let i=qt(n),a=n.rowGap??n.gap,o=n.columnGap??n.gap;return{...r,...y(e,`display`)===void 0&&{display:i===void 0?`flex`:`grid`},...i!==void 0&&{"grid-template-columns":i},...n.direction!==void 0&&{"flex-direction":n.direction},...n.wrap!==void 0&&{"flex-wrap":n.wrap},...n.alignItems!==void 0&&{"align-items":H(n.alignItems)},...n.alignContent!==void 0&&{"align-content":H(n.alignContent)},...n.justifyContent!==void 0&&{"justify-content":H(n.justifyContent)},...a!==void 0&&{"row-gap":a},...o!==void 0&&{"column-gap":o},...Object.fromEntries(Object.entries(n.padding??{}).map(([e,t])=>[`padding-${e}`,t]))}},Yt=(e,t)=>{let n=e.layout??{},r=n=>t!==void 0&&y(e,n)===void 0,i=n.flexBasis??(t?.mode===`fill`?0:`auto`);return{...(r(`flex-basis`)||n.flexBasis!==void 0)&&{"flex-basis":typeof i==`object`?Ut(i):i},...(r(`flex-grow`)||n.flexGrow!==void 0)&&{"flex-grow":n.flexGrow??+(t?.mode===`fill`)},...(r(`flex-shrink`)||n.flexShrink!==void 0)&&{"flex-shrink":n.flexShrink??+(t?.mode===`fill`)},...n.flowOffset!==void 0&&{left:n.flowOffset.x,top:n.flowOffset.y},...n.order!==void 0&&{order:n.order},...Object.fromEntries(Object.entries(n.margin??{}).map(([e,t])=>[`margin-${e}`,t]))}},Xt=e=>{let t=[...e.rotation===void 0||e.rotation===0?[]:[`rotate(${String(e.rotation)}deg)`],...e.flipHorizontal===!0?[`scaleX(-1)`]:[],...e.flipVertical===!0?[`scaleY(-1)`]:[]];return t.length===0?{}:{transform:t.join(` `)}},Zt=(e,t)=>e.alignSelf===void 0||e.alignSelf===`auto`?t?.mode===`fill`?`stretch`:void 0:H(e.alignSelf),Qt=(e,t)=>{if(t===void 0)return{};let n=e.layout?.[t],r=t===`horizontal`?`min-width`:`min-height`;return n?.mode!==`fill`||n.min!==void 0||n.minParent!==void 0||d(e)[r]!==void 0?{}:{[r]:0}},$t=(e,t)=>{let n=e.layout;if(n===void 0)return{};let i=t?.relationships[e.id]?.parentId,a=r(i===void 0?void 0:t?.nodes[i],t),o=n.position??y(e,`position`),s=o===`flow`||o!==`absolute`&&o!==`fixed`&&(o!==void 0||e.box===void 0),c=a===`horizontal`?n.horizontal:n.vertical,l=a===`horizontal`?n.vertical:n.horizontal,u=Zt(n,l);return{...n.position!==void 0&&{position:s?`relative`:`absolute`},...Gt(`width`,n.horizontal,s&&(a===`horizontal`||u===`stretch`)),...Gt(`height`,n.vertical,s&&(a===`vertical`||u===`stretch`)),...s&&a!==void 0&&Yt(e,c),...s&&u!==void 0&&{"align-self":u},...s&&Qt(e,a),...u===`stretch`&&l?.mode===`hug`&&a!==void 0&&{[a===`horizontal`?`height`:`width`]:`auto`},...n.aspectRatio!==void 0&&{"aspect-ratio":n.aspectRatio},...Xt(n)}},en=(e,t)=>Object.fromEntries(Object.entries({...Kt(e,t),...ee(e,{...$t(e,t),...Jt(e)})}).map(([e,t])=>[e,typeof t==`number`&&!Ht.has(e)?`${String(t)}px`:t])),U=e=>e.space===`display-p3`?`color(display-p3 ${String(e.red)} ${String(e.green)} ${String(e.blue)} / ${String(e.alpha)})`:`rgba(${String(Math.round(e.red*255))}, ${String(Math.round(e.green*255))}, ${String(Math.round(e.blue*255))}, ${String(e.alpha)})`,W=e=>{if(!e.visible)return null;if(e.kind===`solid`)return U(e.color);if(e.kind===`image`)return`url(${JSON.stringify(e.assetId)})`;let t=e.stops.map(e=>`${U(e.color)} ${String(e.position*100)}%`).join(`, `);return e.kind===`linear-gradient`?`linear-gradient(${String(e.angle)}deg, ${t})`:`radial-gradient(at ${String(e.center.x*100)}% ${String(e.center.y*100)}%, ${t})`},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=W(e);return t===null?[]:[t]})??[],rn=e=>{if(e?.visible!==!0)return{};let t=W(e.paint);return{"border-width":[e.width.top,e.width.right,e.width.bottom,e.width.left].map(e=>`${String(e)}px`).join(` `),"border-style":e.style,...t!==null&&{"border-color":t}}},an=e=>{if(e?.visible!==!0)return{};let t=W(e.paint);return{"outline-width":`${String(e.width)}px`,"outline-offset":`${String(e.offset)}px`,"outline-style":e.style,...t!==null&&{"outline-color":t}}},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 ${U(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},ln=(e,t)=>({...Object.fromEntries(Object.entries(d(e)).filter(([t])=>e.layout?.clipContent===void 0||![`overflow`,`overflow-x`,`overflow-y`].includes(t))),...cn(e.typography),...sn(e.appearance),...en(e,t),...e.visible===!1&&{display:`none`}}),un=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),G=(e,t)=>{let n=e.nodes[t];if(n===void 0)throw new l(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`);return n},K=(e,t)=>{let n=e.props?.[t];return typeof n==`string`?n:``},dn=e=>`{${JSON.stringify(e)}}`,fn=(e,t,n,r)=>{let i=G(e,t),a=` `.repeat(n),o=[`data-node-id=${JSON.stringify(i.id)}`,`data-name=${JSON.stringify(i.label)}`,`style={${JSON.stringify(ln(i,e))}}`];if(i.locked===!0&&o.push(`data-locked="true"`),i.component===`image`)return`${a}<img ${o.join(` `)} alt=${JSON.stringify(K(i,`alt`))} src=${JSON.stringify(K(i,`src`))} />`;if(i.component===`svg`)return`${a}<div ${o.join(` `)} data-component="svg" />`;let s=i.component===`text`?`span`:`div`,c=i.component===`text`?dn(K(i,`text`)):``,l=(n>=r?[]:un(e,t)).map(t=>fn(e,t,n+1,r));return c===``&&l.length===0?`${a}<${s} ${o.join(` `)} />`:[`${a}<${s} ${o.join(` `)}>`,...c===``?[]:[`${a} ${c}`],...l,`${a}</${s}>`].join(`
|
|
14
|
-
`)},pn=(e,t,n)=>fn(e,t,0,n),mn=(e,t)=>t.map(t=>{let n=G(e,t);return{nodeId:t,name:n.label,component:n.component,box:n.box,css:ln(n,e),layout:n.layout,appearance:n.appearance,typography:n.typography}}),hn={topic:`canvas-agent-authoring`,workflow:[`Keep the complete selection link as --canvas; only selected nodes and descendants are in scope.`,`Unknown state: canvas inspect. When nodeCount=0, use target root and its version to create a populated screen using write-html --review none. No blank pre-render or empty shell.`,`Existing content: read only missing subtree structure or ids. Reuse useful context and product styles.`,`Batch related text, style, rename, duplicate and move changes with canvas edit --edits. Existing focused commands also work.`,`Use the version from the latest successful read or write as --base-version. After a conflict, reread and recompute the requested edit.`,`Render the affected screen when ready for review and inspect the PNG. Repeat after changes or a concrete discrepancy.`],html:{modes:[`insert-children`,`replace`],rules:[`Use inline concrete CSS; flex, padding and gap. Avoid margin, grid, tables and inline layout.`,`Give screen rows, cards and buttons explicit dimensions; avoid relying on implicit stretch. Use block frames for colored badges.`,`Name meaningful groups with layer-name; include content and structure together.`,`Styled text controls become frames with editable text children.`,`Scripts, event handlers, embedded documents, executable URLs and CSS imports are rejected.`]},completion:[`Natural hierarchy with the fewest useful editable primitives.`,`The committed version and affected ids match the request.`,`Inspect the final PNG for hierarchy, alignment, clipping and overflow.`,`Keep text, layout and appearance editable in the ordinary inspector.`]},gn=async(e,t)=>{let n=h.parse(await e.remote.query(`canvas.document.get`,{canvasId:t}));return{held:n,document:b.parse(n.document)}},_n=(e,n)=>{e.command(`guide`).description(`Agent design workflow.`).action(()=>{n.output.result(hn)}),e.command(`get-jsx`).description(`Read concise subtree JSX.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-id <id>`,`Stable subtree root id.`).option(`--depth <integer>`,`Maximum descendant depth from 0 to 20.`,`8`).action(async e=>{let r=t(e.canvas),a=r.canvasId,{held:o,document:s}=await gn(n,a);i(r,s,[e.nodeId]),n.output.result({canvasId:a,version:o.version,nodeId:e.nodeId,jsx:pn(s,e.nodeId,M(bt,e.depth,`--depth`)),warning:`This is a structural reading projection. Use canvas render as the pixel authority.`})}),e.command(`get-computed-styles`).description(`Read effective node CSS.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).action(async e=>{let r=t(e.canvas),a=r.canvasId,{held:o,document:s}=await gn(n,a),c=V(e.nodeIds,j,`--node-ids`);i(r,s,c),n.output.result({canvasId:a,version:o.version,nodes:mn(s,c),warning:`These are authored CSS instructions, not measured browser dimensions. Use canvas render as the pixel authority.`})})},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=>{let n=await I(t,e,V(e.nodes,vt,`--nodes`).map(e=>({kind:`duplicate`,nodeIds:[e.id],...e.parentId!==void 0&&{parentId:e.parentId}})),e.idPrefix),{duplicatedNodes:r,...i}=n;t.output.result({...n,duplicatedNodes:r,apply:i})})},yn=(e,t)=>{e.command(`move-nodes`).description(`Reorder or reparent nodes.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--moves <json-or-@path>`,`Sequential before, after, or parent/index moves.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=await I(t,e,V(e.moves,yt,`--moves`).map(e=>({kind:`move`,nodeId:e.nodeId,destination:`before`in e?{kind:`before`,nodeId:e.before}:`after`in e?{kind:`after`,nodeId:e.after}:{kind:`parent`,parentId:e.parentId,...e.index!==void 0&&{index:e.index}}}))),{moves:r,affectedParents:i,...a}=n;t.output.result({...n,moves:r,affectedParents:i,apply:a})})},bn=(e,t)=>{vn(e,t),yn(e,t)},xn=262144,Sn=e=>{let t=B(e,xn,`--html`);if(Buffer.byteLength(t,`utf8`)>xn)throw new l(`BAD_REQUEST`,`--html exceeds 262144 bytes.`,`Write one visual group at a time, as taught by canvas guide.`);return t},Cn=new Set([`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`]),wn=async(e,n)=>{if(![`insert-children`,`replace`].includes(n.mode))throw new l(`BAD_REQUEST`,`--mode must be insert-children or replace.`,`Choose one of the two documented modes.`);if(![`none`,`render`].includes(n.review))throw new l(`BAD_REQUEST`,`--review must be none or render.`,`Choose one of the documented review modes.`);P(e,n.clientToken,!0);let r=n.mode===`replace`?`replace`:`insert-children`,i=t(n.canvas),a=N(n.baseVersion);e.output.result(await e.invocation.invoke({capability:L(e.catalog(),`canvas.writeHtml`),arguments:{canvasId:i.canvasId,...i.nodeIds.length>0&&{selectionNodeIds:[...i.nodeIds]},targetNodeId:n.targetNodeId,mode:r,html:Sn(n.html),...n.idPrefix!==void 0&&{idPrefix:n.idPrefix},baseVersion:a,review:n.review,renderOutputPath:n.output??null,overwriteRender:n.force===!0,renderScale:M(dt,n.scale,`--scale`),renderTimeoutMs:M(ut,n.timeoutMs,`--timeout-ms`)},clientToken:n.clientToken??null}))},Tn=(e,t)=>{e.command(`write-html`).description(`Compile HTML/CSS primitives.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--target-node-id <id>`,`Container receiving children, or node to replace.`).requiredOption(`--html <html-or-@path>`,`Inline HTML fragment or @path to a UTF-8 file.`).option(`--mode <mode>`,`insert-children or replace.`,`insert-children`).option(`--review <mode>`,`none to return after commitment; render to include review pixels.`,`render`).option(`--id-prefix <prefix>`,`Fresh namespace for a new import/replacement; reuse only for an identical retry.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact write and review.`).option(`--output <path>`,`Write the review PNG to this path.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--scale <number>`,`Review pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--timeout-ms <integer>`,`Review render polling deadline.`,`120000`).addHelpText(`after`,`
|
|
14
|
+
`)},pn=(e,t,n)=>fn(e,t,0,n),mn=(e,t)=>t.map(t=>{let n=G(e,t);return{nodeId:t,name:n.label,component:n.component,box:n.box,css:ln(n,e),layout:n.layout,appearance:n.appearance,typography:n.typography}}),hn={topic:`canvas-agent-authoring`,workflow:[`Keep the complete selection link as --canvas; only selected nodes and descendants are in scope.`,`Unknown state: canvas inspect. When nodeCount=0, use target root and its version to create a populated screen using write-html --review none. No blank pre-render or empty shell.`,`Multiple screens: publish each populated screen before authoring the next so users see progress. Prepare only what that screen needs; do not prepare the whole set before the first write.`,`Existing content: read only missing subtree structure or ids. Reuse useful context and product styles.`,`Batch related text, style, rename, duplicate and move changes with canvas edit --edits. Existing focused commands also work.`,`Use the version from the latest successful read or write as --base-version. After a conflict, reread and recompute the requested edit.`,`Render the affected screen when ready for review and inspect the PNG. Repeat after changes or a concrete discrepancy.`],html:{modes:[`insert-children`,`replace`],rules:[`Use inline concrete CSS; flex, padding and gap. Avoid margin, grid, tables and inline layout.`,`Give screen rows, cards and buttons explicit dimensions; avoid relying on implicit stretch. Use block frames for colored badges.`,`Name meaningful groups with layer-name; include content and structure together.`,`Styled text controls become frames with editable text children.`,`Scripts, event handlers, embedded documents, executable URLs and CSS imports are rejected.`]},completion:[`Natural hierarchy with the fewest useful editable primitives.`,`The committed version and affected ids match the request.`,`Inspect the final PNG for hierarchy, alignment, clipping and overflow.`,`Keep text, layout and appearance editable in the ordinary inspector.`]},gn=async(e,t)=>{let n=h.parse(await e.remote.query(`canvas.document.get`,{canvasId:t}));return{held:n,document:b.parse(n.document)}},_n=(e,n)=>{e.command(`guide`).description(`Agent design workflow.`).action(()=>{n.output.result(hn)}),e.command(`get-jsx`).description(`Read concise subtree JSX.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-id <id>`,`Stable subtree root id.`).option(`--depth <integer>`,`Maximum descendant depth from 0 to 20.`,`8`).action(async e=>{let r=t(e.canvas),a=r.canvasId,{held:o,document:s}=await gn(n,a);i(r,s,[e.nodeId]),n.output.result({canvasId:a,version:o.version,nodeId:e.nodeId,jsx:pn(s,e.nodeId,M(bt,e.depth,`--depth`)),warning:`This is a structural reading projection. Use canvas render as the pixel authority.`})}),e.command(`get-computed-styles`).description(`Read effective node CSS.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).action(async e=>{let r=t(e.canvas),a=r.canvasId,{held:o,document:s}=await gn(n,a),c=V(e.nodeIds,j,`--node-ids`);i(r,s,c),n.output.result({canvasId:a,version:o.version,nodes:mn(s,c),warning:`These are authored CSS instructions, not measured browser dimensions. Use canvas render as the pixel authority.`})})},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=>{let n=await I(t,e,V(e.nodes,vt,`--nodes`).map(e=>({kind:`duplicate`,nodeIds:[e.id],...e.parentId!==void 0&&{parentId:e.parentId}})),e.idPrefix),{duplicatedNodes:r,...i}=n;t.output.result({...n,duplicatedNodes:r,apply:i})})},yn=(e,t)=>{e.command(`move-nodes`).description(`Reorder or reparent nodes.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--moves <json-or-@path>`,`Sequential before, after, or parent/index moves.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=await I(t,e,V(e.moves,yt,`--moves`).map(e=>({kind:`move`,nodeId:e.nodeId,destination:`before`in e?{kind:`before`,nodeId:e.before}:`after`in e?{kind:`after`,nodeId:e.after}:{kind:`parent`,parentId:e.parentId,...e.index!==void 0&&{index:e.index}}}))),{moves:r,affectedParents:i,...a}=n;t.output.result({...n,moves:r,affectedParents:i,apply:a})})},bn=(e,t)=>{vn(e,t),yn(e,t)},xn=262144,Sn=e=>{let t=B(e,xn,`--html`);if(Buffer.byteLength(t,`utf8`)>xn)throw new l(`BAD_REQUEST`,`--html exceeds 262144 bytes.`,`Write one visual group at a time, as taught by canvas guide.`);return t},Cn=new Set([`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`]),wn=async(e,n)=>{if(![`insert-children`,`replace`].includes(n.mode))throw new l(`BAD_REQUEST`,`--mode must be insert-children or replace.`,`Choose one of the two documented modes.`);if(![`none`,`render`].includes(n.review))throw new l(`BAD_REQUEST`,`--review must be none or render.`,`Choose one of the documented review modes.`);P(e,n.clientToken,!0);let r=n.mode===`replace`?`replace`:`insert-children`,i=t(n.canvas),a=N(n.baseVersion);e.output.result(await e.invocation.invoke({capability:L(e.catalog(),`canvas.writeHtml`),arguments:{canvasId:i.canvasId,...i.nodeIds.length>0&&{selectionNodeIds:[...i.nodeIds]},targetNodeId:n.targetNodeId,mode:r,html:Sn(n.html),...n.idPrefix!==void 0&&{idPrefix:n.idPrefix},baseVersion:a,review:n.review,renderOutputPath:n.output??null,overwriteRender:n.force===!0,renderScale:M(dt,n.scale,`--scale`),renderTimeoutMs:M(ut,n.timeoutMs,`--timeout-ms`)},clientToken:n.clientToken??null}))},Tn=(e,t)=>{e.command(`write-html`).description(`Compile HTML/CSS primitives.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--target-node-id <id>`,`Container receiving children, or node to replace.`).requiredOption(`--html <html-or-@path>`,`Inline HTML fragment or @path to a UTF-8 file.`).option(`--mode <mode>`,`insert-children or replace.`,`insert-children`).option(`--review <mode>`,`none to return after commitment; render to include review pixels.`,`render`).option(`--id-prefix <prefix>`,`Fresh namespace for a new import/replacement; reuse only for an identical retry.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact write and review.`).option(`--output <path>`,`Write the review PNG to this path.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--scale <number>`,`Review pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--timeout-ms <integer>`,`Review render polling deadline.`,`120000`).addHelpText(`after`,`
|
|
15
15
|
Write one visual group at a time. Use --review none for a committed receipt, then render its version and inspect the PNG. Use flex, padding and gap; use targeted commands for later edits.
|
|
16
16
|
`).action(async e=>wn(t,e))},En=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),Dn=(e,t)=>typeof t==`number`&&!Cn.has(e)?`${String(t)}px`:String(t),On=e=>Object.entries(e).filter(([,e])=>e!==null).map(([e,t])=>{let n=En(e);return`${n}:${Dn(n,t??``)}`}).join(`;`).replaceAll(`&`,`&`).replaceAll(`"`,`"`),kn=e=>e.length===0?0:Math.max(...e.map(e=>e.x+e.width))+80,An=(e,t)=>{e.command(`create-artboard`).description(`Create a top-level frame.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--name <name>`,`Meaningful layer name.`).requiredOption(`--styles <json-or-@path>`,`CSSProperties with width and height.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact creation and review.`).option(`--output <path>`,`Review PNG path.`).option(`--force`,`Replace an existing review PNG.`,!1).action(async e=>{let n=V(e.styles,mt,`--styles`);if(n.width===void 0||n.height===void 0)throw new l(`BAD_REQUEST`,`--styles must include width and height.`,`Use explicit whole-pixel dimensions such as 1440px and 900px.`);P(t,e.clientToken,!0);let r=m(e.canvas),i=N(e.baseVersion),a=await S(t,r,i),o=Object.entries(a.relationships).flatMap(([e,t])=>{let n=a.nodes[e]?.box;return n!==void 0&&t.parentId===`root`?[n]:[]}),s={display:`flex`,flexDirection:`column`,left:kn(o),top:0,...n,position:`absolute`},c=e.name.replaceAll(`&`,`&`).replaceAll(`"`,`"`);t.output.result(await Te(t.remote,t.render).execute({canvasId:r,targetNodeId:`root`,mode:`insert-children`,html:`<div layer-name="${c}" data-enhance-kind="frame" style="${On(s)}"></div>`,idPrefix:`artboard_${t.mutationKey.current(`canvas.render.importSource`,{canvasId:r})}`,baseVersion:i,renderClientToken:t.mutationKey.current(`canvas.render.create`,{purpose:`create-artboard-review`}),renderOutputPath:e.output??null,overwriteRender:e.force===!0,renderScale:1,renderTimeoutMs:12e4}))})},jn=(e,t)=>{Tn(e,t),An(e,t)},Mn=(e,t)=>{_n(e,t),jn(e,t),Vt(e,t),bn(e,t),Ft(e,t)},Nn=e=>{let n=e.getOptionValue(`canvas`),r=e.getOptionValue(`canvasId`);if(n!==void 0&&r!==void 0)throw new l(`BAD_REQUEST`,`--canvas and --canvas-id cannot be combined.`,`Pass the pasted URL or UUID through --canvas.`);let i=n??r;if(typeof i!=`string`)throw new l(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);return{reference:t(i),url:i}},Pn=(e,t)=>{let n=e.getOptionValue(`nodeId`)??(t.nodeIds.length===1?t.nodeIds[0]:void 0);if(typeof n!=`string`||n===``)throw new l(`BAD_REQUEST`,`--node-id or a single-node selection link is required.`,`Choose one node, or use canvas tree to inspect the linked selection.`);return n},Fn=async(e,t,n,r)=>{let a=h.parse(await t.remote.query(`canvas.document.get`,{canvasId:n.canvasId})),o=b.parse(a.document),s=u(n,o),c=Object.values(o.nodes).filter(e=>s.has(e.id)).map(e=>({...e,kind:e.component,parentId:o.relationships[e.id]?.parentId??null,children:Object.entries(o.relationships).filter(([,t])=>t.parentId===e.id).map(([e])=>e)})),l={canvasId:n.canvasId,version:a.version,source:`selection-link`,selectedNodeIds:n.nodeIds,next:[`Keep this selection link as --canvas for every edit: ${r}`,`Edit only these nodes or their descendants; other canvas content is outside the request.`]};if(e.name()===`node`){let t=Pn(e,n);return i(n,o,[t]),{...l,node:c.find(e=>e.id===t)}}return{...l,nodes:c}},In=(e,t)=>{for(let n of[`inspect`,`tree`,`node`,`selection`]){let r=e.commands.find(e=>e.name()===n),i=r?.options.find(e=>e.long===`--canvas-id`);r!==void 0&&i!==void 0&&(i.makeOptionMandatory(!1),r.options.find(e=>e.long===`--node-id`)?.makeOptionMandatory(!1),r.option(`--canvas <url-or-id>`,`Pasted canvas URL or UUID. Selection links limit reads and edits to the linked subtree.`),r.action(async()=>{let{reference:e,url:i}=Nn(r),a=e.nodeIds.length>0?await Fn(r,t,e,i):await t.remote.query(`canvas.${n}`,{canvasId:e.canvasId,...n===`node`&&{nodeId:Pn(r,e)}});t.output.result(a)}))}},Ln=C.coerce.number().int().positive(),Rn=C.coerce.number().int().nonnegative(),zn=C.coerce.number().min(ve).max(4),q=(e,t,n,r=`canvas render`)=>{let i=e.safeParse(t);if(!i.success)throw new l(`BAD_REQUEST`,`${n} is invalid.`,`Run 'enhance ${r} --help'.`);return i.data},Bn=e=>{if(e===void 0)return null;try{let t=de.safeParse(JSON.parse(e));if(t.success)return t.data}catch{}throw new l(`BAD_REQUEST`,`--bounds must be a finite positive world rectangle.`,`Pass JSON such as '{"x":0,"y":0,"width":800,"height":600}'.`)},Vn=(e,t)=>e===void 0?t===null?{kind:`content`}:{kind:`bounds`,bounds:t}:{kind:`node`,nodeId:e},Hn=e=>{if(!(typeof e!=`string`||!e.startsWith(`rec_`)))return C.uuid().safeParse(e.slice(4)).data},Un=(e,t)=>{let n=C.uuid().nullable().safeParse(t??null);if(!n.success)throw new l(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact render.`);return e.mutationKey.select(n.data,!1),e.mutationKey.current(`canvas.render.create`,{})},Wn=async(e,n)=>{let r=t(e.canvas??``);if(r.nodeIds.length===0)return e.nodeId;let a=e.nodeId??(r.nodeIds.length===1?r.nodeIds[0]:void 0);if(a===void 0||e.bounds!==void 0)throw new l(`BAD_REQUEST`,`A selection link requires one selected node to render.`,`Pass --node-id for one node in the selection; bounds and whole-canvas renders would include unrelated content.`);let o=h.parse(await n.remote.query(`canvas.document.get`,{canvasId:r.canvasId}));return i(r,b.parse(o.document),[a]),a},Gn=async(e,n)=>{if(e.canvas===void 0)throw new l(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);if(e.nodeId!==void 0&&e.bounds!==void 0)throw new l(`BAD_REQUEST`,`--node-id and --bounds cannot be combined.`,`Choose one focused target, or omit both to render all authored content.`);let r=await Wn(e,n);if(r===void 0&&e.atMs!==void 0)throw new l(`BAD_REQUEST`,`--at-ms requires --node-id.`,"Render the stable recording node returned by `enhance canvas tree`.");let i=e.atMs===void 0?null:Hn(r);if(i===void 0&&e.atMs!==void 0)throw new l(`BAD_REQUEST`,`--at-ms requires a stable recording node id such as rec_<recording-uuid>.`,"Run `enhance canvas tree --canvas <url-or-id>` and choose a recording node.");Un(n,e.clientToken);let a=await n.invocation.invoke({capability:L(n.catalog(),`canvas.render`),arguments:{canvasId:t(e.canvas).canvasId,expectedVersion:e.expectedVersion===void 0?null:q(Ln,e.expectedVersion,`--expected-version`),target:Vn(r,Bn(e.bounds)),sourceState:i==null?null:{kind:`recording`,recordingId:i,atMs:q(Rn,e.atMs??``,`--at-ms`)},scale:q(zn,e.scale,`--scale`),outputPath:e.output??null,overwrite:e.force===!0,timeoutMs:q(Ln,e.timeoutMs,`--timeout-ms`)},clientToken:e.clientToken??null});n.output.result(a)},Kn=(e,t)=>{e.option(`--canvas <url-or-id>`,`Canvas URL or UUID to render.`).option(`--node-id <id>`,`Render one stable canvas node instead of all authored content.`).option(`--bounds <json>`,`Render an explicit rectangle in canvas world coordinates.`).option(`--expected-version <integer>`,`Refuse pixels from any other document version.`).option(`--at-ms <integer>`,`Pause a recording node at this millisecond; inspect the PNG before snapshotting it.`).option(`--scale <number>`,`Output pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--output <path>`,`Write the PNG to this path instead of a protected temporary file.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--timeout-ms <integer>`,`Local polling deadline in milliseconds.`,`120000`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this render request.`).addHelpText(`after`,`
|
|
17
17
|
For transcript-led selection, inspect nearby --at-ms renders and reject transitions or duplicate states before running recording snapshot.
|
|
@@ -20,4 +20,4 @@ For transcript-led selection, inspect nearby --at-ms renders and reject transiti
|
|
|
20
20
|
Preview first: canvas render --node-id rec_<recording-uuid> --at-ms <integer>, then inspect its PNG. This command persists the accepted moment.
|
|
21
21
|
`).action(async e=>{let n=C.uuid().nullable().safeParse(e.clientToken??null),r=C.uuid().safeParse(e.recordingId);if(!n.success||!r.success)throw new l(`BAD_REQUEST`,`The recording id or client token is not a UUID.`,"Use the recording id from `recording list`; mint one client token per accepted moment.");t.output.result(await t.invocation.invoke({capability:L(t.catalog(),`recording.snapshot`),arguments:{canvasId:m(e.canvas),recordingId:r.data,atMs:Ar(e.atMs,`--at-ms`,!1),timeoutMs:Ar(e.timeoutMs,`--timeout-ms`,!0)},clientToken:n.data}))})},Mr=(e,t,n)=>{if(e!==`canvas.document.save`||typeof n!=`object`||!n||!(`outcome`in n)||n.outcome!==`conflict`)return n;throw new l(`CONFLICT`,`The canvas document changed before this save landed.`,`Run 'enhance canvas document get --canvas-id ${typeof t==`object`&&t&&`canvasId`in t&&typeof t.canvasId==`string`?t.canvasId:`<canvas-id>`}', merge your change into that document, then retry with its version.`)},Nr=(e,t)=>$e(e,e=>({[e]:{query:async n=>t.query(e,n),mutate:async n=>Mr(e,n,await t.mutate(e,n))}})),Pr=(e,t)=>{let n=e.commands.find(e=>e.name()===`transcript`);if(n===void 0)throw TypeError(`the API router did not supply transcript commands`);n.command(`get`).description(`Read timestamped speech cues as candidate moments; render and inspect candidate PNGs before snapshotting.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID containing the recording.`).requiredOption(`--recording-id <uuid>`,`Recording UUID returned by recording list.`).action(async e=>{let n=C.uuid().safeParse(e.recordingId);if(!n.success)throw new l(`BAD_REQUEST`,`--recording-id must be a UUID.`,"Use the recording id returned by `enhance recording list`.");t.output.result(await t.invocation.invoke({capability:L(t.catalog(),`transcript.read`),arguments:{canvasId:m(e.canvas),recordingId:n.data},clientToken:null}))})},Fr={jsonInput:`auto`,prompts:!1,logger:`ndjson`,errorMapping:`stable-exit-codes`},Ir=e=>{let t=e.state;return{logger:e.output.logger,prompts:Fr.prompts,process:Xn(),formatError:e=>{let n=_(e,t.pendingParserMessage);return t.exitCode=ae(n,!1,e),t.pendingParserMessage=null,JSON.stringify(n)}}},Lr=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,Rr=e=>{let t=Lr(e),n=t===null?void 0:t.description;return typeof n==`string`&&n!==``?n:null},zr=e=>{let t=ze({router:e});return{descriptions:new Map(t.flatMap(([e,t])=>{let n=Rr(t.meta);return n===null?[]:[[e,n]]})),mutationPaths:new Set(t.flatMap(([e,t])=>t.type===`mutation`?[e]:[]))}},Br=()=>{let e=null;return()=>(e??=se(),e)},Vr=(e,t,n)=>{let r=at(t.remote),i=je({remote:t.remote,mutationKey:t.mutationKey,configDirectory:t.configDirectory,now:()=>new Date,progress:t.output.result});lt(e,ke(t.credentials,t.remote,we(t.remote)),t.output),hr(e,i,n,t.output),gr(e,{version:t.version,credentials:t.credentials,remote:t.remote,output:t.output}),Tr(e,{screen:r,recording:rt(t.remote),world:ot(t.remote,r)},t.output),mr(e,t.output,n),qn(e,{remote:t.remote,mutationKey:t.mutationKey,invocation:i,catalog:n,output:t.output,configDirectory:t.configDirectory,now:()=>new Date}),jr(e,{invocation:i,catalog:n,output:t.output}),kr(e,i,n,t.output),Pr(e,{invocation:i,catalog:n,output:t.output})},Hr=e=>{let t=le(),n=Br(),{descriptions:r,mutationPaths:i}=zr(t),a=Re({router:Nr(t,e.remote),name:e.commandName,version:e.version,description:`Operate Enhance as the authenticated person.`,jsonInput:Fr.jsonInput}),o=Ir(e),s=a.buildProgram(o);if(!(s instanceof Le))throw TypeError(`trpc-cli did not return a Commander program`);dr(s),Vr(s,e,n),sr(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 v))throw t;if(t.requestedCode!==0&&c.pendingParserMessage!==null){let n=_(t,c.pendingParserMessage);c.exitCode=ae(n,!0),c.pendingParserMessage=null,e.output.failure(n)}throw t}}}},Ur=e=>w.exit(e),Wr=36e5,X=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Gr=e=>{if(Array.isArray(e))return e.map(e=>JSON.stringify(e));if(!X(e)||!Array.isArray(e.items))return[JSON.stringify(e)];let t=e.items;if(t.length===0)return[JSON.stringify(e)];let n=e.truncated===!0;return t.map(e=>JSON.stringify(X(e)?{...e,truncated:n}:{value:e,truncated:n}))},Kr=e=>{let t=`${e.join(`
|
|
22
22
|
`)}\n`;if(!(t.length>25e3||e.some(e=>e.length>2e3))){w.stdout.write(t);return}let n=Ze(`sha256`).update(t).digest(`hex`).slice(0,16),r=E.join(Ve(),`enhance-${n}.ndjson`);T(r,t,{mode:384}),w.stdout.write(`${JSON.stringify({path:r,characters:t.length,records:e.length})}\n`)},qr=e=>{try{let t=new URL(e),n=new Set;for(let e of t.searchParams.keys())n.add(e.toLowerCase());return n.has(`x-amz-signature`)||n.has(`x-amz-credential`)||n.has(`x-amz-algorithm`)}catch{return!1}},Z=e=>typeof e==`string`?qr(e):Array.isArray(e)?e.some(e=>Z(e)):X(e)?Object.values(e).some(e=>Z(e)):!1,Q=e=>{Ke(e,{recursive:!0,mode:448}),Ue(e,448)},Jr=e=>{if(!We(e))return;let t=Date.now()-Wr,n=Je(e,{withFileTypes:!0});for(let r of n){if(!r.isFile()||!r.name.startsWith(`result-`))continue;let n=E.join(e,r.name);Ge(n).mtimeMs<t&&Xe(n)}},$=e=>({...e,sensitive:!0,cleanup:`unlink-after-use`,deleteAfter:new Date(Date.now()+Wr).toISOString()}),Yr=(e,t)=>{let n=Gr(e),r=`${n.join(`
|
|
23
|
-
`)}\n`;Q(t);let i=E.join(t,`result-${D()}.ndjson`);T(i,r,{mode:384,flag:`wx`}),w.stdout.write(`${JSON.stringify($({path:i,characters:r.length,records:n.length,reason:`signed-url`}))}\n`)},Xr=e=>X(e)?typeof e.token==`string`?{field:`token`,value:e.token}:typeof e.acceptToken==`string`?{field:`acceptToken`,value:e.acceptToken}:null:null,Zr=(e,t,n)=>{let r=`${t.value}\n`;Q(n);let i=E.join(n,`result-${D()}.token`);T(i,r,{mode:384,flag:`wx`});let a=Object.fromEntries(Object.entries(e).filter(([e])=>e!==t.field));w.stdout.write(`${JSON.stringify({...a,secret:$({path:i,field:t.field,characters:r.length})})}\n`)},Qr=e=>e.includes(`Usage:`)||e.includes(`Options:`)||e.includes(`Commands:`),$r=te.omit({fields:!0}).extend({remediation:C.string(),fields:C.array(C.object({path:C.string(),message:C.string()})).optional()}),ei=e=>{try{let t=JSON.parse(e),n=$r.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}},ti=(e,t)=>{if(typeof e==`string`&&Qr(e)){w.stdout.write(e);return}let n=Xr(e);if(n!==null&&X(e)){Zr(e,n,t);return}if(Z(e)){Yr(e,t);return}let r=fe(e);if(r!==null){let e=null;if(r.detail!==null){Q(t);let n=E.join(t,`result-${D()}.ndjson`),i=`${JSON.stringify(r.detail)}\n`;T(n,i,{mode:384,flag:`wx`}),e=$({path:n,characters:i.length,records:1})}w.stdout.write(`${JSON.stringify({...r.value,...e!==null&&{detail:e}})}\n`);return}Kr(Gr(e))},ni=e=>{w.stderr.write(`${JSON.stringify(e)}\n`)},ri=(e,t,n=`enhance`)=>{let r=e,i=E.join(t,`sensitive`);return Jr(i),{result:e=>{ti(g(e,n),i)},failure:e=>{ni(be(e,n))},logger:{info:(...e)=>{ti(g(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(g(e.map(String).join(``),n)),i=ei(t);i===null?r.pendingParserMessage=t:ni(i)}}}};(async()=>{let e={exitCode:1,pendingParserMessage:null},t=ri(e,x.configDirectory,x.commandName),n=Ne(x.configDirectory),r=Fe(),i=Hr({version:`0.1.
|
|
23
|
+
`)}\n`;Q(t);let i=E.join(t,`result-${D()}.ndjson`);T(i,r,{mode:384,flag:`wx`}),w.stdout.write(`${JSON.stringify($({path:i,characters:r.length,records:n.length,reason:`signed-url`}))}\n`)},Xr=e=>X(e)?typeof e.token==`string`?{field:`token`,value:e.token}:typeof e.acceptToken==`string`?{field:`acceptToken`,value:e.acceptToken}:null:null,Zr=(e,t,n)=>{let r=`${t.value}\n`;Q(n);let i=E.join(n,`result-${D()}.token`);T(i,r,{mode:384,flag:`wx`});let a=Object.fromEntries(Object.entries(e).filter(([e])=>e!==t.field));w.stdout.write(`${JSON.stringify({...a,secret:$({path:i,field:t.field,characters:r.length})})}\n`)},Qr=e=>e.includes(`Usage:`)||e.includes(`Options:`)||e.includes(`Commands:`),$r=te.omit({fields:!0}).extend({remediation:C.string(),fields:C.array(C.object({path:C.string(),message:C.string()})).optional()}),ei=e=>{try{let t=JSON.parse(e),n=$r.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}},ti=(e,t)=>{if(typeof e==`string`&&Qr(e)){w.stdout.write(e);return}let n=Xr(e);if(n!==null&&X(e)){Zr(e,n,t);return}if(Z(e)){Yr(e,t);return}let r=fe(e);if(r!==null){let e=null;if(r.detail!==null){Q(t);let n=E.join(t,`result-${D()}.ndjson`),i=`${JSON.stringify(r.detail)}\n`;T(n,i,{mode:384,flag:`wx`}),e=$({path:n,characters:i.length,records:1})}w.stdout.write(`${JSON.stringify({...r.value,...e!==null&&{detail:e}})}\n`);return}Kr(Gr(e))},ni=e=>{w.stderr.write(`${JSON.stringify(e)}\n`)},ri=(e,t,n=`enhance`)=>{let r=e,i=E.join(t,`sensitive`);return Jr(i),{result:e=>{ti(g(e,n),i)},failure:e=>{ni(be(e,n))},logger:{info:(...e)=>{ti(g(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(g(e.map(String).join(``),n)),i=ei(t);i===null?r.pendingParserMessage=t:ni(i)}}}};(async()=>{let e={exitCode:1,pendingParserMessage:null},t=ri(e,x.configDirectory,x.commandName),n=Ne(x.configDirectory),r=Fe(),i=Hr({version:`0.1.16-dev.sha-342a11e485fa`,credentials:n,remote:Ae(x.apiUrl,n,r),mutationKey:r,output:t,state:e,configDirectory:x.configDirectory,commandName:x.commandName});try{await i.run()}catch(n){n instanceof v&&Ur(n.requestedCode===0?0:e.exitCode),t.failure(_(n,null)),Ur(1)}})();export{};
|
package/dist/mcp-main.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{d as e,m as t,o as n}from"./cli-output-identity.lib-DiyUPF-a.mjs";import{a as r,i,m as a,n as o,o as s,r as c,t as l}from"./mutation-key.adapter-DSHM0rrk.mjs";import{t as u}from"./mcp-server.adapter-
|
|
2
|
+
import{d as e,m as t,o as n}from"./cli-output-identity.lib-DiyUPF-a.mjs";import{a as r,i,m as a,n as o,o as s,r as c,t as l}from"./mutation-key.adapter-DSHM0rrk.mjs";import{t as u}from"./mcp-server.adapter-Dgdzx7ky.mjs";import{z as d}from"zod";import f from"node:process";import{serveStdio as p}from"@modelcontextprotocol/server/stdio";const m=d.object({openBrowser:d.boolean()}),h=(e,t)=>{let i=a(e,t,r(t)),o=null,s=null;return{login:async e=>{if(o!==null)return o.ready;let t=m.parse(e),r=new AbortController,a=Promise.withResolvers();s=null;let c=(async()=>{try{await i.loginWithBrowser({label:`Agent plugin`,openBrowser:t.openBrowser,signal:r.signal,onReady:e=>{s={authenticated:!1,status:`waiting_for_browser`,url:e},a.resolve(s)}}),s=null}catch(e){s={authenticated:!1,status:`failed`,error:n(e,null)},a.reject(e)}finally{o=null}})();return o={controller:r,ready:a.promise,completion:c},a.promise},status:async()=>s===null?await e.read()===null?{authenticated:!1}:i.status():s,logout:async()=>(o?.controller.abort(),await o?.completion,s=null,i.logout())}},g=new Set([`auth.login`,`auth.logout`,`auth.status`,`doctor`]),_=async e=>{switch(e.capability){case`auth.login`:return e.auth.login(e.arguments);case`auth.logout`:return e.auth.logout();case`auth.status`:return e.auth.status();case`doctor`:{let[t,n]=await Promise.all([e.remote.health(),e.credentials.read()]);return{status:n!==null&&t.reachable?`ok`:`degraded`,runtimeVersion:e.version,api:{reachable:t.reachable,status:t.status,...t.error!==void 0&&{error:t.error}},credential:{present:n!==null}}}default:throw TypeError(`${e.capability} has no MCP transport execution`)}},v=(e,t,n,r)=>{let i=o(e,t,l()),a=h(t,i);return{invoke:async c=>{if(g.has(c.capability.id))return _({capability:c.capability.id,arguments:c.arguments,credentials:t,remote:i,version:r,auth:a});let u=l();return s({remote:o(e,t,u),mutationKey:u,configDirectory:n}).invoke(c)}}},y=d.object({authenticated:d.literal(!1)}),b=d.object({authenticated:d.literal(!1),status:d.literal(`waiting_for_browser`),url:d.url()}),x=d.object({authenticated:d.literal(!1),status:d.literal(`failed`),error:d.object({code:d.string(),message:d.string(),remediation:d.string()})}),S=d.object({authenticated:d.literal(!0),personId:d.uuid(),displayName:d.string().min(1),tokenId:d.uuid(),tokenLabel:d.string().min(1),expiresAt:d.iso.datetime().nullable()}),C=d.object({openBrowser:d.boolean().default(!0).describe(`Open the system browser for human sign-in; return its URL immediately.`)}),w=d.strictObject({}),T=d.union([b,x,y,S]),E=d.object({loggedOut:d.boolean()}),D=d.object({status:d.enum([`ok`,`degraded`]),runtimeVersion:d.string().min(1),api:d.object({reachable:d.boolean(),status:d.number().int().nullable(),error:d.string().optional()}),credential:d.object({present:d.boolean()})}),O=e=>({summary:e.summary,useWhen:e.useWhen,preconditions:[`Run through the local Enhance MCP runtime, which owns the user-scoped credential.`,`Keep credential values outside model-visible input and output.`],input:[],output:[],result:e.result,recovery:[`BAD_REQUEST: correct the named option and call again.`,`UNAUTHORIZED: start browser sign-in and let the person complete consent.`,`FORBIDDEN: leave the credential unchanged and report the governing account policy.`,`INTERNAL: call doctor, report the failing boundary, and stop repeating the call.`],next:e.next,examples:[{input:e.exampleInput,output:e.exampleOutput}]}),k=e=>t({...e,source:`composite`,idempotency:e.operation===`query`?`none`:`single`,execution:{kind:`composite`,procedures:[]},meta:{description:e.guide.summary},policy:{exposure:`mcp-transport`,reason:`The local MCP runtime owns its own authentication and installation diagnostics.`,owner:`mcp`},cliPath:null,inputExample:e.guide.examples[0]?.input,outputExample:e.guide.examples[0]?.output}),A=[k({id:`auth.login`,operation:`mutation`,effect:`external`,inputSchema:C,outputSchema:b,guide:O({summary:`Open browser sign-in and store a revocable user-scoped Enhance credential.`,useWhen:`Use when Enhance is not authenticated or its credential was revoked.`,result:`Returns waiting_for_browser and the exact sign-in URL immediately. Show this URL to the person if their browser restores another page. Consent continues in the background; auth.status reports completion or a failure.`,next:[`Show the sign-in URL, then check auth.status after the person finishes. Only report success after authenticated is true and a canvas read succeeds.`],exampleInput:{openBrowser:!0},exampleOutput:{authenticated:!1,status:`waiting_for_browser`,url:`https://app.example.test/oauth/authorize?client_id=client_enhance_cli`}})}),k({id:`auth.logout`,operation:`mutation`,effect:`delete`,inputSchema:w,outputSchema:E,guide:O({summary:`Remove the user-scoped local Enhance credential.`,useWhen:`Use only when the person asks to disconnect this local agent host.`,result:`Reports whether a local credential was removed without returning its value.`,next:[`Call auth.status to confirm the local runtime is disconnected.`],exampleInput:{},exampleOutput:{loggedOut:!0}})}),k({id:`auth.status`,operation:`query`,effect:`read`,inputSchema:w,outputSchema:T,guide:O({summary:`Check whether the local Enhance MCP runtime is authenticated.`,useWhen:`Use before a workflow or after login, logout, expiry, or an authorization failure.`,result:`Returns safe identity metadata, a pending sign-in URL, a sign-in failure, or authenticated false; never a credential value.`,next:[`While waiting_for_browser, show the URL and let the person finish. After failure, report the error before retrying auth.login. Continue the workflow only when authenticated is true.`],exampleInput:{},exampleOutput:{authenticated:!1}})}),k({id:`doctor`,operation:`query`,effect:`read`,inputSchema:w,outputSchema:D,guide:O({summary:`Check MCP runtime identity, API reachability, and credential presence without changes.`,useWhen:`Use after repeated connection, authentication, or compatibility failure.`,result:`Returns bounded diagnostics without machine paths, credentials, or customer data.`,next:[`Follow the failing boundary; do not repeat a mutation while diagnostics are degraded.`],exampleInput:{},exampleOutput:{status:`ok`,runtimeVersion:`0.1.16`,api:{reachable:!0,status:200},credential:{present:!0}}})})].toSorted((e,t)=>e.id.localeCompare(t.id)),j=()=>A,M=c(i.configDirectory),N=v(i.apiUrl,M,i.configDirectory,`0.1.16-dev.sha-342a11e485fa`),P=[...e(),...j()];p(()=>u({version:`0.1.16-dev.sha-342a11e485fa`,name:i.mcpServiceName,commandName:i.commandName,invocation:N,catalog:P,exposures:[`shared`,`mcp-transport`]}),{legacy:`serve`,onerror:()=>f.stderr.write(`${i.mcpServiceName} transport failure\n`)});export{};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{A as e,E as t,M as n,d as r,ht as i,i as a,l as o,lt as s,mt as c,n as l,o as u,r as d,s as f,t as p,w as m,xt as h,y as ee}from"./cli-output-identity.lib-DiyUPF-a.mjs";import{z as g}from"zod";import{createHash as _,randomUUID as v}from"node:crypto";import{readFile as y,rm as b}from"node:fs/promises";import{McpServer as x}from"@modelcontextprotocol/server";const S=g.object({ok:g.literal(!1),error:g.object({code:g.string(),message:g.string(),remediation:g.string(),fields:g.array(g.object({path:g.string(),message:g.string()})).optional()})}),C=g.object({uri:g.string(),mimeType:g.string(),bytes:g.number().int().nonnegative()}),te=g.object({ok:g.literal(!0),artifact:C}),w=g.object({id:g.string(),operation:g.enum([`query`,`mutation`]),effect:g.enum([`read`,`write`,`delete`,`external`]),idempotency:g.enum([`none`,`single`,`composite`]),summary:g.string(),useWhen:g.string(),preconditions:g.array(g.string()),inputSchema:g.unknown(),exampleInput:g.unknown(),output:g.array(g.object({name:g.string(),required:g.boolean(),meaning:g.string()})),result:g.string(),recovery:g.array(g.string()),next:g.array(g.string()),schemaDigest:g.string(),guidanceDigest:g.string(),behaviorDigest:g.string()}),T=w.pick({id:!0,operation:!0,effect:!0,summary:!0,useWhen:!0}),E=g.union([g.object({ok:g.literal(!0),result:g.unknown(),artifact:C.optional(),detail:C.optional()}),te,S]),D=g.union([g.object({ok:g.literal(!0),result:g.object({matches:g.array(T),totalMatches:g.number().int().nonnegative(),truncated:g.boolean(),bestContract:w.optional(),detailRequired:g.object({capability:g.string()}).optional()})}),S]),O=g.union([g.object({ok:g.literal(!0),result:w}),S]),k=g.uuid().optional().describe(`Reuse only when retrying this exact mutation.`),A=ee.pick({baseVersion:!0,targetNodeId:!0,html:!0,idPrefix:!0}).extend({canvas:g.string().min(1).describe(`Canvas UUID or complete canvas/selection URL. Preserve a supplied selection URL.`),mode:g.enum([`insert-children`,`replace`]).default(`insert-children`),clientToken:k}),j=m.extend({clientToken:k}),M=g.object({canvas:g.string().min(1),expectedVersion:g.number().int().positive().describe(`Version returned by the latest successful read or write.`),target:i.default({kind:`content`}),sourceState:c.nullable().default(null),scale:g.number().min(.1).max(4).default(1)}),N=async(e,t,n,r=null)=>{let i=e.catalog.find(e=>e.id===t);if(i===void 0)throw TypeError(`Missing canvas capability ${t}`);return e.invocation.invoke({capability:i,arguments:n,clientToken:r})},P=async(r,i)=>{let a=e(i.canvas);if(a.nodeIds.length===0)return{canvasId:a.canvasId,target:i.target};let o=i.target.kind===`node`?i.target.nodeId:i.target.kind===`content`&&a.nodeIds.length===1?a.nodeIds[0]:void 0;if(o===void 0)throw new n(`BAD_REQUEST`,`A selection link requires one selected node to render.`,`Choose a node target inside the selection; bounds or whole-canvas renders can include unrelated content.`);let c=s.parse(await N(r,`canvas.document.get`,{canvasId:a.canvasId}));if(c.version!==i.expectedVersion)throw new n(`CONFLICT`,`The canvas changed before rendering.`,`Read the selected subtree and render its current version.`);return t(a,h.parse(c.document),[o]),{canvasId:a.canvasId,target:{kind:`node`,nodeId:o}}},F=async(e,t,n)=>{try{return await t.results.success(e,await n(),t.delivery)}catch(e){return t.results.failure(e)}},I=(t,n)=>{n.catalog.some(e=>e.id===`canvas.writeHtml`)&&t.registerTool(`canvas_write_html`,{title:`Design editable canvas content`,description:`Create a populated screen or visual group from safe HTML/CSS. Returns the committed version and root node without an extra read or render. If starting state is unknown, call capability_query with {"capability":"canvas.inspect","input":{"canvasId":"<UUID from canvas URL>"}}. When nodeCount is 0, use targetNodeId "root" and the returned version. Use flex, padding, gap, concrete inline CSS and layer-name. Give important rows/cards/buttons explicit dimensions; avoid implicit stretch, margins, grid, tables and inline badge backgrounds.
|
|
2
|
+
import{A as e,E as t,M as n,d as r,ht as i,i as a,l as o,lt as s,mt as c,n as l,o as u,r as d,s as f,t as p,w as m,xt as h,y as ee}from"./cli-output-identity.lib-DiyUPF-a.mjs";import{z as g}from"zod";import{createHash as _,randomUUID as v}from"node:crypto";import{readFile as y,rm as b}from"node:fs/promises";import{McpServer as x}from"@modelcontextprotocol/server";const S=g.object({ok:g.literal(!1),error:g.object({code:g.string(),message:g.string(),remediation:g.string(),fields:g.array(g.object({path:g.string(),message:g.string()})).optional()})}),C=g.object({uri:g.string(),mimeType:g.string(),bytes:g.number().int().nonnegative()}),te=g.object({ok:g.literal(!0),artifact:C}),w=g.object({id:g.string(),operation:g.enum([`query`,`mutation`]),effect:g.enum([`read`,`write`,`delete`,`external`]),idempotency:g.enum([`none`,`single`,`composite`]),summary:g.string(),useWhen:g.string(),preconditions:g.array(g.string()),inputSchema:g.unknown(),exampleInput:g.unknown(),output:g.array(g.object({name:g.string(),required:g.boolean(),meaning:g.string()})),result:g.string(),recovery:g.array(g.string()),next:g.array(g.string()),schemaDigest:g.string(),guidanceDigest:g.string(),behaviorDigest:g.string()}),T=w.pick({id:!0,operation:!0,effect:!0,summary:!0,useWhen:!0}),E=g.union([g.object({ok:g.literal(!0),result:g.unknown(),artifact:C.optional(),detail:C.optional()}),te,S]),D=g.union([g.object({ok:g.literal(!0),result:g.object({matches:g.array(T),totalMatches:g.number().int().nonnegative(),truncated:g.boolean(),bestContract:w.optional(),detailRequired:g.object({capability:g.string()}).optional()})}),S]),O=g.union([g.object({ok:g.literal(!0),result:w}),S]),k=g.uuid().optional().describe(`Reuse only when retrying this exact mutation.`),A=ee.pick({baseVersion:!0,targetNodeId:!0,html:!0,idPrefix:!0}).extend({canvas:g.string().min(1).describe(`Canvas UUID or complete canvas/selection URL. Preserve a supplied selection URL.`),mode:g.enum([`insert-children`,`replace`]).default(`insert-children`),clientToken:k}),j=m.extend({clientToken:k}),M=g.object({canvas:g.string().min(1),expectedVersion:g.number().int().positive().describe(`Version returned by the latest successful read or write.`),target:i.default({kind:`content`}),sourceState:c.nullable().default(null),scale:g.number().min(.1).max(4).default(1)}),N=async(e,t,n,r=null)=>{let i=e.catalog.find(e=>e.id===t);if(i===void 0)throw TypeError(`Missing canvas capability ${t}`);return e.invocation.invoke({capability:i,arguments:n,clientToken:r})},P=async(r,i)=>{let a=e(i.canvas);if(a.nodeIds.length===0)return{canvasId:a.canvasId,target:i.target};let o=i.target.kind===`node`?i.target.nodeId:i.target.kind===`content`&&a.nodeIds.length===1?a.nodeIds[0]:void 0;if(o===void 0)throw new n(`BAD_REQUEST`,`A selection link requires one selected node to render.`,`Choose a node target inside the selection; bounds or whole-canvas renders can include unrelated content.`);let c=s.parse(await N(r,`canvas.document.get`,{canvasId:a.canvasId}));if(c.version!==i.expectedVersion)throw new n(`CONFLICT`,`The canvas changed before rendering.`,`Read the selected subtree and render its current version.`);return t(a,h.parse(c.document),[o]),{canvasId:a.canvasId,target:{kind:`node`,nodeId:o}}},F=async(e,t,n)=>{try{return await t.results.success(e,await n(),t.delivery)}catch(e){return t.results.failure(e)}},I=(t,n)=>{n.catalog.some(e=>e.id===`canvas.writeHtml`)&&t.registerTool(`canvas_write_html`,{title:`Design editable canvas content`,description:`Create a populated screen or visual group from safe HTML/CSS. For multiple screens, publish the first populated screen before authoring the next, then publish each subsequent screen separately so the user can see and steer progress. Prepare only what that screen needs; do not prepare the whole set before the first write. Returns the committed version and root node without an extra read or render. If starting state is unknown, call capability_query with {"capability":"canvas.inspect","input":{"canvasId":"<UUID from canvas URL>"}}. When nodeCount is 0, use targetNodeId "root" and the returned version. Use flex, padding, gap, concrete inline CSS and layer-name. Give important rows/cards/buttons explicit dimensions; avoid implicit stretch, margins, grid, tables and inline badge backgrounds. Include real content, not an empty shell. Reuse a returned version for subsequent edits; read a targeted subtree only when its ids or structure are unknown. Use canvas_edit for small changes, then canvas_render once at a useful review point. The schema here is executable; no search or describe is required.`,inputSchema:A,outputSchema:E,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},async({canvas:r,clientToken:i,...a})=>F(t,n,async()=>{let t=e(r);return N(n,`canvas.writeHtml`,{...a,canvasId:t.canvasId,...t.nodeIds.length>0&&{selectionNodeIds:t.nodeIds},review:`none`,renderOutputPath:null,overwriteRender:!1,renderScale:1,renderTimeoutMs:12e4},i??null)}))},L=(e,t)=>{t.catalog.some(e=>e.id===`canvas.edit`)&&e.registerTool(`canvas_edit`,{title:`Edit existing canvas content`,description:`Apply text, styles, rename, duplicate or move edits together in one atomic mutation. Use ids from the input version and the latest successful read or write version; no intermediate read is required just to advance a version. Keep the complete selection URL. Read only the missing subtree when ids are unknown. Returns a compact committed receipt; render after the requested changes are complete.`,inputSchema:j,outputSchema:E,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},async({clientToken:n,...r})=>F(e,t,async()=>N(t,`canvas.edit`,r,n??null)))},R=(e,t)=>{t.catalog.some(e=>e.id===`canvas.render`)&&e.registerTool(`canvas_render`,{title:`Review canvas pixels`,description:`Render the version returned by a successful read or write and inspect its native PNG. Target the affected screen/node; a blank canvas does not need a pre-render. For a selection link use one node inside the selection. Review after a meaningful visual change, and repeat only after further changes or a real discrepancy.`,inputSchema:M,outputSchema:E,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async n=>F(e,t,async()=>N(t,`canvas.render`,{...await P(t,n),expectedVersion:n.expectedVersion,sourceState:n.sourceState,scale:n.scale,outputPath:null,overwrite:!1,timeoutMs:12e4})))},z=e=>({register:t=>{I(t,e),L(t,e),R(t,e)}}),B=e=>e.replaceAll(/\s+/gu,` `).trim(),ne=e=>{let t=`${e.id} [${e.effect}] — `,n=B(e.guide.summary),r=180-t.length;return`${t}${n.slice(0,r)}`},V=(e,t)=>{let n=e.toSorted((e,t)=>e.id.localeCompare(t.id)).map(e=>ne(e)),r=_(`sha256`).update(n.join(`
|
|
3
3
|
`)).digest(`hex`),i=[`Enhance MCP ${t} — ${String(n.length)} capabilities — sha256:${r}`,...n].join(`
|
|
4
4
|
`);if(Buffer.byteLength(i)>24576)throw RangeError(`the complete capability catalogue exceeds 24 KiB`);return{digest:r,text:i}},H=(e,t,n=`enhance`)=>{let r=V(e,t),i=String(l(r.text,n));return{register:t=>{t.registerTool(`capability_catalogue`,{title:`Scan every Enhance capability`,description:`Return the complete bounded capability inventory when the task is broad, uncertain, or capability_search does not find the right words. Call capability_describe with one exact id before invoking it.`,inputSchema:g.strictObject({}),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":e.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":e.length}},()=>({content:[{type:`text`,text:i}]}))}}},U=g.object({capability:g.string().min(1).describe(`Exact capability id returned by capability_search or capability_catalogue.`)}),W=(e,t)=>({register: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:U,outputSchema:O,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},({capability:r})=>{let i=e.describe(r);return i===null?t.failure(new n(`BAD_REQUEST`,`Unknown shared capability: ${r}.`,`Call capability_search or capability_catalogue and use an exact id from its results.`,{capability:`No shared capability has this id.`})):t.inline(i)})}}),G=/(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu,K=/[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu,q=e=>JSON.stringify(e),J=(e,t=``)=>typeof e==`string`?K.test(e)||G.test(t)&&!t.endsWith(`Id`):Array.isArray(e)?e.some(e=>J(e,t)):typeof e!=`object`||!e?!1:Reflect.get(e,`sensitive`)===!0||Object.entries(e).some(([e,t])=>J(t,e)),Y=async(e,t,n)=>{let r=await y(t.path),i=v(),a=`enhance://artifact/${i}`;if(n===`embedded`&&t.cleanup===`unlink-after-use`)try{await b(t.path,{force:!0})}catch{}return n===`linked`&&e.registerResource(`artifact-${i}`,a,{title:`Enhance artifact`,mimeType:t.contentType},e=>({contents:[{uri:e.href,mimeType:t.contentType,blob:r.toString(`base64`)}]})),{metadata:d.omit({path:!0,sensitive:!0,cleanup:!0,deleteAfter:!0}).parse(t),artifact:{uri:a,mimeType:t.contentType,bytes:r.byteLength},image:{type:`image`,data:r.toString(`base64`),mimeType:t.contentType}}},X=(e,t,n)=>{let r=v(),i=`enhance://result/${r}`,a=Buffer.byteLength(t);if(n===`embedded`){let e={ok:!0,artifact:{uri:i,mimeType:`application/json`,bytes:a}};return{content:[{type:`text`,text:q(e)},{type:`resource`,resource:{uri:i,mimeType:`application/json`,text:t}}],structuredContent:e}}e.registerResource(`result-${r}`,i,{title:`Protected Enhance result`,mimeType:`application/json`},e=>({contents:[{uri:e.href,mimeType:`application/json`,text:t}]}));let o={ok:!0,artifact:{uri:i,mimeType:`application/json`,bytes:a}};return{content:[{type:`text`,text:q(o)},{type:`resource_link`,name:`Protected Enhance result`,uri:i,mimeType:`application/json`}],structuredContent:o}},Z=e=>new n(`BAD_REQUEST`,`Input validation error.`,`Correct the rejected fields using this tool’s schema, then retry. Describe the exact capability only if its contract is unknown.`,Object.fromEntries(e.issues.map(e=>[e.path.length===0?`input`:e.path.join(`.`),e.message]))),re=async(e,t,n)=>{let r=d.safeParse(t);if(r.success){let t=await Y(e,r.data,n);return{value:t.metadata,detail:null,attachment:t}}let i=a(t);if(i===null)return{value:t,detail:null,attachment:null};let o=i.detail??i.value,s=d.safeParse(o.review);if(!s.success)return{...i,attachment:null};try{let t=await Y(e,s.data,n),r={...o,review:{...t.metadata,artifact:t.artifact}},i=a(r);return{value:i?.value??r,detail:i?.detail??null,attachment:t}}catch{let e={...o,review:{state:`unavailable`,mutationCommitted:!0,requestedVersion:o.version,retry:{tool:`canvas_render`,arguments:{canvas:o.canvasId,expectedVersion:o.version,target:s.data.target}}},next:[`Retry the render of the committed version; do not replay the write.`]},t=a(e);return{value:t?.value??e,detail:t?.detail??null,attachment:null}}},ie=(e,t)=>{let n={ok:!0,result:l(e,t)};return{content:[{type:`text`,text:q(n)}],structuredContent:n}},ae=(e,t=`enhance`)=>({success:async(e,n,r)=>{let i=l(n,t),a=await re(e,i,r),o=a.attachment,s=q(a.value);if(J(a.value)||o===null&&a.detail===null&&Buffer.byteLength(s)>2e4)return X(e,s,r);let c=a.detail===null?null:X(e,q(a.detail),r),u={ok:!0,result:a.value,...o!==null&&{artifact:o.artifact},...c!==null&&{detail:c.structuredContent.artifact}};return{content:[{type:`text`,text:q(u)},...o===null?[]:[o.image],...c?.content.filter(e=>e.type!==`text`)??[]],structuredContent:u}},inline:e=>ie(e,t),failure:n=>{let r=p(u(n instanceof g.ZodError?Z(n):n,null),t),i={ok:!1,error:r.code===`UNAUTHORIZED`?{...r,remediation:e}:r};return{content:[{type:`text`,text:q(i)}],structuredContent:i,isError:!0}}}),oe=g.object({query:g.string().trim().min(1).max(200).describe(`Plain-language task, domain, or exact capability id to discover.`),operation:g.enum([`any`,`query`,`mutation`]).default(`any`).describe(`Filter dispatch, not effect. Omit if unknown; render uses mutation.`),limit:g.number().int().min(1).max(10).default(5).describe(`Maximum contracts to return.`)}),se=g.object({capability:g.string().min(1).describe(`Exact query id from an available complete contract.`),input:g.record(g.string(),g.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`)}),Q=g.object({capability:g.string().min(1).describe(`Exact mutation id from an available complete contract.`),input:g.record(g.string(),g.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`),clientToken:g.uuid().optional().describe(`Stable UUID reused only when retrying this exact mutation input.`)}),$=(e,t,r)=>{let i=e.find(e=>e.id===t);if(i===void 0)throw new n(`BAD_REQUEST`,`Unknown shared capability: ${t}.`,`Call capability_search or capability_catalogue and use an exact id from its results.`,{capability:`No shared capability has this id.`});if(i.operation!==r){let e=i.operation===`query`?`capability_query`:`capability_mutate`;throw new n(`BAD_REQUEST`,`${t} is a ${i.operation}, not a ${r}.`,`Call ${e} with the same capability and input.`,{capability:`Use ${e} for this capability.`})}return i},ce=(e,t,n,r)=>{e.registerTool(`capability_search`,{title:`Discover Enhance capabilities`,description:`Search the Enhance capability catalogue for a specific likely action. Returns relevant summaries and a complete bestContract when it fits. Invoke from that contract directly; call capability_describe only when detailRequired is returned or a different match is needed.`,inputSchema:oe,outputSchema:D,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":t.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":t.length}},async({query:e,operation:t,limit:i})=>r.inline(n.search({query:e,operation:t,limit:i})))},le=(e,t,n,r)=>{e.registerTool(`capability_query`,{title:`Run a discovered Enhance query`,description:`Run one read-only capability using an available complete contract. Search or describe only when the contract is missing.`,inputSchema:se,outputSchema:E,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a})=>{try{return await r.results.success(e,await n.invoke({capability:$(t,i,`query`),arguments:a,clientToken:null}),r.delivery)}catch(e){return r.results.failure(e)}})},ue=(e,t,n,r)=>{e.registerTool(`capability_mutate`,{title:`Run a discovered Enhance mutation`,description:`Run one state-changing capability using an available complete contract. Respect its preconditions and reuse clientToken only when retrying the identical mutation.`,inputSchema:Q,outputSchema:E,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a,clientToken:o})=>{try{return await r.results.success(e,await n.invoke({capability:$(t,i,`mutation`),arguments:a,clientToken:o??null}),r.delivery)}catch(e){return r.results.failure(e)}})},de=e=>{let t=new x({name:e.name??`enhance-mcp`,version:e.version},{capabilities:{tools:{listChanged:!1},resources:{listChanged:!0}},...e.exposures?.includes(`mcp-transport`)===!0&&{instructions:`Transport attachment is not Enhance sign-in, even when the host reports mcp_auth success. Use capability_query with capability auth.status to check the person. If authenticated is false or a read returns UNAUTHORIZED, use capability_mutate with capability auth.login and input {"openBrowser":true}, then show the returned sign-in URL and let the person complete browser sign-in. If their browser restores a canvas or another page, direct them to this exact URL. A waiting_for_browser result is pending, not authenticated. Verify auth.status and a read such as canvas.list before reporting setup complete.`}}),n=f(e.catalog??r(),e.exposures??[`shared`]),i=o(n),a=e.delivery??`linked`,s=ae(e.exposures?.includes(`mcp-transport`)===!0?`Call capability_mutate with capability auth.login and input {"openBrowser":true}. Show the returned sign-in URL, complete browser sign-in, then verify auth.status and a read such as canvas.list.`:`Reconnect this hosted MCP server through your host’s browser OAuth sign-in. Then verify person.me and a read such as canvas.list.`,e.commandName);H(n,e.version,e.commandName).register(t),ce(t,n,i,s),W(i,s).register(t);let c={delivery:a,results:s};return le(t,n,e.invocation,c),ue(t,n,e.invocation,c),z({catalog:n,invocation:e.invocation,...c}).register(t),t};export{de as t};
|
package/dist/mcp.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as e,d as t}from"./cli-output-identity.lib-DiyUPF-a.mjs";import{t as n}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{t as r}from"./mcp-server.adapter-
|
|
2
|
+
import{c as e,d as t}from"./cli-output-identity.lib-DiyUPF-a.mjs";import{t as n}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{t as r}from"./mcp-server.adapter-Dgdzx7ky.mjs";export{t as createCapabilityCatalogAdapter,r as createEnhanceMcpServer,n as toCapabilityInventory,e as toSharedCapabilities};
|