pixie-mcp 0.7.5 → 0.7.7

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/pixie-mcp.mjs +15 -11
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pixie-mcp",
3
- "version": "0.7.5",
3
+ "version": "0.7.7",
4
4
  "description": "MCP server for interacting with the Pixie API. Inspired by Aseprite's API and MCP server.",
5
5
  "type": "module",
6
6
  "bin": {
package/pixie-mcp.mjs CHANGED
@@ -1,13 +1,17 @@
1
1
  #!/usr/bin/env node
2
- var W=(r,e)=>()=>(r&&(e=r(r=0)),e);function st(r){let e="";for(let t=0;t<r.length;t+=32768)e+=String.fromCharCode.apply(null,r.subarray(t,t+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var it=W(()=>{"use strict"});var K,nn,rn,Nr,at=W(()=>{"use strict";K="[A-Za-z0-9_-]{1,64}",nn="token|members|link|slow|suggest|project",rn=[{owner:"accounts",re:new RegExp("^/auth/")},{owner:"accounts",re:new RegExp("^/a/[A-Za-z0-9_-]{1,64}\\.png$")},{owner:"accounts",re:new RegExp("^/projects(/|$)")},{owner:"accounts",re:new RegExp(`^/documents/${K}/(${nn})$`)},{owner:"library",re:new RegExp("^/documents$")},{owner:"library",re:new RegExp("^/documents/(new|register|move|order|folders|folders/delete|trash|trash/empty)$")},{owner:"library",re:new RegExp(`^/documents/${K}(/(thumbnail\\.png|export|duplicate|rename|restore))?$`)},{owner:"library",re:new RegExp(`^/documents/${K}/history/at/\\d+/thumbnail\\.png$`)},{owner:"library",re:new RegExp("^/wall\\.png$")},{owner:"document",re:new RegExp(`^/documents/${K}/history(/at/\\d+|/\\d+|/source(/[A-Za-z0-9_-]{1,64})?)?$`)},{owner:"document",re:new RegExp(`^/documents/${K}/comments(/[A-Za-z0-9]{1,40})?$`)},{owner:"document",re:new RegExp(`^/documents/${K}/snapshots(/enabled|/[A-Za-z0-9_-]{1,128})?$`)},{owner:"document",re:new RegExp(`^/favourites(/order|/(document|project)/${K})?$`)}],Nr=rn.map(({owner:r,re:e})=>({owner:r,source:e.source}))});var Oe,Ne=W(()=>{"use strict";at();Oe=["read","draw","create","duplicate","organize"]});async function ct(r){let e=new TextEncoder().encode(String(r));return st(new Uint8Array(await crypto.subtle.digest("SHA-256",e)))}var Fr,ht=W(()=>{"use strict";it();Ne();Fr=120*1e3});function I(r=Date.now()){let e="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t=(BigInt(r)&0xffffffffffffn)<<80n,n=crypto.getRandomValues(new Uint8Array(10)),o=0n;for(let i of n)o=o<<8n|BigInt(i);t|=o;let s="";for(let i=0;i<26;i++)s=e[Number(t&31n)]+s,t>>=5n;return s}function q(r){return r==null?{at:0}:typeof r=="number"?{at:r}:{frame:r}}var un,dn,pn,me,Q,Me,se=W(()=>{"use strict";un=new TextEncoder,dn=new TextDecoder,pn=1;me=class r{#e;#r;constructor(e){this.#e=e,this.#r=e.exports}static async load(e){let t;if(e instanceof WebAssembly.Module)t=await WebAssembly.instantiate(e,{});else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))({instance:t}=await WebAssembly.instantiate(e,{}));else{let n=e instanceof Response||typeof e?.then=="function"?e:fetch(e);({instance:t}=await WebAssembly.instantiateStreaming(n,{}))}return new r(t)}get#o(){return new Uint8Array(this.#r.memory.buffer)}call(e,t={}){let n=un.encode(JSON.stringify({m:e,a:t})),o=this.#r.sprite_alloc(n.length);if(!o)throw new Error("sprite-core: allocation failed");let s=0;try{if(this.#o.set(n,o),s=this.#r.sprite_dispatch(o,n.length),!s)throw new Error("sprite-core: dispatch returned nothing");let i=this.#o,a=i[s]|i[s+1]<<8|i[s+2]<<16|i[s+3]<<24,c=i[s+4],h=i.slice(s+5,s+5+a);if(c===pn)return h;let l=JSON.parse(dn.decode(h));if(l&&l.error)throw new Error(l.error);return l}finally{s?this.#r.sprite_free_result(s):this.#r.sprite_dealloc(o,n.length)}}reset(){this.#r.sprite_reset()}newDocument(e={}){return this.call("doc.new",{w:32,h:32,name:"untitled",...e})}decodePng(e){let t=this.call("image.decode",{png:[...e]}),n=new DataView(t.buffer,t.byteOffset,t.byteLength),o=n.getUint32(0,!0),s=n.getUint32(4,!0);return{w:o,h:s,pixels:t.subarray(8)}}openSession(e,t,n=1){let{h:o}=this.call("session.new",{doc:e,author:t,seed:n});return new Q(this,o)}openRoom(e,{seq:t=0}={}){let{h:n}=this.call("room.new",{doc:e,...t>0?{seq:t}:{}});return new Me(this,n)}},Q=class{constructor(e,t){this.core=e,this.h=t}#e(e,t={}){return this.core.call(e,{h:this.h,...t})}state(){return this.#e("session.state")}apply(e,{now:t=Date.now(),label:n="Edit",job:o=null}={}){let s={now:t,label:n,bodies:Array.isArray(e)?e:[e]};return o&&(s.job=o),this.#e("session.apply",s).ops}remote(e){return this.#e("session.remote",{sop:e})}reject(e){return this.#e("session.reject",{op:e})}undo(e=Date.now()){return this.#e("session.undo",{now:e}).ops}redo(e=Date.now()){return this.#e("session.redo",{now:e}).ops}pending(){return this.#e("session.pending")}checkpoint({doc:e=!0}={}){return this.#e("session.checkpoint",{doc:e})}save(){return this.#e("session.save")}drawArt(e,t,n={}){return this.#e("session.drawArt",{rows:e,colors:t,...n}).bodies}drawAnimation(e,t,n={}){return this.#e("session.drawAnimation",{frames:e,colors:t,...n}).bodies}readArt(e,t,n={}){return this.#e("session.readArt",{layer:e,...q(t),...n})}cel(e,t){return this.#e("session.cel",{layer:e,...q(t)})}layerImage(e,t){return this.#e("session.layerImage",{layer:e,...q(t)})}tileCel(e,t){return this.#e("session.tileCel",{layer:e,...q(t)})}tile(e,t){return this.#e("session.tile",{tileset:e,index:t})}composite(e,{include:t="export"}={}){return this.#e("session.composite",{...q(e),include:t})}png(e,{scale:t=1,rect:n=null}={}){return this.#e("session.png",{...q(e),scale:Math.max(1,Math.round(t)||1),...n?{rect:n}:{}})}contactSheet({columns:e=4,scale:t=2}={}){return this.#e("session.sheet",{columns:e,scale:t})}thumbnail(e=48){return this.#e("session.thumbnail",{size:e})}card({frame:e=null,width:t=1200,height:n=630,framing:o=null,bleed:s=0,raw:i=!1}={}){return this.#e("session.card",{width:t,height:n,...o??{},...q(e),...s?{bleed:s}:{},...i?{raw:i}:{}})}cardLayout({frame:e=null,width:t=1200,height:n=630,framing:o=null}={}){return this.#e("session.cardLayout",{width:t,height:n,...o??{},...q(e)})}fit({width:e,height:t,margin:n=0,inscribed:o=!1,dx:s=0,dy:i=0,frame:a=null}){return this.#e("session.fit",{width:e,height:t,margin:n,inscribed:o,dx:s,dy:i,...q(a)})}close(){this.#e("session.free")}},Me=class{constructor(e,t){this.core=e,this.h=t}#e(e,t={}){return this.core.call(e,{h:this.h,...t})}state(){return this.#e("room.state")}submit(e,t=Date.now()){return this.#e("room.submit",{op:e,now:t})}since(e){return this.#e("room.since",{seq:e})}compact(){return this.#e("room.compact")}save(){return this.#e("room.save")}lease(e,t){return this.#e("room.lease",{action:e,...t})}region(e,t,n){return this.#e("room.region",{layer:e,frame:t,rect:{x:n.x??0,y:n.y??0,w:n.w,h:n.h}})}close(){this.#e("room.free")}}});function gt(r){return JSON.stringify(r)}function bt(r){let e=r.rle instanceof Uint8Array?r.rle:null,t=new TextEncoder().encode(JSON.stringify({...r,rle:void 0}));if(t.length>fn)return null;let n=new Uint8Array(3+t.length+(e?.length??0));return n[0]=yt,n[1]=t.length&255,n[2]=t.length>>8&255,n.set(t,3),e&&n.set(e,3+t.length),n}function mn(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):null}function xt(r){if(typeof r!="string"){let e=mn(r);if(!e||e.length<3||e[0]!==yt)return null;let t=e[1]|e[2]<<8;if(e.length<3+t)return null;try{let n=JSON.parse(new TextDecoder().decode(e.subarray(3,3+t)));if(!n||typeof n.t!="string")return null;let o=e.subarray(3+t);return n.rle=o.length?Uint8Array.from(o):null,n}catch{return null}}try{let e=JSON.parse(r);return e&&typeof e.t=="string"?e:null}catch{return null}}var T,mt,P,wt,yt,fn,$t=W(()=>{"use strict";T={HELLO:"hello",SUBMIT:"submit",PRESENCE:"presence",STROKE:"stroke",LEASE:"lease",REVIEW:"review",PING:"ping",PROMPT:"prompt",ANSWER:"answer",STOP:"stop"},mt={DOCUMENT:"document",LIBRARY:"library"},P={WELCOME:"welcome",REHELLO:"rehello",OPS:"ops",REJECT:"reject",PRESENCE:"presence",STROKE:"stroke",LEASE:"lease",INK:"ink",SUGGESTIONS:"suggestions",SUGGESTION:"suggestion",ERROR:"error",PONG:"pong",PROMPT:"prompt",ANSWER:"answer",STOP:"stop"},wt={OPS:"ops",SNAPSHOT:"snapshot"};yt=157,fn=65535});function St(r){return I().toLowerCase().slice(0,16)}var kt=W(()=>{"use strict";se()});function gn(r){let e=[];if(!r.length)return new Uint8Array;let t=r[0],n=r[1],o=r[2],s=r[3],i=0,a=()=>{let c=i;do{let h=c&127;c>>>=7,e.push(c?h|128:h)}while(c);e.push(t,n,o,s)};for(let c=0;c<r.length;c+=4)r[c]===t&&r[c+1]===n&&r[c+2]===o&&r[c+3]===s?i++:(a(),t=r[c],n=r[c+1],o=r[c+2],s=r[c+3],i=1);return a(),new Uint8Array(e)}function yn(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode.apply(null,r.subarray(n,n+32768));return btoa(e)}function bn(r){return yn(gn(r))}function vt(r,e,t,n){return{t:"paintRegion",layer:r,frame:e,rect:{x:t.x,y:t.y,w:t.w,h:t.h},rle:bn(n)}}var jt=W(()=>{"use strict"});import{readFile as mr}from"node:fs/promises";import{readFile as Jt,writeFile as Vt,mkdir as Kt,chmod as Xt}from"node:fs/promises";import{readFileSync as Zt}from"node:fs";import{homedir as Yt,hostname as Qt}from"node:os";import{join as Te}from"node:path";import{execFile as en}from"node:child_process";var E=r=>String(r??"").replace(/\/+$/,"").replace(/^ws/,"http"),Ge=r=>String(r??"").replace(/\/+$/,"").replace(/^http/,"ws");async function He(r,e){if(!r?.ok||!(r.headers.get("content-type")??"").includes("json"))return null;let t=await r.json().catch(()=>null);return!t||typeof t!="object"?null:e.some(n=>n in t)?t:null}async function Je(r,{timeoutMs:e=3e3,fetchImpl:t=fetch}={}){try{let n=await t(`${E(r)}/setup`,{signal:AbortSignal.timeout(e)});return await He(n,["accounts","expectedPort","install"])}catch{return null}}var Re=new Map;function Ve(r,{fetchImpl:e=fetch,timeoutMs:t=3e3}={}){let n=E(r);return Re.has(n)||Re.set(n,Ht(r,{fetchImpl:e,timeoutMs:t})),Re.get(n)}async function Ht(r,{fetchImpl:e,timeoutMs:t}){try{let n=await e(`${E(r)}/config.json`,{signal:AbortSignal.timeout(t)}),s=(await He(n,["rooms","accounts"]))?.rooms;if(typeof s=="string"&&/^(wss?|https?):\/\/./.test(s))return Ge(s)}catch{}return Ge(r)}var re=process.env.SPRITE_PUBLIC_SERVER||tn()||null;function tn(){return"wss://drawpixie.com"}var Ke=Te(process.env.XDG_CONFIG_HOME||Te(Yt(),".config"),"sprite"),Pe=Te(Ke,"agent.json"),Xe=r=>String(r??"").replace(/\/+$/,"");function Ze(){return`${Qt().replace(/\.local$/,"")}`.slice(0,60)||"a computer"}async function Ye(){try{let r=JSON.parse(await Jt(Pe,"utf8"));return r&&typeof r=="object"&&r.servers?r:{servers:{}}}catch{return{servers:{}}}}async function oe(r){return process.env.SPRITE_TOKEN?{token:process.env.SPRITE_TOKEN,from:"the environment"}:(await Ye()).servers[Xe(r)]??null}async function Qe(r,e){await Kt(Ke,{recursive:!0,mode:448});let t=await Ye();t.servers[Xe(r)]={...e,at:Date.now()};let n=`${Pe}.tmp`;await Vt(n,JSON.stringify(t,null,2),{mode:384}),await Xt(n,384);let{rename:o}=await import("node:fs/promises");await o(n,Pe)}async function et(r,{timeoutMs:e=3e3}={}){try{let t=await fetch(`${E(r)}/setup`,{signal:AbortSignal.timeout(e)});return t.ok?!!(await t.json()).accounts:!1}catch{return!1}}async function tt(r,e,{session:t=null}={}){let n=t??await oe(r);if(!n?.token)return;let o=await fetch(`${E(r)}/documents/${encodeURIComponent(e)}/token`,{headers:{Authorization:`Bearer ${n.token}`}});if(o.status===401)throw new Error("this machine is signed out \u2014 pair it again");if(o.status===403)throw new Error(`no access to ${e}`);if(!o.ok)throw new Error(`could not get access to ${e}`);return(await o.json()).token}async function nt(r,{name:e,w:t,h:n},{session:o=null}={}){let s=o??await oe(r);if(!s?.token)return;let i=await fetch(`${E(r)}/documents/new`,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:e,w:t,h:n})});if(i.status===401)throw new Error("this machine is signed out \u2014 pair it again");if(!i.ok)throw new Error(`could not make a document: the server said ${i.status}`);let{id:a}=await i.json();if(typeof a!="string"||!a)throw new Error("could not make a document: the server named none");return a}async function rt(r,e,{method:t="GET",body:n=null,session:o=null}={}){let s=o??await oe(r);if(!s?.token)return;let i=await fetch(`${E(r)}${e}`,{method:t,headers:{Authorization:`Bearer ${s.token}`,...n!==null?{"Content-Type":"application/json"}:{}},body:n!==null?JSON.stringify(n):void 0});if(i.status===401)throw new Error("this machine is signed out \u2014 pair it again");let a=await i.json().catch(()=>({}));if(!i.ok)throw new Error(a?.error?String(a.error):`the server said ${i.status}`);return a}function ot(r){let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return new Promise(t=>en(e,[r],()=>t()))}ht();Ne();import{createServer as on}from"node:http";import{randomBytes as ut}from"node:crypto";var sn=300*1e3,an=()=>ut(32).toString("base64url"),cn=()=>ut(16).toString("base64url");function lt(r,e){return`<!doctype html><meta charset="utf-8"><title>Pixie</title><body style="background:#101014;color:#d8d8e0;font:14px/1.6 system-ui,sans-serif;display:grid;place-items:center;height:100vh;margin:0;text-align:center"><div><p style="font-size:16px">${r}</p><p style="color:#8a8a99;font-size:12px">${e}</p></div>`}async function hn({state:r,timeoutMs:e}){let t,n,o=new Promise((c,h)=>{t=c,n=h}),s=on((c,h)=>{let l=new URL(c.url,"http://127.0.0.1");if(l.pathname!=="/callback"){h.writeHead(404).end();return}if(l.searchParams.get("state")!==r){h.writeHead(404).end();return}let u=l.searchParams.get("error");h.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}).end(u?lt("Nothing was granted.","You can close this window."):lt("This computer can now draw in your sprites.","You can close this window and go back to what you were doing.")),t(l.searchParams)});await new Promise((c,h)=>{s.once("error",h),s.listen(0,"127.0.0.1",c)});let i=setTimeout(()=>n(new Error("nobody answered the browser in time")),e);i.unref?.();let{port:a}=s.address();return{redirect:`http://127.0.0.1:${a}/callback`,wait:o,close:()=>{clearTimeout(i),s.close(),s.closeAllConnections?.()}}}async function dt(r,{onUrl:e=()=>{},open:t=ot,label:n="the Pixie agent",scope:o=Oe,timeoutMs:s=sn}={}){let i=an(),a=await ct(i),c=cn(),h=await hn({state:c,timeoutMs:s});try{let l=new URL(`${E(r)}/authorize`);l.searchParams.set("challenge",a),l.searchParams.set("state",c),l.searchParams.set("redirect",h.redirect),l.searchParams.set("scope",o.join(",")),l.searchParams.set("name",n),e(l.toString()),await t(l.toString());let u=await h.wait,d=u.get("error");if(d)throw new Error(d==="access_denied"?"you said no on that screen, so nothing was granted":`that request was refused: ${d}`);let p=u.get("code");if(!p)throw new Error("the browser came back without an authorization");let w=await fetch(`${E(r)}/auth/authorize/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:p,verifier:i,name:Ze()})}),f=await w.json().catch(()=>({}));if(!w.ok||!f.token)throw new Error(f.error||"that authorization could not be exchanged");return await Qe(r,{token:f.token,name:f.name,email:f.email,scope:f.scope??null}),f}finally{h.close()}}import{realpathSync as pt}from"node:fs";import{fileURLToPath as ln}from"node:url";function ft(r){let e=process.argv[1];if(!e)return!1;try{return pt(ln(r))===pt(e)}catch{return!1}}se();import{execFile as qt}from"node:child_process";$t();se();var wn=5e3,we=class{#e=null;constructor(e,t,n){if(!n||!n.author)throw new Error("DocumentClient needs an author");if(this.core=e,this.author=n.author,this.name=n.name||"anonymous",this.agent=n.agent===!0,this.answers=n.answers===!0,this.seed=n.seed??1,this.epoch=0,this.resumed=null,n.resume){let{h:o,dropped:s}=e.call("session.resume",{doc:t,author:this.author,seed:this.seed,seq:n.resume.seq??0,pending:n.resume.pending??[]});this.session=new Q(e,o),this.resumed={seq:n.resume.seq??0,dropped:s??[]}}else this.session=e.openSession(t,this.author,this.seed);this.getToken=n.getToken??null,this.transport=null,this.connected=!1,this.welcomed=!1,this.ready=new Promise(o=>{this.#e=o}),this.participants=[],this.leases=[],this.presence=null,this.you=null,this.onChange=()=>{},this.onPresence=()=>{},this.onStroke=()=>{},this.strokePreview=!0,this.onLeases=()=>{},this.ink=null,this.onInk=()=>{},this.proposals=new Map,this.suggesting=!1,this.onSuggestions=()=>{},this.onLost=()=>{},this.waiters=new Set,this.onPrompt=()=>{},this.onAnswer=()=>{},this.onStop=()=>{},this.onStatus=()=>{}}apply(e,t={}){let n=this.session.apply(e,t);return this.#l(n),this.onChange(),n}acked(e,{timeoutMs:t=3e4}={}){let n=new Set((Array.isArray(e)?e:[e]).map(o=>o?.opId??o).filter(Boolean));return new Promise((o,s)=>{let i={ids:n,resolve:o,reject:s,timer:null};i.timer=setTimeout(()=>{this.waiters.delete(i);let a=[...n].filter(c=>this.session.pending().some(h=>h.opId===c)).length;s(new Error(`${a} operation${a===1?"":"s"} not confirmed by the room after ${Math.round(t/1e3)}s \u2014 `+(this.connected?"it is answering slowly":`the connection dropped; nothing since sequence ${this.session.state().seq} has been saved`)))},t),this.waiters.add(i),this.#r()})}#r(){if(!this.waiters.size)return;let e=new Set(this.session.pending().map(t=>t.opId));for(let t of this.waiters)[...t.ids].some(n=>e.has(n))||(this.waiters.delete(t),clearTimeout(t.timer),t.resolve())}#o(e,t){for(let n of this.waiters)n.ids.has(e)&&(this.waiters.delete(n),clearTimeout(n.timer),n.reject(new Error(t)))}undo(e=Date.now()){let t=this.session.undo(e);return this.#l(t),this.onChange(),t}redo(e=Date.now()){let t=this.session.redo(e);return this.#l(t),this.onChange(),t}setPresence(e){this.presence=e,this.connected&&this.#n({t:T.PRESENCE,...e})}sendStroke({layer:e,frame:t,rect:n,rle:o,done:s=!1}){if(!this.connected||!this.welcomed||!this.strokePreview||this.suggesting)return;this._strokeSentAt=Date.now();let i=bt({t:T.STROKE,layer:e,frame:t,rect:n,rle:o,done:s});i&&this.#i(i)}suggest(e){if(!e.length||!this.connected||!this.welcomed)return[];let t=this.session.state().seq,n=e.map(o=>({opId:I(),author:this.author,parentSeq:t,...o}));return this.#n({t:T.SUBMIT,ops:n}),n}review(e,t){!this.connected||!this.welcomed||this.#n({t:T.REVIEW,author:e,verdict:t})}lease(e,t={}){this.#n({t:T.LEASE,action:e,...t})}prompt(e,{where:t=mt.DOCUMENT}={}){if(!this.connected)return null;let n=String(e??"").trim().slice(0,2e3);if(!n)return null;let o=I();return this.#n({t:T.PROMPT,id:o,text:n,where:t}),o}answer(e,t="",{reply:n=null,made:o=null,model:s=null}={}){return this.connected?(this.#n({t:T.ANSWER,state:e,text:String(t??"").slice(0,2e3),reply:n,made:o,model:s}),!0):!1}stopAnswer(e){return!this.connected||!e?!1:(this.#n({t:T.STOP,id:e}),!0)}get state(){return this.session.state()}checkpoint({doc:e=!0}={}){return{epoch:this.epoch,author:this.author,...this.session.checkpoint({doc:e})}}composite(e){return this.session.composite(e)}connect(e){return this.transport=e,this.pendingToken=this.getToken?this.getToken():void 0,this.pendingToken?.catch?.(()=>{}),e.onopen=async()=>{this.connected=!0,this.welcomed=!1,clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.connected&&this.#n({t:T.PING})},wn),await this.#a()},e.onmessage=t=>this.#p(t),e.onclose=()=>{this.connected=!1,this.welcomed=!1,clearInterval(this.heartbeat),this.onStatus({connected:!1})},e.readyState===1&&e.onopen(),this}disconnect(){if(this.transport){this.connected=!1,this.welcomed=!1,clearInterval(this.heartbeat);try{this.transport.close()}catch{}this.transport=null,this.onStatus({connected:!1})}}async#a(){let e;if(this.pendingToken!==void 0){let n=this.pendingToken;this.pendingToken=void 0,e=await n}else e=this.getToken?await this.getToken():void 0;let t=this.session.state();this.#n({t:T.HELLO,author:this.author,name:this.name,token:e,since:t.seq,...this.agent?{agent:!0}:{},...this.answers?{answers:!0}:{},...this.presence?.active===!1?{active:!1}:{},docId:t.doc.id})}#p(e){let t=xt(e);if(t)switch(t.t){case P.WELCOME:return this.#h(t);case P.REHELLO:return this.welcomed=!1,void this.#a();case P.OPS:return this.#c(t);case P.REJECT:return this.#t(t);case P.PRESENCE:return this.participants=t.participants||[],this.onPresence(this.participants);case P.STROKE:return this.onStroke(t);case P.LEASE:return this.leases=t.leases||[],this.onLeases(this.leases);case P.INK:return this.ink={left:t.left,cap:t.cap,refillMs:t.refillMs,nextInMs:t.nextInMs??0,at:Date.now()},this.onInk(this.ink);case P.SUGGESTIONS:return this.proposals=new Map((t.proposals??[]).map(n=>[n.author,{...n,ops:[...n.ops??[]]}])),this.onSuggestions(this.proposals);case P.SUGGESTION:{if(t.gone)return this.proposals.delete(t.author),this.onSuggestions(this.proposals,{author:t.author,name:t.name??null,gone:t.gone,by:t.by??null,applied:t.applied??0});let n=this.proposals.get(t.author)??{author:t.author,name:t.name??null,cc:t.cc??null,ops:[],at:t.at};if(n.name=t.name??n.name,n.at=t.at??n.at,t.replaced?.length){let o=new Set(t.replaced);n.ops=n.ops.filter(s=>!(s.rect?.w===1&&s.rect?.h===1&&o.has(`${s.rect.x},${s.rect.y}`)))}return n.ops.push(...t.ops??[]),this.proposals.set(t.author,n),this.onSuggestions(this.proposals,{author:t.author,added:t.ops?.length??0})}case P.PROMPT:return this.onPrompt(t);case P.ANSWER:return this.onAnswer(t);case P.STOP:return this.onStop(t);case P.ERROR:if(this.#d(t.message)){this.strokePreview=!1;return}return this.onLost({kind:t.fatal?"fatal":"protocol",message:t.message});default:return}}#h(e){this.you=e.you,this.suggesting=e.you?.suggest===!0,this.welcomed=!0;let t=this.session.pending();if(e.catchup.kind===wt.SNAPSHOT){let{h:n,dropped:o}=this.core.call("session.resume",{doc:e.catchup.doc,author:this.author,seed:this.seed,seq:e.catchup.seq,pending:t});if(this.session.close(),this.session=new Q(this.core,n),this.epoch++,o&&o.length){for(let s of o)this.#o(s,"could not be replayed onto the current document");this.onLost({kind:"rebased",ops:o,message:`${o.length} edit${o.length>1?"s":""} could not be replayed onto the current document`})}}else for(let n of e.catchup.ops||[])this.#u(n);if(this.#r(),this.participants=e.participants||[],this.leases=e.leases||[],t.length&&this.suggesting)for(let n of t)this.session.reject(n.opId);else t.length&&this.#n({t:T.SUBMIT,ops:t});this.presence&&this.#n({t:T.PRESENCE,...this.presence}),this.onStatus({connected:!0,resent:t.length}),this.onPresence(this.participants),this.onLeases(this.leases),this.onChange(),this.#e?.(),this.#e=null}#c(e){let t=!1;for(let n of e.ops||[])this.#u(n),t=!0;t&&(this.#r(),this.onChange())}#u(e){let t=this.session.remote(e);t.dropped&&t.dropped.length&&this.onLost({kind:"obsolete",ops:t.dropped,message:`${t.dropped.length} of your edits no longer apply and were dropped`})}#t(e){e.opId&&this.session.reject(e.opId),e.opId&&this.#o(e.opId,e.message),this.onLost({kind:e.kind,ops:e.opId?[e.opId]:[],message:e.message}),this.onChange()}#l(e){!e.length||!this.connected||!this.welcomed||this.#n({t:T.SUBMIT,ops:e})}#n(e){this.#i(gt(e))}#d(e){return typeof e!="string"?!1:e===`unknown message: ${T.STROKE}`?!0:e==="unreadable message"&&Date.now()-(this._strokeSentAt??0)<2e3}#i(e){if(this.transport)try{this.transport.send(e)}catch{this.connected=!1}}close(){this.disconnect(),this.session.close()}};se();kt();var F=r=>{let e=String(r).replace("#","");return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]};var ee=([r,e,t])=>.3*r+.59*e+.11*t;function ge([r,e,t]){let n=Math.max(r,e,t),o=Math.min(r,e,t),s=n-o,i=0;return s&&(n===r?i=(e-t)/s%6:n===e?i=(t-r)/s+2:i=(r-e)/s+4,i*=60,i<0&&(i+=360)),[i,n?s/n:0,n/255]}var Et={luminance:(r,e)=>ee(F(r))-ee(F(e)),hue:(r,e)=>{let[t,n]=ge(F(r)),[o,s]=ge(F(e));return n<.08||s<.08?n<.08&&s<.08?ee(F(r))-ee(F(e)):n<.08?-1:1:Math.round(t/20)!==Math.round(o/20)?t-o:ee(F(r))-ee(F(e))},saturation:(r,e)=>ge(F(r))[1]-ge(F(e))[1]};function te(r,e="hue"){let t=Et[e]??Et.hue;return[...r].sort(t)}jt();import{readFile as ce,writeFile as Wn,mkdir as Gn}from"node:fs/promises";import{access as xn,mkdir as $n,writeFile as Sn}from"node:fs/promises";import{dirname as kn}from"node:path";async function ye(r,e,{overwrite:t=!1,seq:n=null}={}){let o=await xn(r).then(()=>!0,()=>!1);if(o&&!t){let s=r.replace(/(\.png)?$/i,`-seq${n??"N"}$1`);throw new Error(`${r} already exists \u2014 a chat that showed it once will keep showing the old picture, so a preview gets a new name each time: ${s}. Pass overwrite: true only for a file nothing has shown yet.`)}return await $n(kn(r),{recursive:!0}),await Sn(r,e),o}import{createHash as Hn}from"node:crypto";import{tmpdir as Jn}from"node:os";import{join as ze,basename as ve,extname as Vn,resolve as Kn}from"node:path";function Ie(r){try{return/^(localhost|127\.0\.0\.1|\[::1\]|::1)$/.test(new URL(E(r)).hostname)}catch{return!1}}function _t(r,{publicServer:e=re}={}){let t=E(r);return e&&r===e?`nothing is answering at ${t} \u2014 this machine is offline, or the site is down`:Ie(r)?`nothing is answering at ${t} \u2014 start the editor with \`npm start\` in the Pixie repository, then try again`:`nothing is answering at ${t} \u2014 check the address and that whatever serves it is up`}import{readFile as In,writeFile as Tt}from"node:fs/promises";var En=new Set(["note","unfinished","takes","intent","finished","run","label"]);function G(r,e=0,t=120){if(r==null||typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return r.length>t?`${r.slice(0,t-1)}\u2026`:r;if(Array.isArray(r)){if(r.length&&r.every(n=>typeof n=="string")){let n=new Set(r.map(o=>o.length));return`${r.length}\xD7${n.size===1?r[0].length:`${Math.min(...n)}\u2013${Math.max(...n)}`}`}return`[${r.length}]`}if(typeof r=="object"){let n=Object.keys(r),o=n.length<=8&&n.every(i=>r[i]==null||typeof r[i]!="object");if(n.length>32||e>0&&!o)return`{${n.length}}`;let s={};for(let i of n)s[i]=G(r[i],e+1,En.has(i)&&typeof r[i]=="string"?2e3:120);return s}return String(r)}function vn(r){if(r&&typeof r=="object"&&Array.isArray(r.content)){let e=r.content.find(n=>n.type==="image"),t=r.content.find(n=>n.type==="text")?.text??"";if(r.isError)return{ok:!1,error:G(t)};if(e)return{ok:!0,result:`image \u2014 ${G(t)}`};try{return{ok:!0,result:G(JSON.parse(t))}}catch{return{ok:!0,result:G(t)}}}return{ok:!0,result:G(r)}}var be=class{constructor(){this.entries=[],this.next=1,this.open=new Map,this.starts=new Map,this.idleFrom=1,this.lead=new Map}async record(e,t,n){let o=Date.now(),s={i:this.next++,t:new Date(o).toISOString(),tool:e,args:G(t??{})};try{let i=await n();return Object.assign(s,vn(i),{ms:Date.now()-o}),this.#e(s),i}catch(i){throw Object.assign(s,{ok:!1,error:G(i?.message??String(i)),ms:Date.now()-o}),this.#e(s),i}}#e(e){this.entries.push(e),this.entries.length>4e3&&this.entries.splice(0,this.entries.length-4e3)}began(e){if(!e)return;let t=this.entries.at(-1)?.i??this.next;this.open.size===0&&this.idleFrom<t&&this.lead.set(e,this.idleFrom),this.open.set(e,t),this.starts.set(t,e)}all(e=500){let t=this.entries.length,n=new Map,o=null;for(let s of this.entries){let i=this.starts.get(s.i);i&&(o=i),n.set(s.i,s.args?.job??o??null),s.tool==="finish_job"&&(s.args?.job??o)===o&&(o=null)}return{calls:t,dropped:Math.max(0,t-e),entries:this.entries.slice(-e).map(s=>n.get(s.i)?{...s,job:n.get(s.i)}:s)}}finished(e){let t=e??(this.open.size===1?[...this.open.keys()][0]:null);if(!t||!this.open.has(t))return[];let n=this.open.get(t);this.open.delete(t);let o=this.lead.get(t)??n;return this.lead.delete(t),this.open.size===0&&(this.idleFrom=this.next),this.entries.filter(s=>s.i>=o&&(s.args?.job==null||s.args.job===t)&&(this.starts.get(s.i)??t)===t).map(s=>s.i<n?{...s,between:!0}:s)}};function At(r,e){let t=r.inputSchema??{},n=t.properties??{},o=Object.keys(n),s=e&&typeof e=="object"?e:{},i={};for(let[c,h]of Object.entries(s)){if(!(c in n)){let l=_n(c,o),u=o.length?`${r.name} takes: ${o.join(", ")}.`:`${r.name} takes no arguments.`;throw new Error(`no such argument \`${c}\`${l?` \u2014 did you mean \`${l}\`?`:""} ${u}`)}i[c]=jn(r.name,c,n[c],h)}let a=(t.required??[]).filter(c=>i[c]===void 0);if(a.length)throw new Error(`${r.name} needs ${a.map(c=>`\`${c}\``).join(" and ")}. It takes: ${o.join(", ")}.`);return i}function jn(r,e,t,n){if(n==null)return n;let o=t.type;if(o==="integer"||o==="number"){let s=typeof n=="string"&&n.trim()!==""?Number(n):n;if(typeof s!="number"||!Number.isFinite(s))throw new Error(`\`${e}\` must be a number, got ${ne(n)}. ${r} takes \`${e}\` as ${o==="integer"?"an integer":"a number"}.`);if(o==="integer"&&!Number.isInteger(s))throw new Error(`\`${e}\` must be a whole number, got ${s}.`);if(t.minimum!==void 0&&s<t.minimum)throw new Error(`\`${e}\` must be at least ${t.minimum}, got ${s}.`);if(t.maximum!==void 0&&s>t.maximum)throw new Error(`\`${e}\` must be at most ${t.maximum}, got ${s}.`);return s}if(o==="boolean"){if(n==="true")return!0;if(n==="false")return!1;if(typeof n!="boolean")throw new Error(`\`${e}\` must be true or false, got ${ne(n)}.`);return n}if(o==="string"&&typeof n!="string"){if(typeof n=="number")return String(n);throw new Error(`\`${e}\` must be text, got ${ne(n)}.`)}if(o==="array"&&!Array.isArray(n))throw new Error(`\`${e}\` must be a list, got ${ne(n)}.`);if(o==="object"&&(typeof n!="object"||Array.isArray(n)))throw new Error(`\`${e}\` must be an object, got ${ne(n)}.`);if(t.enum&&!t.enum.includes(n))throw new Error(`\`${e}\` must be one of ${t.enum.map(s=>`\`${s}\``).join(", ")}, got ${ne(n)}.`);return n}function ne(r){return typeof r=="string"?`"${r.length>40?r.slice(0,37)+"\u2026":r}"`:Array.isArray(r)?"a list":r&&typeof r=="object"?"an object":String(r)}function _n(r,e){let t=r.toLowerCase(),n=e.filter(i=>{let a=i.toLowerCase();return(t.startsWith(a)||a.startsWith(t))&&a!==t});if(n.length)return n.sort((i,a)=>Math.abs(i.length-t.length)-Math.abs(a.length-t.length))[0];let o=null,s=3;for(let i of e){let a=An(t,i.toLowerCase());a<s&&(s=a,o=i)}return o}function An(r,e){let t=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=r.length;n++){let o=t[0];t[0]=n;for(let s=1;s<=e.length;s++){let i=t[s];t[s]=Math.min(t[s]+1,t[s-1]+1,o+(r[n-1]===e[s-1]?0:1)),o=i}}return t[e.length]}import{readFileSync as Rn}from"node:fs";import{execFileSync as Tn}from"node:child_process";import{fileURLToPath as Pn}from"node:url";import{dirname as On}from"node:path";var Rt="0.7.5";function Nn(){let r=new URL("./version.json",import.meta.url);try{let e=JSON.parse(Rn(r,"utf8"))?.version;if(typeof e=="string"&&e)return e;throw new Error("it names no version")}catch(e){throw new Error(`${r.pathname} could not be read as a version: ${e.message}`)}}var xe=Rt??Nn();function Mn(){if(Rt)return null;let r=On(Pn(import.meta.url)),e=(...t)=>Tn("git",t,{cwd:r,stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();try{let t=e("rev-parse","--short=12","HEAD");return t?e("status","--porcelain","--",".","../../edge/src","../../core/js")?`${t}-dirty`:t:null}catch{return null}}var Ce=Mn();var $e={type:"string",description:"#rrggbb"};async function Cn(r,e){let t=await In(r).catch(s=>{throw new Error(`could not read ${r}: ${s.code==="ENOENT"?"no such file":s.message}`)});if(t.length>8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71){if(!e.core?.decodePng)throw new Error("this server cannot decode a PNG \u2014 send rows and colors");return Ln(e.core.decodePng(t))}let o;try{o=JSON.parse(t.toString("utf8"))}catch{throw new Error(`${r} is neither a PNG nor JSON`)}if(!o||typeof o!="object"||!Array.isArray(o.rows)||typeof o.colors!="object")throw new Error(`${r} needs "rows" (an array of strings) and "colors" (a map of character to #rrggbb)`);return o}function Ln({w:r,h:e,pixels:t}){let n={},o=new Map,s=33,i=h=>{let l=o.get(h);if(l)return l;for(;;)if(s===34||s===46||s===92||s===127)s+=1;else if(s>=128&&s<161)s=161;else if(s>=55296&&s<57344)s=57344;else break;return l=String.fromCodePoint(s),s+=1,o.set(h,l),n[l]=h,l},a=h=>h.toString(16).padStart(2,"0"),c=[];for(let h=0;h<e;h++){let l="";for(let u=0;u<r;u++){let d=(h*r+u)*4,p=t[d+3];if(p===0){l+=".";continue}let w=p===255?`#${a(t[d])}${a(t[d+1])}${a(t[d+2])}`:`#${a(t[d])}${a(t[d+1])}${a(t[d+2])}${a(p)}`;l+=i(w)}c.push(l)}return{rows:c,colors:n}}var O={type:"string",description:"The job this call belongs to. May be omitted when exactly one job is open."},ie={type:"string",description:"Which document. Omit to use the one your job owns. The id \u2014 the one new_sprite, get_info and list_documents hand back \u2014 or the exact name when only one document has it. In a local editor a 0-based tab index works too."},Un=r=>({isError:!0,content:[{type:"text",text:r}]}),Se=r=>({content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r)}]}),Pt=(r,e)=>({content:[{type:"image",data:Buffer.from(r).toString("base64"),mimeType:"image/png"},{type:"text",text:e}]}),U={w:240,h:126},Ot={w:80,h:42},Dn="40\xD721, 80\xD742, 120\xD763, 160\xD784, 240\xD7126, 480\xD7252, 600\xD7315",zn="40\xD740, 50\xD750, 80\xD780, 100\xD7100",Fn="60\xD720, 75\xD725, 150\xD750, 300\xD7100";function Le(r,e){if(!r||!e)return null;let t=r/e,n=1200/630;if(Math.abs(t-n)<.15){let o=Math.round(r/n);return`${r}\xD7${e} is ${t.toFixed(2)}:1; the link-card shape at this width is ${r}\xD7${o} \u2014 resize_canvas if it is meant to be posted.`}return Math.abs(t-1)<.1?`${r}\xD7${e} is nearly square; ${Math.max(r,e)}\xD7${Math.max(r,e)} would be a profile picture.`:Math.abs(t-3)<.25?`${r}\xD7${e} is nearly 3:1; ${r}\xD7${Math.round(r/3)} would be a profile banner.`:null}function ke(r,e){return!r||!e?null:r===e?"This is square, the shape of a profile picture: in the editor, file \u25B8 Save as profile picture (400\xD7400) fits it inside the circle it will be cropped to. Tell the user.":r===3*e?"This is 3:1, the shape of a profile banner: in the editor, file \u25B8 Save as profile banner (1500\xD7500) exports it at the size X wants. Tell the user.":Math.abs(r/e-1200/630)<.02?"This is the link-card shape: the share button posts it edge to edge.":null}function qn(r){let e=String(r??"").trim();if(!/^[A-Za-z0-9]+([-_][A-Za-z0-9]+)+$/.test(e))return e;let t=e.split(/[-_]+/).join(" ");return t[0].toUpperCase()+t.slice(1)}var Bn=[{name:"new_sprite",description:"Create a sprite and claim it. Call this FIRST \u2014 before writing a script, computing a grid, or thinking about pixels. It costs milliseconds and puts a labeled document in front of the user immediately, so they can see what you are making and where. The tab opens in the background and never steals their focus. The size is `w` and `h` (not width/height), as everywhere here.",inputSchema:{type:"object",properties:{name:{type:"string",description:'The title, the way a person would write it: "Blue cake", not "blue-cake". Shown on the tab and in the library; the URL is minted from it. A hyphenated lowercase name is turned into words.'},w:{type:"integer",default:U.w,description:`Width in pixels. WHAT THE USER ASKED FOR WINS: a stated size or shape is used as stated, and a named artist, piece or style is matched in scale and detail. The rest is defaults for when nothing was said: ${U.w}\xD7${U.h} \u2014 1.91:1, the ratio link cards crop to, so a piece drawn on it posts edge to edge, and big enough for a subject with parts (a dish with its slice and garnish, a figure with props, a room). ${Ot.w}\xD7${Ot.h} when the user asks for something SIMPLE \u2014 "simple", "quick", "small", "minimal", "a little", "basic", "rough", "doodle", "icon-like" \u2014 bold shapes and big pixels. Any multiple of 40\xD721 fills the card (${Dn}: examples, not limits). A PROFILE PICTURE is square and cropped to a circle \u2014 keep the subject inside it: ${zn}. A BANNER is 3:1: ${Fn}. Use a game asset's own size (8\xD78, 16\xD716, 32\xD732) only when the user asks for a tile, icon, or sprite for a game.`},h:{type:"integer",default:U.h,description:"Height in pixels. See w."},palette:{type:"array",items:$e,description:"Optional starting palette. Kept in ramp order \u2014 by hue, then dark to light \u2014 not the order given, so a script that indexes the document's palette by position will be off: map by hex."},intent:{type:"string",description:'One line on what you are making, including the VIEW. Shown while you work. The default view is three-quarter: the camera above and to one side, so an object shows its top and two sides and a scene has depth \u2014 unless the user says "flat", "side view", "front", "profile", "top-down", "icon" or "tile", which mean what they say and no perspective at all.'},folder:{type:"string",description:'Optional folder to file it in, by path (`food/sushi`). Made if it does not exist. Use this when the user asks for sprites "in a folder" rather than moving them afterwards.'},challenge:{type:"string",enum:["daily","weekly"],description:'"daily" when the user asks for the sprite of the day / today\'s theme / the Pixel Dailies; "weekly" for the sprite of the week / this week\'s word / Weekly Pixels. The name comes from the theme itself (pass `name` only to override), and finish_job will say how to post it as an entry. Call `challenges` first if you want to see the theme before drawing.'}},required:["intent"]},run:async(r,e)=>{let t=r.name?qn(r.name):null,n=r.w??null,o=r.h??null;if(r.challenge){let s=await e.challenge(r.challenge);if(t??=s.theme,n===null&&o===null&&s.sizes?.length){let i=s.sizes[Math.floor((s.sizes.length-1)/2)],[a,c]=i.split(/[x×]/).map(Number);a&&c&&([n,o]=[a,c])}}if(!t)throw new Error("new_sprite needs a name, or a challenge to take one from");return e.newSprite({name:t,w:n??U.w,h:o??U.h,intent:r.intent,palette:r.palette,folder:r.folder??null,challenge:r.challenge??null})}},{name:"challenges",description:`The sprite of the day and the sprite of the week: Pixel Dailies sets a theme every day ("Today's theme is #Gateway") and Weekly Pixels a word every week, with sizes. When the user says "the sprite of the day", "today's theme", "the daily", "the weekly", "this week's word" or names either community, this is what they mean \u2014 read it here rather than asking them. The server reads the accounts and keeps the answer; nothing is fetched from Bluesky by you.`,inputSchema:{type:"object",properties:{}},run:(r,e)=>e.challenges()},{name:"begin_job",description:"Claim an existing document for one piece of work \u2014 the other way to start, where new_sprite is the one for new art. Refused by name if another job holds it, which is what keeps parallel requests from colliding. With no `document` and no job open, it picks up the document you last finished IN THIS SESSION \u2014 one more pass on the same sprite is begin_job({ intent }); a document from an earlier session has to be named (list_documents has them).",inputSchema:{type:"object",properties:{document:{type:"string",description:"Which document: the id, or the exact name when only one document has it. Omit, with no job open, for the one you last finished in this session; a document from an earlier one has to be named."},intent:{type:"string"},layer:{type:"string",description:"Restrict the claim to one layer, leaving the rest free. Rooms only."}},required:["intent"]},run:(r,e)=>e.beginJob({document:r.document,intent:r.intent,layer:r.layer??null})},{name:"finish_job",description:"Release the document. Call this when the sprite is done, so the user knows to look. The result says what to do next for a profile picture, a banner or a card \u2014 pass that on to the user \u2014 and carries `trace`: every call of this job, as the server saw it \u2014 and, marked `between: true`, any made with no job open since the last finish. When the task asked for a report back, do NOT assemble trace.jsonl out of these: `get_info({ trace: true })` returns the whole session in one result, and two reports that concatenated finish_job returns by hand both lost `versions` \u2014 which is a sibling of `trace` here, travels inside this call's own trace entry, and is what feedback.py stamps the report with. Without it a current server is labeled ancient and every friction item struck.",inputSchema:{type:"object",properties:{job:O,note:{type:"string",description:`One line on what shipped \u2014 "8 roses, hooked thorns, ivy; crown at CY 69" \u2014 which becomes the history's line for this job in place of the intent written before the work. Optional; up to 200 characters.`}}},run:async(r,e)=>({...await e.finishJob({job:r.job,note:r.note??""}),versions:{mcp:xe,...Ce?{commit:Ce}:{}}})},{name:"push_source",description:"Push the generator behind this job \u2014 the script(s) that made the sprite \u2014 so the next agent (or you, tomorrow) can pick the work up rather than redraw it from the pixels. Stored beside the job's mark in the document's version history, with the seq it reproduces; READABLE BY THIS ACCOUNT ONLY, never by anyone else in the room. Push the source, not its output: the .py, and anything it imports that is yours; not the grid JSON or a PNG, which it regenerates (text, \u2264 16 files, \u2264 96 KiB). `run` is the exact command; `takes` what it needs that is not in the push (a reference from Commons: its URL; the skill's references/ helpers by name); `unfinished` what you would do next. Push before finish_job, and again after a real change.",inputSchema:{type:"object",properties:{files:{type:"array",items:{type:"string"},description:'Paths on this machine to the files to push. The basename is kept, the directory is not \u2014 so two generators both called `mint.py` need `{ from: "<path on disk>", path: "<name to push it as>" }` instead of a plain path.'},run:{type:"string",description:'The command that regenerates the sprite from these files, e.g. "python3 buche.py .context/yule/solo.json && draw_art({ file })".'},takes:{type:"string",description:"What it needs that is not in the push: reference URLs, the references/ helpers it imports, a palette. Empty if nothing."},unfinished:{type:"string",description:"What is not done, or what you would change next. The next agent reads this first."},job:O},required:["files","run"]},run:(r,e)=>e.pushSource({job:r.job,files:r.files,run:r.run,takes:r.takes??"",unfinished:r.unfinished??""})},{name:"pull_source",description:"What this account pushed on a document: with no `job`, the list (job, seq, run, unfinished, file names) \u2014 with a `job`, its files written to disk under `into` (default .context/source/<job>/) with how to run them, what they take and what was unfinished. Call it before redrawing a sprite an agent made: if there is a push, start from it. Only your own pushes come back; a mark with `source: true` in the history that is not listed here is somebody else's. READ THE FILES BEFORE RUNNING THEM, and run them in the workspace with nothing the task does not need \u2014 they are code somebody pushed.",inputSchema:{type:"object",properties:{document:ie,job:{type:"string",description:"The job whose push to write to disk. Omit to list."},into:{type:"string",description:"Directory to write the files into. Default .context/source/<job>/. A file that exists with different content is not overwritten."}}},run:(r,e)=>e.pullSource({document:r.document??null,job:r.job??null,into:r.into??null})},{name:"draw_art",description:'Returns when the room has confirmed the drawing \u2014 `seq` is the room\'s number for it and `committed` is true \u2014 or fails saying why; if it says the connection dropped, wait a moment and check get_info before drawing more. Draw a character grid. Each string in `rows` is one row of pixels and each character maps to a color via `colors`. A key is any single character except "." and " " \u2014 letters, digits, punctuation, any Unicode symbol \u2014 so a generator that runs past 62 colors keeps going. "." and " " leave existing pixels alone; a color mapped to null erases. Every character is resolved before a pixel moves, so a typo fails rather than half-drawing. With no style reference, keep the palette small \u2014 four to eight colors, reused for shading \u2014 because that is what makes a small sprite read as pixel art rather than as a downscaled photograph. When matching an artist or a piece, use as many colors as their work does. A canvas past ~300 wide goes in bands: several calls with `y`, a few dozen rows each. A LARGE OR GENERATED GRID SHOULD NOT PASS THROUGH YOU: have the script write it to a file and pass `file` instead of `rows` \u2014 a JSON file of {rows, colors, x?, y?, \u2026}, or a PNG. Either is the whole canvas or, with `rect`, one region of it: a pass that touched only the fire base sends the same file and names the rect, and the history says "fire base", not everything. The reply says how many pixels are not what they were (`changed`; `inked` is how many the grid painted, when the two differ \u2014 a full-canvas redraw that moved a corner says 180 and 30240) and which colors joined the palette, so growth is never silent (with `palette: "replace"` nothing joins: the palette is this drawing\'s colors, and the reply says so). read here on the same machine. Then the call is fifty bytes, whatever the canvas.',inputSchema:{type:"object",properties:{file:{type:"string",description:'Path to a grid on this machine, instead of rows and colors: a JSON file of draw_art arguments, or a PNG. A PNG\'s colors are used as they are \u2014 not quantized to the palette; each distinct color joins it (or with `palette: "replace"`, becomes it) \u2014 so read_art({ png }) \u2192 edit \u2192 draw_art({ file }) round-trips exactly. Anything given in the call as well wins.'},rows:{type:"array",items:{type:"string"}},colors:{type:"object",additionalProperties:{oneOf:[$e,{type:"null"}]}},x:{type:"integer"},y:{type:"integer"},center:{type:"boolean"},clear:{type:"boolean",description:"Erase the cel first."},rect:{type:"object",description:"With `file`, JSON or PNG: replace only this region `{x, y, w, h}` of the canvas from a full-canvas file \u2014 a one-object change is not a whole-canvas redraw. With `clear`, only the region is emptied first.",properties:{x:{type:"integer"},y:{type:"integer"},w:{type:"integer"},h:{type:"integer"}}},palette:{type:"string",enum:["add","replace","keep"],description:"What this drawing's colors do to the document palette: `add` (default) joins them; `replace` makes them the whole palette \u2014 for a generated piece redrawn several times, so the palette does not pile up; `keep` leaves the palette as it is \u2014 for a pass the user may send back (a glow tried three ways left 120 tints behind), or a generator whose blends are not colors anybody will pick."},layer:{type:"string",description:"Layer name or index. Defaults to the top one."},frame:{type:"integer",description:"Frame index. Defaults to the first."},label:{type:"string",description:"What this shows as in the undo history."},job:O}},run:async(r,e)=>{let t=r.file?{...await Cn(r.file,e),...r}:r;if(!Array.isArray(t.rows)||!t.colors)throw new Error("draw_art needs rows and colors, or a file that has them");return e.drawArt({job:t.job,rows:t.rows,colors:t.colors,x:t.x??0,y:t.y??0,center:t.center??!1,clear:t.clear??!1,layer:t.layer,frame:t.frame??0,label:t.label,palette:t.palette??"add",rect:t.rect??null})}},{name:"draw_animation",description:"Write every frame in ONE call, as a single undo step. Use copyPrevious so a frame carries the last one forward and sends only the pixels that moved \u2014 that is what takes a six-frame loop from four thousand tokens of restated grid to under a thousand. Never loop draw_art. SILHOUETTE FIRST: at 32px a front-on animal is any animal; when the subject could go several ways, draw 2-3 rough silhouettes as frames, look with render_animation, keep the one that reads, then add detail \u2014 three candidates cost barely more than one.",inputSchema:{type:"object",properties:{frames:{type:"array",minItems:1,items:{type:"object",properties:{rows:{type:"array",items:{type:"string"}},copyPrevious:{type:"boolean"},x:{type:"integer"},y:{type:"integer"},center:{type:"boolean"}},required:["rows"]}},colors:{type:"object",additionalProperties:{oneOf:[$e,{type:"null"}]}},fps:{type:"number"},layer:{type:"string"},label:{type:"string"},job:O},required:["frames","colors"]},run:(r,e)=>e.drawAnimation({job:r.job,frames:r.frames,colors:r.colors,fps:r.fps,layer:r.layer,label:r.label})},{name:"read_art",description:"Read a cel back as a grid \u2014 the exact inverse of draw_art, so you can extend art a human drew rather than only replacing it. Reads never need a job and never wait: with no job open they read the document last finished in this session, or the `document` named. The fallback is this process's memory, so the first call of a new session names its document.",inputSchema:{type:"object",properties:{document:ie,layer:{type:"string"},frame:{type:"integer"},trim:{type:"boolean",description:"Return only the drawn area. Rooms only."},file:{type:"string",description:"Write the grid to this path on this machine as JSON \u2014 the shape draw_art takes as `file` \u2014 instead of returning it, so a script can round-trip art without it passing through you. The reply says where it went and how big it is."},png:{type:"string",description:"Write the document to this path as a PNG, one image pixel per sprite pixel \u2014 the composite, or one `layer` \u2014 so an image tool, `references/compare.py` or `references/scene.py guides` can open the room's truth directly. A local editor writes the composite only."},job:O}},run:async(r,e)=>{if(r.png){if(!e.readPng)throw new Error("a PNG of the document is a room thing \u2014 in a local editor, read_art({ file }) and render it");let i=await e.readPng({document:r.document,job:r.job,layer:r.layer??null,frame:r.frame??0});return await Tt(r.png,i.png).catch(a=>{throw new Error(`could not write ${r.png}: ${a.message}`)}),{document:i.document,png:r.png,size:`${i.w}\xD7${i.h}`,layer:r.layer??"composite"}}let t=await e.readArt({document:r.document,job:r.job,layer:r.layer,frame:r.frame??0,trim:r.trim??!1});if(!r.file)return t;let{rows:n,colors:o,...s}=t;return await Tt(r.file,JSON.stringify({rows:n,colors:o},null,0)).catch(i=>{throw new Error(`could not write ${r.file}: ${i.message}`)}),{...s,file:r.file,size:`${n[0]?.length??0}\xD7${n.length}`,colors:Object.keys(o??{}).length}}},{name:"render_preview",description:"See one frame as an image, so you can check your own work rather than working blind. Needs no job: with none open it renders the document last finished in this session, or the `document` named \u2014 the first look of a new session names it, the fallback being this process's. Rendered at a readable size by default (about a thousand pixels on the long side); `scale` is screen pixels per sprite pixel if you want a particular one. To look closely at one part of a big canvas \u2014 a cell of a sprite sheet \u2014 pass `rect` `{x, y, w, h}` in sprite pixels, or `rects` to put several objects side by side in ONE image, which is what the per-object audit wants (an agent wrote its own tiler rather than make eight calls, and spent the audit looking at its own render instead of the room's). The text beside the image says exactly what was rendered, at what scale, and at which document seq \u2014 the room's confirmed state, never a queued or stale mirror: a render waits for the room to confirm what you sent and is refused while the connection is down. WHEN MATCHING A REFERENCE, pass `reference` (a path on this machine \u2014 PNG, or a JPEG on a Mac): the reference is brought to the canvas grid and shown on the LEFT of the render, same rect, same scale \u2014 the only comparison that catches an object built nothing like the original. A reference that is not the shape of the canvas is fitted whole (black where it does not reach) \u2014 into the `rect` when one is given, so one icon beside the one cell it was drawn into is the icon filling that cell; `referenceRect` brings one part of it \u2014 the object you are checking, in reference pixels \u2014 into the `rect` instead (into the whole canvas when there is no `rect`), fitted by the side that limits it, so the two sides are one object at one scale; the caption gives that scale in reference pixels per canvas pixel. That is how to compare one thing up close. To give rects in canvas pixels instead, pass the reference already resampled to the canvas's size (analyze_reference.py --resample): a reference the canvas's shape maps 1:1, so `referenceRect` is then the same numbers as `rect`. Judge per object from that, never from the whole image or from memory \u2014 and judge construction, not resemblance: count the faces, name the light, say where the shadow falls, on theirs and on yours. `values` renders both as grays \u2014 the squint test for a value plan and a focal point. ON A TRANSPARENT CANVAS pass `background` (\"checker\" or a #rrggbb): alpha is shown over white, so a white tip or a pale sparkle is invisible and cannot be judged at all.",inputSchema:{type:"object",properties:{document:ie,frame:{type:"integer"},scale:{type:"integer",description:"Screen pixels per sprite pixel. Default: whatever makes the long side about 1000px."},rect:{type:"object",description:"A window onto the canvas in sprite pixels, cropped before scaling. Omit w/h to run to the edge.",properties:{x:{type:"integer"},y:{type:"integer"},w:{type:"integer"},h:{type:"integer"}}},rects:{type:"array",description:"Several windows instead of one, tiled left to right into a single image with a magenta line between them \u2014 the per-object audit in one call rather than one call per object. Not with `reference`.",items:{type:"object",properties:{x:{type:"integer"},y:{type:"integer"},w:{type:"integer"},h:{type:"integer"}}}},reference:{type:"string",description:"Path to a reference image on this machine: a PNG anywhere, a JPEG on a Mac (converted on the way; elsewhere convert it first). Shown beside the render at the same crop and scale, fitted whole to the canvas grid and centered \u2014 or the part of it `referenceRect` names."},referenceRect:{type:"object",description:"The part of the reference to bring to the grid, in reference pixels: `{x, y, w, h}`. Omit for the whole picture. With a `rect`, this region is fitted into that rect (centered, black where it does not reach); pick the region that holds the object `rect` shows, at the same proportions, and the two sides are that object at one scale.",properties:{x:{type:"integer"},y:{type:"integer"},w:{type:"integer"},h:{type:"integer"}}},values:{type:"boolean",description:"Render as values only (grayscale) \u2014 the render, and the reference when one is given. A picture that is mid-tone everywhere shows it here and nowhere else."},background:{type:"string",description:'What the transparent pixels show as: `"checker"` or a `#rrggbb`. Default is nothing \u2014 the alpha arrives as alpha, which a viewer paints white, so white or near-white art on a transparent canvas is INVISIBLE in the preview. Pass this whenever the canvas is transparent and the art has light pixels: a white tip, a sparkle, snow, a highlight. A sparkle was once shipped unseen for want of it.'},file:{type:"string",description:"Also write the image to this path \u2014 exactly what is returned: the rect, the scale, the reference beside it, the values. For `final.png` and the crops a report keeps, for any check that wants the room's picture rather than a local re-render, and for showing the user. A path that already exists is REFUSED unless `overwrite` is true: a chat that has shown a path once keeps showing the old picture under it, so a preview meant to be seen gets a new name every time (`preview-<seq>.png`; the caption says the seq)."},overwrite:{type:"boolean",description:"Let `file` replace a file that exists. Only for a file nothing has shown yet \u2014 a report's `final.png` being redone \u2014 never for a preview embedded in a reply."},job:O}},async run(r,e){let t=await e.preview({document:r.document,job:r.job,frame:r.frame??0,scale:r.scale??null,rect:r.rect??null,rects:r.rects??null,reference:r.reference??null,referenceRect:r.referenceRect??null,values:r.values===!0,background:r.background??null,file:r.file??null,overwrite:r.overwrite===!0});return Pt(t.png,t.caption)}},{name:"render_animation",description:"Every frame as one numbered contact sheet. Stills inspected one call at a time, minutes apart, cannot tell you whether motion reads; a contact sheet can, in one call. Check any animation with this before calling it done.",inputSchema:{type:"object",properties:{document:ie,columns:{type:"integer",default:4},scale:{type:"integer",default:2},job:O}},async run(r,e){let t=await e.sheet({document:r.document,job:r.job,columns:r.columns??4,scale:r.scale??2});return Pt(t.png,t.caption)}},{name:"add_layer",description:"Add a layer above the others. Anything you will revise while the rest stays \u2014 a figure over a background, a caption over a figure \u2014 goes on its own layer, so a revision is one draw_art with `clear: true` on that layer and the base is never redrawn or at risk.",inputSchema:{type:"object",properties:{name:{type:"string"},job:O}},run:(r,e)=>e.addLayer({job:r.job,name:r.name})},{name:"add_frame",description:"Add an animation frame after the last one.",inputSchema:{type:"object",properties:{copy:{type:"boolean",description:"Start from the previous frame."},job:O}},run:(r,e)=>e.addFrame({job:r.job,copy:r.copy??!1})},{name:"set_palette",description:"Replace the palette. Constraining yourself to a small fixed palette is the single biggest quality lever in pixel art \u2014 choose it before you draw, because every draw_art adds its colors. With `prune: true` and no `colors`, drop every palette entry no pixel uses instead: the way to clean up after a session that did not. Never done for you on finish_job.",inputSchema:{type:"object",properties:{colors:{type:"array",items:$e,minItems:1},prune:{type:"boolean",description:"Keep only the colors some pixel uses. `colors` is ignored."},job:O}},run:(r,e)=>!r.prune&&!r.colors?.length?Un("set_palette wants `colors`, or `prune: true`"):e.setPalette({job:r.job,colors:r.colors??[],prune:r.prune===!0})},{name:"set_fps",description:"Set playback speed for every frame. Eight to twelve suits character animation.",inputSchema:{type:"object",properties:{fps:{type:"integer",minimum:1,maximum:60},job:O},required:["fps"]},run:(r,e)=>e.setFps({job:r.job,fps:r.fps})},{name:"clear",description:"Erase a cel. Destructive, so it goes through a job like every other write.",inputSchema:{type:"object",properties:{layer:{type:"string"},frame:{type:"integer"},job:O}},run:(r,e)=>e.clearCel({job:r.job,layer:r.layer,frame:r.frame??0})},{name:"trim_canvas",description:'Crop the canvas to the drawn pixels. Call this before finish_job on every GAME ASSET \u2014 a tile, an icon, a sprite for a sheet: you cannot know its extent before you have drawn it, so overshoot at new_sprite and trim afterwards, or empty space is inherited by every export and sheet. Do NOT trim a piece made to be posted: its canvas is the card, and the space around the subject is the composition. `center: true` instead KEEPS the canvas and moves the art to the middle of it \u2014 "make it horizontally and vertically centered", which arrives on every transparent sprite; `get_info`\'s `bbox` is where the art is now.',inputSchema:{type:"object",properties:{margin:{type:"integer",default:0},center:{type:"boolean",description:"Do not crop: keep the canvas and move the drawn pixels to its center. `margin` is ignored."},job:O}},run:(r,e)=>e.trim({job:r.job,margin:r.margin??0,center:r.center===!0})},{name:"resize_canvas",description:"Change the canvas size, keeping the art \u2014 the fix for a sprite made at the wrong size, in place, on the same document. `anchor` says where the old canvas sits on the new one: `center` (default), `top-left`, `top`, `top-right`, `left`, `right`, `bottom-left`, `bottom`, `bottom-right`. Never make a second document for a size change. The old art is kept at `anchor`; pass `clear: true` to start the new size blank in the same call \u2014 otherwise the room shows the old picture in the corner until the next full draw_art.",inputSchema:{type:"object",properties:{w:{type:"integer",minimum:1,maximum:1024},h:{type:"integer",minimum:1,maximum:1024},anchor:{type:"string"},clear:{type:"boolean",description:"Erase everything after resizing, so a full redraw at the new size does not follow an old picture in the corner."},job:O},required:["w","h"]},run:(r,e)=>e.resizeCanvas({job:r.job,w:r.w,h:r.h,anchor:r.anchor??"center",clear:r.clear===!0})},{name:"get_info",description:"What is in a document \u2014 size, layers, frames, palette \u2014 and who else is looking at it; `connected` says whether the room is on the other end and `pending` how many operations it has not confirmed. Both should be true and zero before you trust a read. `trace: true` adds this session's whole call record \u2014 every call, not one job's, the same entries finish_job hands back \u2014 which is what a report's Trace section is written from when it spans several jobs. Per process: a new session starts an empty one.",inputSchema:{type:"object",properties:{document:ie,job:O,trace:{type:"boolean",description:"Add every call this session has made, oldest first, as `trace`, each entry carrying the `job` it belongs to \u2014 for a report over more than one job."}}},run:(r,e)=>e.info({document:r.document,job:r.job})},{name:"list_documents",description:'Every document you can reach, and every job currently open. Call this when the user names a sprite ("add a frame to the hamster") so you can pass it to begin_job. Never guess a name.',inputSchema:{type:"object",properties:{}},run:(r,e)=>e.documents()},{name:"create_folder",description:"Make a folder in the library, by path \u2014 `food/sushi` nests. Already existing is fine. Prefer passing `folder` to new_sprite when the sprites are new; use this for an empty folder or before move_documents.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The folder path."}},required:["name"]},run:(r,e)=>e.createFolder({name:r.name})},{name:"move_documents",description:"File documents into a folder, or back to the top level with folder null. Takes document ids from list_documents. The folder is made if it does not exist.",inputSchema:{type:"object",properties:{documents:{type:"array",items:{type:"string"},description:"Document ids."},folder:{type:["string","null"],description:"Folder path, or null for the top level."}},required:["documents"]},run:(r,e)=>e.moveDocuments({documents:r.documents,folder:r.folder??null,make:!0})},{name:"take_requests",description:"Requests people have typed into the editor and not yet been answered. Call this when the user asks you to check, or after joining a room they are in. Each one is somebody asking for a sprite in words \u2014 treat it exactly as if they had said it to you directly. Each carries what it wants: a `room` to answer in, or `room: null` for a request typed at the library, which wants a brand new sprite rather than a change to any existing one.",inputSchema:{type:"object",properties:{}},run:(r,e)=>e.takeRequests()},{name:"open_editor",description:"Open the Pixie editor in the default browser and wait for it to connect. Run this first if nothing is connected.",inputSchema:{type:"object",properties:{}},async run(r,e){let t=await e.openEditor();return Se(t.message)}},{name:"select_document",description:"Bring a document to the front for the USER to look at. This does not give you the right to draw in it \u2014 begin_job does that.",inputSchema:{type:"object",properties:{document:{type:["string","integer"]}},required:["document"]},run:(r,e)=>e.select({document:r.document})},{name:"close_document",description:"Close a document: in a local editor its tab, in a room the connection and any job you hold on it. The document stays in the library, so this tidies the workspace rather than deleting anything.",inputSchema:{type:"object",properties:{document:{type:["string","integer"]}}},run:(r,e)=>e.closeDocument({document:r.document??null})},{name:"set_frame",description:"Move the user to a frame, by 0-based index.",inputSchema:{type:"object",properties:{index:{type:"integer"}},required:["index"]},run:(r,e)=>e.setFrame({index:r.index})},{name:"set_layer",description:"Move the user to a layer, by 0-based index counting from the bottom.",inputSchema:{type:"object",properties:{index:{type:"integer"}},required:["index"]},run:(r,e)=>e.setLayer({index:r.index})},{name:"undo",description:"Undo the last change, so the user can always reject generated art.",inputSchema:{type:"object",properties:{}},run:(r,e)=>e.undo()},{name:"redo",description:"Redo the last undone change.",inputSchema:{type:"object",properties:{}},run:(r,e)=>e.redo()}];function Nt(r){let e=r.trace??=new be,t=n=>n&&typeof n=="object"&&Array.isArray(n.content);return Bn.filter(n=>r.supports(n.name)).map(n=>({name:n.name,description:n.description,inputSchema:n.inputSchema,run:async o=>{let s=await e.record(n.name,o,()=>n.run(At(n,o),r));if((n.name==="new_sprite"||n.name==="begin_job")&&s?.job&&e.began(s.job),n.name==="finish_job"&&s&&typeof s=="object"&&!t(s))return Se({...s,trace:e.finished(s.job??o?.job)});if(n.name==="get_info"&&o?.trace===!0&&s&&typeof s=="object"&&!t(s)){let{calls:i,dropped:a,entries:c}=e.all();return Se({...s,trace:c,traceCalls:i,...a?{traceDropped:a}:{},traceNote:"every call this session made, oldest first \u2014 save as trace.jsonl, one entry per line. This call is in it."})}return t(s)?s:Se(s)}}))}var Mt=/^[A-Za-z0-9_-]{1,64}$/,Xn=6e3;function It(r,e){return Math.max(1,Math.min(32,Math.round(1e3/Math.max(r,e,1))))}function Ct(r,e,t,n=null){let o=Zn(n,r.w,r.h),s=o.x===0&&o.y===0&&o.w===r.w&&o.h===r.h?r:Yn(r,o),i=Math.min(e/o.w,t/o.h),a=Math.max(1,Math.round(o.w*i)),c=Math.max(1,Math.round(o.h*i)),h=er(s,a,c),l=Math.floor((e-a)/2),u=Math.floor((t-c)/2),d=new Uint8Array(e*t*4);for(let p=0;p<c;p++)d.set(h.pixels.subarray(p*a*4,(p+1)*a*4),((u+p)*e+l)*4);return{w:e,h:t,pixels:d,placed:{x:l,y:u,w:a,h:c},region:o,by:e/o.w<=t/o.h?"width":"height"}}function Zn(r,e,t){let n=Math.max(0,Math.min(e-1,Math.floor(Number(r?.x??0))||0)),o=Math.max(0,Math.min(t-1,Math.floor(Number(r?.y??0))||0)),s=Math.max(1,Math.min(e-n,Math.floor(Number(r?.w??e-n))||e-n)),i=Math.max(1,Math.min(t-o,Math.floor(Number(r?.h??t-o))||t-o));return{x:n,y:o,w:s,h:i}}function Yn(r,e){let t=new Uint8Array(e.w*e.h*4);for(let n=0;n<e.h;n++){let o=((e.y+n)*r.w+e.x)*4;t.set(r.pixels.subarray(o,o+e.w*4),n*e.w*4)}return{w:e.w,h:e.h,pixels:t}}async function Qn(r,e){if(e.length>8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return e;let n=e[0]===255&&e[1]===216?"JPEG":e.subarray(0,4).toString()==="GIF8"?"GIF":e.subarray(8,12).toString()==="WEBP"?"WebP":"not a PNG",o="convert it first: python3 references/pngio.py in.jpg out.png (Pillow, or `sips` on a Mac), or any image tool";if(process.platform!=="darwin")throw new Error(`the reference ${r} is ${n==="not a PNG"?n:`a ${n}`}, and this server reads PNG \u2014 ${o}`);let s=ze(Jn(),`pixie-ref-${Hn("sha256").update(e).digest("hex").slice(0,16)}-${ve(r,Vn(r))}.png`),i=await ce(s).catch(()=>null);return i||(await new Promise((a,c)=>{qt("sips",["-s","format","png",r,"--out",s],(h,l,u)=>{h?c(new Error(`the reference ${r} is ${n==="not a PNG"?n:`a ${n}`}, and sips could not convert it (${String(u||h.message).trim()}) \u2014 ${o}`)):a()})}),ce(s))}function er(r,e,t){let n=new Uint8Array(e*t*4),o=r.w/e,s=r.h/t;for(let i=0;i<t;i++){let a=Math.floor(i*s),c=Math.max(a+1,Math.floor((i+1)*s));for(let h=0;h<e;h++){let l=Math.floor(h*o),u=Math.max(l+1,Math.floor((h+1)*o)),d=0,p=0,w=0,f=0,m=0;for(let y=a;y<c&&y<r.h;y++)for(let x=l;x<u&&x<r.w;x++){let A=(y*r.w+x)*4;d+=r.pixels[A],p+=r.pixels[A+1],w+=r.pixels[A+2],f+=r.pixels[A+3],m++}let g=(i*e+h)*4;m&&n.set([Math.round(d/m),Math.round(p/m),Math.round(w/m),Math.round(f/m)],g)}}return{w:e,h:t,pixels:n}}function Ee(r,e=new Uint8Array(r.length)){for(let t=0;t<r.length;t+=4){let n=Math.round(.299*r[t]+.587*r[t+1]+.114*r[t+2]);e[t]=e[t+1]=e[t+2]=n,e[t+3]=r[t+3]}return e}function tr(r){if(r==null||r===!1||r==="")return null;let e=String(r).trim().toLowerCase();if(e==="checker"||e==="true")return{checker:!0};let t=/^#?([0-9a-f]{6})$/.exec(e);if(!t)throw new Error(`background: "checker" or a #rrggbb color, not ${JSON.stringify(r)}`);let n=parseInt(t[1],16);return{rgb:[n>>16&255,n>>8&255,n&255]}}var nr=[[204,204,204],[153,153,153]],Fe=4;function Ue(r,e,t,n,o){if(!o)return r;for(let s=0;s<t;s++)for(let i=0;i<e;i++){let a=(s*e+i)*4,c=r[a+3]/255;if(c===1)continue;let h=o.rgb??nr[(((n.x+i)/Fe|0)+((n.y+s)/Fe|0))%2];for(let l=0;l<3;l++)r[a+l]=Math.round(r[a+l]*c+h[l]*(1-c));r[a+3]=255}return r}function Lt(r){return r?`, on ${r.rgb?`#${r.rgb.map(t=>t.toString(16).padStart(2,"0")).join("")}`:`a ${Fe}px checker`} where the canvas is transparent`:""}function Ut(r,e,t){let n=new Uint8Array(t.w*t.h*4);for(let o=0;o<t.h;o++){let s=((t.y+o)*e+t.x)*4;n.set(r.subarray(s,s+t.w*4),o*t.w*4)}return n}function ae(r,e,t){let n=(c,h)=>Number.isFinite(+c)?Math.max(0,Math.round(+c)):h,o=Math.min(n(r?.x,0),e),s=Math.min(n(r?.y,0),t),i=Math.min(n(r?.w,e-o),e-o),a=Math.min(n(r?.h,t-s),t-s);return{x:o,y:s,w:i,h:a}}var je=class{constructor(e,t){this.core=e,this.author=t.author,this.name=t.name||"agent",this.connectTransport=t.connect,this.getToken=t.getToken??null,this.createDocument=t.createDocument??null,this.control=t.control??null,this.probe=t.probe??null,this.rooms=new Map,this.asked=[],this.onAsked=null,this.jobs=new Map,this.shapeSaid=new Map,this.log=[]}async open(e,{w:t=32,h:n=32,name:o=e}={}){let s=this.rooms.get(e);if(s)return s.client;let i=this.core.newDocument({w:t,h:n,name:o,seed:Ft(),now:Date.now()}),a=new we(this.core,i,{author:this.author,name:this.name,seed:Ft(),agent:!0,getToken:this.getToken?()=>this.getToken(e):null});a.onLost=u=>{this.lastRefusal=u},a.onPrompt=u=>{if(u.author===this.author)return;let d=u.where==="library";this.asked.push({text:u.text,from:u.name,at:u.at,wants:d?"a new sprite":"a change to this one",room:d?null:e,askedIn:e}),this.asked.length>32&&this.asked.shift(),this.onAsked?.()};let c=this.connectTransport(e,{w:t,h:n,name:o}),h=!1;return await new Promise((u,d)=>{let p=setTimeout(()=>d(new Error(`timed out joining ${e}`)),1e4);a.onStatus=f=>{f.connected&&(h=!0,clearTimeout(p),u())},a.connect(c);let w=c.onclose;c.onclose=()=>{if(w?.(),h)return this.#r(e,{w:t,h:n,name:o});clearTimeout(p),this.#e(e).then(f=>d(new Error(f)))}}),this.rooms.set(e,{client:a,attempts:0}),a}async#e(e){return this.serverUrl?(this.probe?await this.probe(this.serverUrl).catch(()=>!1):!1)?Mt.test(e)?`the room "${e}" would not open, and the server is up: try once more \u2014 a room can be away for a moment \u2014 and if it repeats, there is no such document or it is not this account's; list_documents names what it can`:`the room server refused "${e}": that is a name, not a document id \u2014 list_documents gives the id, and passing the exact name works when it is unique`:_t(this.serverUrl):"nothing is answering at the room server"}#r(e,t){let n=this.rooms.get(e);if(!n||n.closing)return;let o=Math.min(15e3,1e3*2**Math.min(n.attempts,4));n.attempts+=1,n.retry=setTimeout(()=>{if(!this.rooms.get(e)||n.closing)return;let s=this.connectTransport(e,t),i=!1,a=s.onclose;n.client.onStatus=h=>{h.connected&&(i=!0,n.attempts=0)},n.client.connect(s);let c=s.onclose;s.onclose=()=>{c?.(),a?.(),this.#r(e,t)}},o),n.retry.unref?.()}client(e){let t=this.rooms.get(e);if(!t)throw new Error(`not in room ${e}`);return t.client}async peek(e){return this.rooms.has(e)?this.client(e):this.open(e)}async begin(e,t,{layer:n=null,open:o={}}={}){let s=await this.open(e,o),i=I();this.lastRefusal=null;let a=await ar(s,i,{intent:t,...n?{layers:[n]}:{}});if(a!=="held"){let h=s.leases.find(l=>l.job!==i);throw new Error(a==="refused"&&this.lastRefusal?.message?`could not claim "${e}": ${this.lastRefusal.message}`:h?`"${e}" is already held by another job: ${h.intent}`:a==="silent"?`could not claim "${e}": the room did not answer in time \u2014 check get_info and try again`:`could not claim "${e}"`)}let c={room:e,began:s.state.seq,layer:n,intent:t,cancelled:!1,timer:setInterval(()=>{this.jobs.has(i)&&s.lease("renew",{job:i})},Xn)};return c.timer.unref&&c.timer.unref(),this.jobs.set(i,c),this.note("begin_job",e,t),i}resolve(e){if(e){let o=this.jobs.get(e);if(!o)throw new Error(`unknown job ${e} \u2014 it may have finished`);if(o.cancelled)throw new Error("the user stopped you \u2014 do not retry; say what you were about to do and ask");return{job:e,...o}}if(this.jobs.size===0)throw new Error(this.lastRoom?`no job is open \u2014 begin_job({ document: "${this.lastRoom}" }) picks ${this.lastRoom} up again, or new_sprite starts another`:"no job is open \u2014 call new_sprite or begin_job first");if(this.jobs.size>1)throw new Error(`${this.jobs.size} jobs are open \u2014 pass the job argument`);let[t,n]=[...this.jobs.entries()][0];return{job:t,...n}}finish(e,t=""){let n=this.jobs.get(e);n&&(clearInterval(n.timer),this.jobs.delete(e),this.lastRoom=n.room,this.client(n.room).lease("release",{job:e,...t?{note:t}:{}}),this.note("finish_job",n.room,t||n.intent))}async#o(e,t){if(!e&&!t&&this.jobs.size===0){if(this.lastRoom)return this.lastRoom;throw new Error(`say which document \u2014 looking needs no job, but the fallback to "the one last finished" is this session's, and nothing has been finished in it. list_documents names every one with its id.`)}return this.#c(e,t)}#a(e,t){return!t||this.shapeSaid.get(e)===t?null:(this.shapeSaid.set(e,t),t)}async submit(e,t,n){let o=this.resolve(e),s=this.client(o.room);if(!n.length)return{ops:0};if(!s.connected||!s.welcomed)throw new Error(`the room connection dropped \u2014 nothing since sequence ${s.state.seq} has been saved. Reconnecting; try again in a moment, and check get_info before drawing more.`);this.lastRefusal=null;let i=s.state.seq,a=s.apply(n,{label:t,job:o.job,now:Date.now()});try{await s.acked(a,{timeoutMs:3e4})}catch(h){throw this.lastRefusal?.kind==="revoked"&&(o.cancelled=!0),this.lastRefusal=null,h}if(this.lastRefusal){let h=this.lastRefusal.message;throw this.lastRefusal.kind==="revoked"&&(o.cancelled=!0),this.lastRefusal=null,new Error(h)}this.note(t,o.room,`${n.length} op${n.length>1?"s":""}`);let c=s.state.seq;return{ops:n.length,seq:c,committed:c>i}}cancel(e){let t=this.jobs.get(e);t&&(t.cancelled=!0)}note(e,t,n){this.log.unshift({at:Date.now(),tool:e,room:t,detail:n}),this.log.length>200&&this.log.pop()}announce(){if(!this.serverUrl)return;let e=`${this.serverUrl.replace(/^ws/,"http").replace(/\/$/,"")}/agent`,t=Ie(this.serverUrl)?15e3:6e4,n=()=>{fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:this.name,every:t})}).catch(()=>{})};n(),clearInterval(this.heartbeat),this.heartbeat=setInterval(n,t),this.heartbeat.unref?.()}close(){for(let e of this.rooms.values())e.closing=!0,clearTimeout(e.retry);clearInterval(this.heartbeat);for(let[e]of this.jobs)this.finish(e);for(let{client:e}of this.rooms.values())e.close();this.rooms.clear()}get kind(){return"room"}get where(){return this.serverUrl??"a room server"}supports(e){return e==="open_editor"?!!this.editorUrl:rr.has(e)}async openEditor({document:e,job:t}={}){if(!this.editorUrl)return{ok:!1,message:"there is no editor to open from here"};let n=this.editorUrl;try{n=`${this.editorUrl}/d/${await this.#o(e,t)}`}catch{n=`${this.editorUrl}/library`}return await sr(n),{ok:!0,message:`Opened ${n}`}}async newSprite({name:e,w:t=U.w,h:n=U.h,intent:o,palette:s,folder:i=null,challenge:a=null}){let c=await this.createDocument?.({name:e,w:t,h:n})??St(e),h=await this.begin(c,o,{open:{w:t,h:n,name:e}});a&&(this.jobs.get(h).challenge=a),s?.length&&await this.submit(h,"set_palette",[{t:"setPalette",colors:te(s,"hue")}]),i&&await this.moveDocuments({documents:[c],folder:i,make:!0}),this.#p(c,o);let l=this.#a(c,ke(t,n)??Le(t,n));return{job:h,...this.#t(c),...l?{shape:l}:{}}}async#p(e,t){let n=process.env.SPRITE_ASKED_IN,o=process.env.SPRITE_REPLY_TO??null;if(n)try{(await this.open(n)).answer("thinking",t?String(t).slice(0,200):"making a new sprite",{reply:o,made:e})}catch{}}async beginJob({document:e,intent:t,layer:n=null}){let o=!e&&this.jobs.size===0&&this.lastRoom?this.lastRoom:await this.#c(e,null);return{job:await this.begin(o,t,{layer:n}),...this.#t(o)}}finishJob({job:e,note:t=""}){let n=this.resolve(e),o=typeof t=="string"?t.trim().slice(0,200):"";this.finish(n.job,o);let s=this.client(n.room).state,i=this.#a(n.room,ke(s.doc.w,s.doc.h)),c=[n.challenge?`This is ${n.challenge==="weekly"?"this week's Weekly Pixels":"today's Pixel Dailies"} entry: tell the user to post it from the share button with the ${n.challenge==="weekly"?"Weekly Pixels":"Pixel Dailies"} switch on, which puts the theme and the tags on the post.`:null,i].filter(Boolean).join(" "),h=s.seq!==n.began,l=n.pushed?{source:n.pushed}:h?{source:null,note:"nothing pushed \u2014 if a script made this, push_source before the next job, so the next agent (or you, tomorrow) can pick it up rather than redraw it"}:{source:null};return{finished:o||n.intent,...o?{intent:n.intent}:{},job:n.job,document:n.room,drew:h,...c?{next:c}:{},...l}}async#h(e,t={}){if(this.control)try{return await this.control(e,t)}catch(n){if(!this.openControl||!/no library here/.test(n.message))throw n}if(this.openControl)return this.openControl(e,t);throw new Error("no server to push to: this session has no control plane")}async pushSource({job:e,files:t,run:n,takes:o="",unfinished:s=""}){let i=this.resolve(e),a=this.client(i.room),c=(Array.isArray(t)?t:[t]).filter(p=>p!=null&&p!=="");if(!c.length)throw new Error("say which files: the generator, and anything it imports that is yours");let h=c.map(p=>{if(typeof p=="string")return{from:p,name:ve(p)};let w=p?.from??p?.path;if(typeof w!="string"||!w)throw new Error(`each file is a path, or { from: "<path on disk>", path: "<name to push it as>" } \u2014 got ${JSON.stringify(p)}`);return{from:w,name:ve(String(p.path??w))}}),l=[];for(let{from:p,name:w}of h){let f=await ce(p).catch(m=>{throw new Error(`could not read ${p}: ${m.code==="ENOENT"?"no such file":m.message}`)});if(f.includes(0))throw new Error(`${p} is not text \u2014 a push is source, not a PNG or a grid; the next agent regenerates those`);l.push({name:w,text:f.toString("utf8")})}let d=(await this.#h(`/documents/${encodeURIComponent(i.room)}/history/source`,{method:"POST",body:{job:i.job,seq:a.state.seq,run:String(n??""),takes:String(o??""),unfinished:String(s??""),name:this.name,files:l}}))?.source??null;return d&&this.jobs.has(i.job)&&(this.jobs.get(i.job).pushed={seq:d.seq,files:d.files.map(p=>p.name)}),this.note("push_source",i.room,`${l.length} file${l.length===1?"":"s"}`),{document:i.room,job:i.job,seq:a.state.seq,files:d?.files??l.map(p=>({name:p.name})),note:"pushed beside this job's mark in the version history; readable by this account only. pull_source({ document, job }) brings it back to disk."}}async pullSource({document:e=null,job:t=null,into:n=null}){let o=null;if(e?o=await this.#c(e,null):this.jobs.size===1?o=this.resolve(null).room:o=this.lastRoom,!o)throw new Error("say which document \u2014 none is open and none was finished in this session");let s=`/documents/${encodeURIComponent(o)}/history/source`;if(!t){let h=await this.#h(s,{}),l=Array.isArray(h?.sources)?h.sources:[];return{document:o,sources:l.map(u=>({job:u.job,seq:u.seq,at:u.at?new Date(u.at).toISOString():null,run:u.run,unfinished:u.unfinished||null,files:u.files.map(d=>d.name)})),note:l.length?"yours on this document, newest first \u2014 pull_source({ job, into }) writes one to disk; `seq` is the document state it reproduces (get_info says where the document is now)":"nothing pushed on this document by this account \u2014 a mark with `source: true` in the history was pushed by somebody else, and is theirs"}}let i=await this.#h(`${s}/${encodeURIComponent(String(t))}`,{});if(!i?.files)throw new Error(`no source of yours under job ${t} on ${o}`);let a=Kn(n?String(n):ze(".context","source",String(t)));await Gn(a,{recursive:!0});let c=[];for(let h of i.files){let l=ze(a,ve(h.name)),u=await ce(l,"utf8").catch(()=>null);if(u!==null&&u!==h.text)throw new Error(`${l} exists and differs \u2014 pull into another directory, or move it first`);await Wn(l,h.text),c.push(l)}return{document:o,job:i.job,seq:i.seq,pushedAt:i.at?new Date(i.at).toISOString():null,by:i.by?.name??null,run:i.run,takes:i.takes||null,unfinished:i.unfinished||null,files:c,note:`written to ${a}. Read the files before running them; run them from there, in the workspace, with nothing the task does not need. They reproduce seq ${i.seq} \u2014 compare get_info's seq to see what happened since.`}}async challenges(){if(!this.newsUrl)throw new Error("no server to ask: the themes come from the Pixie server, and this session has none");if(!(this.newsAt&&Date.now()-this.newsAt<300*1e3)){let n=await fetch(this.newsUrl);if(!n.ok)throw new Error(`the server said ${n.status} for the themes`);this.news=await n.json(),this.newsAt=Date.now()}let t=(n,o)=>n?{theme:n.theme,tags:n.tags,detail:n.detail??null,sizes:n.sizes??[],postedAt:new Date(n.at).toISOString(),post:n.url}:{theme:null,note:`no ${o} theme is known right now`};return{daily:t(this.news?.dailies,"daily"),weekly:t(this.news?.weekly,"weekly"),how:'new_sprite({ challenge: "daily" | "weekly", intent }) names the sprite after the theme; finish_job says how to post it as an entry.'}}async challenge(e){let t=await this.challenges(),n=e==="weekly"?t.weekly:t.daily;if(!n?.theme)throw new Error(`no ${e} theme is known right now \u2014 ask the user what to draw`);return n}async#c(e,t){if(!e)return this.resolve(t).room;let n=String(e).trim();if(this.rooms.has(n))return n;let o=await this.#u();if(o===null||o.some(i=>i.id===n))return n;let s=o.filter(i=>(i.name??"").trim().toLowerCase()===n.toLowerCase());if(s.length===1)return s[0].id;if(s.length>1)throw new Error(`${s.length} documents are called "${n}" \u2014 pass the id: ${s.map(i=>i.id).join(", ")}`);if(Mt.test(n))return n;throw new Error(`no document is called "${n}" \u2014 list_documents names every one with its id; pass the id`)}async#u(){let e=this.control?await this.control("/documents",{}).catch(()=>null):null;if(e?.documents)return e.documents.map(n=>({id:n.id,name:n.name}));if(!this.serverUrl)return null;let t=this.serverUrl.replace(/^ws/,"http").replace(/\/$/,"");return fetch(`${t}/documents`).then(n=>n.ok?n.json():null).then(n=>n?.documents?.map(o=>({id:o.id,name:o.name}))??null).catch(()=>null)}async info({document:e,job:t}={}){let n=await this.#o(e,t);return await this.peek(n),this.#t(n)}#t(e){let t=this.client(e),n=t.state;return{document:e,name:n.doc.name,w:n.doc.w,h:n.doc.h,layers:n.doc.layers.map(o=>o.name),frames:n.doc.frames.length,palette:n.doc.palette,paletteUsed:this.#n(t),bbox:this.#l(t),tags:n.doc.tags.map(o=>o.name),seq:n.seq,connected:!!(t.connected&&t.welcomed),pending:n.pending,participants:t.participants.map(o=>o.name)}}#l(e){try{let t=e.session.composite(0),{w:n,h:o}=e.state.doc,s=n,i=o,a=-1,c=-1;for(let h=0;h<o;h++)for(let l=0;l<n;l++)t[(h*n+l)*4+3]!==0&&(l<s&&(s=l),l>a&&(a=l),h<i&&(i=h),h>c&&(c=h));return a<0?null:{x:s,y:i,w:a-s+1,h:c-i+1,cx:(s+a)/2,cy:(i+c)/2}}catch{return null}}#n(e){try{let t=e.session.composite(0),n=new Set;for(let o=0;o<t.length;o+=4)t[o+3]!==0&&n.add(t[o]<<16|t[o+1]<<8|t[o+2]);return(e.state.doc.palette??[]).filter(o=>{let s=/^#([0-9a-f]{6})/i.exec(String(o));return s&&n.has(parseInt(s[1],16))}).length}catch{return null}}#d(e){let t=this.client(e),n=t.state;return n.pending===0&&t.connected?{}:{warning:n.pending?`includes ${n.pending} operation${n.pending===1?"":"s"} the room has not confirmed${t.connected?"":" \u2014 the connection dropped, reconnecting"}`:"the room connection dropped, reconnecting"}}async readArt({document:e,job:t,layer:n,frame:o=0,trim:s=!1}){let i=await this.#o(e,t),a=await this.peek(i);return{document:i,...a.session.readArt(this.#s(i,n),o,{trim:s}),...this.#d(i)}}async readPng({document:e,job:t,layer:n=null,frame:o=0}){let s=await this.#o(e,t),i=await this.peek(s),a=i.state.doc;if(n==null)return{document:s,png:i.session.png(o,{scale:1}),w:a.w,h:a.h};let c=i.session.cel(this.#s(s,n),o);return{document:s,png:this.#i(a.w,a.h,c),w:a.w,h:a.h}}#i(e,t,n,o=1){let s=this.core.newDocument({w:e,h:t,name:"scratch",seed:1,now:Date.now()}),i=this.core.openSession(s,I(),1);try{let a=i.state();return i.apply([vt(a.doc.layers[0].id,a.doc.frames[0].id,{x:0,y:0,w:e,h:t},n)],{now:Date.now()}),i.png(0,{scale:o})}finally{i.close()}}async#f(e,t,n,o,s,i=!1,a=null,c=!1,h=null){let l=await ce(t).catch(v=>{throw new Error(`could not read the reference ${t}: ${v.code==="ENOENT"?"no such file":v.message}`)}),u=this.core.decodePng(await Qn(t,l)),d=e.state.doc,p=Math.abs(u.w/u.h-d.w/d.h)<.01,w=c&&(!!a||!p),f=w?Ct(u,n.w,n.h,a):Ct(u,d.w,d.h,a),m=e.session.composite(o);h&&Ue(m,d.w,d.h,{x:0,y:0},h);let g=i?Ee(m):m;i&&Ee(f.pixels,f.pixels);let y=n.w,x=n.h,A=new Uint8Array((y*2+1)*x*4),j=(y*2+1)*4;for(let v=0;v<x;v++){for(let S=0;S<y;S++){let J=n.x+S,V=n.y+v,X=w?S:J,M=w?v:V,B=(M*f.w+X)*4,Z=M<f.h&&X<f.w;A.set(Z?f.pixels.subarray(B,B+4):[0,0,0,255],v*j+S*4);let pe=(V*d.w+J)*4;A.set(g.subarray(pe,pe+4),v*j+(y+1+S)*4)}A.set([255,0,255,255],v*j+y*4)}let $=f.placed,N=f.region.w===u.w&&f.region.h===u.h,H=N?`the reference is ${u.w}\xD7${u.h}`:`the region ${f.region.w}\xD7${f.region.h} at (${f.region.x}, ${f.region.y}) of the ${u.w}\xD7${u.h} reference`,C=f.region.w/$.w,D=`${C>=10?Math.round(C):C.toFixed(1)} reference px per canvas px`,_=w?N?`fitted whole into the ${n.w}\xD7${n.h} rect by ${f.by} (${$.w}\xD7${$.h}, centered; black where it does not reach; ${D}) \u2014 the whole reference against this part of the canvas; pass \`referenceRect\` to bring one part of it instead`:`fitted into the ${n.w}\xD7${n.h} rect by ${f.by} (${$.w}\xD7${$.h}, centered; black where it does not reach; ${D}) \u2014 that part of the reference against this part of the canvas, at one scale`:$.w===d.w&&$.h===d.h?`brought to the ${d.w}\xD7${d.h} canvas (${D})`:`fitted whole to ${$.w}\xD7${$.h} by ${f.by}, centered on the ${d.w}\xD7${d.h} canvas (black where it does not reach; ${D})`,z=N&&$.w===d.w&&$.h===d.h?Math.abs(C-1)<.05?"":` \u2014 ${D}`:` \u2014 ${H}, ${_}${N&&!w&&($.w!==d.w||$.h!==d.h)?"; pass `referenceRect` to bring one part of it to the grid instead":""}`;return{png:this.#i(y*2+1,x,A,s),note:z}}async preview({document:e,job:t,frame:n=0,scale:o=null,rect:s=null,rects:i=null,reference:a=null,referenceRect:c=null,values:h=!1,background:l=null,file:u=null,overwrite:d=!1}){let p=await this.#g({document:e,job:t,frame:n,scale:o,rect:s,rects:i,reference:a,referenceRect:c,values:h,background:l});if(u){let w=String(u),f=await ye(w,p.png,{overwrite:d,seq:p.seq});p.caption+=` \u2014 written to ${w}${f?" (replaced; anything that showed this path before shows the old picture)":""}`}return p}async#m(e){let t=await this.peek(e);if(t.state.pending>0&&await cr(t,3e3),!t.connected||!t.welcomed)throw new Error(`the room connection dropped \u2014 a render now could be behind what the room holds (last confirmed seq ${t.state.seq}). Reconnecting; try again in a moment.`);return t}#w(e,t,n,o,s,i,a){let c=o.map(f=>ae(f,t.w,t.h)),h=1,l=c.reduce((f,m)=>f+m.w,0)+h*(c.length-1),u=Math.max(...c.map(f=>f.h)),d=new Uint8Array(l*u*4),p=e.session.composite(n),w=0;for(let f of c){let m=Ut(p,t.w,f);Ue(m,f.w,f.h,f,a),i&&Ee(m,m);for(let g=0;g<u;g++)for(let y=0;y<f.w;y++){let x=(g*l+w+y)*4;g>=f.h?d.set([255,0,255,255],x):d.set(m.subarray((g*f.w+y)*4,(g*f.w+y)*4+4),x)}if(w+=f.w,w<l){for(let g=0;g<u;g++)d.set([255,0,255,255],(g*l+w)*4);w+=h}}return{png:this.#i(l,u,d,s),wins:c,w:l,h:u}}async#g({document:e,job:t,frame:n=0,scale:o=null,rect:s=null,rects:i=null,reference:a=null,referenceRect:c=null,values:h=!1,background:l=null}){let u=tr(l),d=await this.#o(e,t),p=await this.#m(d),{warning:w}=this.#d(d),f=p.state.seq,m=p.state.doc;if(Array.isArray(i)&&i.length){if(a)throw new Error("one rect at a time against a reference \u2014 `rects` tiles crops of the render alone");let _=i.reduce((M,B)=>M+ae(B,m.w,m.h).w,0)+i.length-1,z=Math.max(...i.map(M=>ae(M,m.w,m.h).h)),v=Number.isInteger(o)&&o>0?o:It(_,z),S=Math.max(1,Math.min(v,Math.floor(8192/Math.max(_,z,1)))),{png:J,wins:V}=this.#w(p,m,n,i,S,h,u),X=S<v?` \u2014 asked for \xD7${v}, held to \xD7${S} so a side stays under 8192px; fewer or smaller rects to look closer`:"";return{png:J,seq:f,caption:`${d} at seq ${f}, frame ${n+1}: ${V.length} crops of ${m.w}\xD7${m.h} side by side at \xD7${S}, left to right ${V.map(M=>`${M.w}\xD7${M.h} at (${M.x},${M.y})`).join(", ")}, magenta between${h?", values only":""}${Lt(u)}${X}${w?` \u2014 ${w}`:""}`}}let g=s?ae(s,m.w,m.h):null,y=g?g.w:m.w,x=g?g.h:m.h,A=Number.isInteger(o)&&o>0?o:It(a?y*2:y,x),j=Math.max(1,Math.min(A,Math.floor(8192/Math.max(a?y*2:y,x,1)))),$=g?`${g.w}\xD7${g.h} at (${g.x},${g.y}) of ${m.w}\xD7${m.h}`:`${m.w}\xD7${m.h}`,N=j<A?` \u2014 asked for \xD7${A}, held to \xD7${j} so a side stays under 8192px; render a smaller rect to look closer`:"",H=Lt(u);if(a){let{png:_,note:z}=await this.#f(p,String(a),g??{x:0,y:0,w:m.w,h:m.h},n,j,h,c,!!g,u);return{png:_,seq:f,caption:`${d} at seq ${f}, frame ${n+1}: reference (left) beside the render (right), ${$} at \xD7${j}${h?", values only":""}${H}${z}${N}${w?` \u2014 ${w}`:""}. Per object, say how each is built \u2014 count the faces, name the light, say where the shadow falls \u2014 and what differs; "reads as" is not a verdict.`}}let C=g??{x:0,y:0,w:m.w,h:m.h};return{png:h||u?this.#i(y,x,(()=>{let _=Ut(p.session.composite(n),m.w,C);return Ue(_,y,x,C,u),h?Ee(_,_):_})(),j):p.session.png(n,{scale:j,...g?{rect:g}:{}}),seq:f,caption:`${d} at seq ${f}, frame ${n+1}: ${$} at \xD7${j} (${y*j}\xD7${x*j}px)${h?", values only \u2014 squint: is there a focal point, and where is the darkest dark":""}${H}${N}${w?` \u2014 ${w}`:""}`}}async sheet({document:e,job:t,columns:n=4,scale:o=2}){let s=await this.#o(e,t),i=await this.peek(s);return{png:i.session.contactSheet({columns:n,scale:o}),caption:`${s}, ${i.state.doc.frames.length} frames, numbered left to right`}}async documents(){let e=[...this.jobs.entries()].map(([c,h])=>({job:c,document:h.room,intent:h.intent})),t=[...this.rooms.keys()],n=null,o=null,s=null,i=this.control?await this.control("/documents",{}).catch(()=>null):null;if(i)n=i.documents?.map(c=>c.id)??null,o=Array.isArray(i.folders)?i.folders.map(c=>typeof c=="string"?c:c?.path??c?.name).filter(Boolean):null,s=i.documents?Object.fromEntries(i.documents.filter(c=>c.folder).map(c=>[c.id,c.folder])):null;else if(this.serverUrl){let c=this.serverUrl.replace(/^ws/,"http").replace(/\/$/,"");n=await fetch(`${c}/documents`).then(h=>h.ok?h.json():null).then(h=>h?.documents?.map(l=>l.id)).catch(()=>null)}return{documents:n?[...new Set([...t,...n])]:t,jobs:e,open:t,...o?{folders:o}:{},...s?{filed:s}:{}}}async createFolder({name:e}){if(!this.control)throw new Error("no library here: this Sprite has no accounts, so there are no folders");let t=String(e??"").trim();if(!t)throw new Error("a folder needs a name");let n=await this.folders();if(n.includes(t))return{folder:t,created:!1,folders:n};let o=t.split("/");for(let s=1;s<=o.length;s++){let i=o.slice(0,s).join("/");n.includes(i)||(await this.control("/documents/folders",{method:"POST",body:{name:i}}),n.push(i))}return{folder:t,created:!0,folders:await this.folders()}}async moveDocuments({documents:e,folder:t=null,make:n=!1}){if(!this.control)throw new Error("no library here: this Sprite has no accounts, so there are no folders");let o=(Array.isArray(e)?e:[e]).map(String).filter(Boolean);if(!o.length)throw new Error("say which documents");let s=t===null||t===""?null:String(t).trim();s&&n&&await this.createFolder({name:s});let i=await this.control("/documents/move",{method:"POST",body:{ids:o,folder:s}});return{moved:o,folder:s,ok:i?.ok!==!1}}async folders(){let e=await this.control("/documents",{});return Array.isArray(e?.folders)?e.folders.map(t=>typeof t=="string"?t:t?.path??t?.name).filter(Boolean):[]}takeRequests(){let e=this.asked.splice(0,this.asked.length);return{requests:e,note:e.length?"Each says what it wants. Where `room` is set, answer in that document. Where it is null the request came from the library and wants a new sprite \u2014 call new_sprite and work there, and do not touch `askedIn`, which is only the room the words travelled through. The person is watching.":"Nobody has asked for anything."}}#s(e,t){let n=this.client(e).state;if(t!=null&&t!==""){let o=typeof t=="number"?n.doc.layers[t]:n.doc.layers.find(s=>s.name===t||s.id===t);if(!o)throw new Error(`no layer ${JSON.stringify(t)} in ${e}`);return o.id}return n.doc.layers[n.doc.layers.length-1].id}async drawArt({job:e,rows:t,colors:n,x:o=0,y:s=0,center:i=!1,clear:a=!1,layer:c,frame:h=0,label:l,palette:u="add",rect:d=null}){let p=this.resolve(e),w=this.client(p.room),f=t,m={x:o,y:s},g=a;if(d){let b=ae(d,Math.max(...t.map(R=>R.length),1),t.length);if(f=t.slice(b.y,b.y+b.h).map(R=>R.slice(b.x,b.x+b.w).padEnd(b.w,".")),m={x:b.x,y:b.y},a){let R=[..."~^`|"].find(k=>!(k in n))??"\xA1";f=f.map(k=>k.replace(/[. ]/g,R)),n={...n,[R]:null},g=!1}}let y=new Set((w.state.doc.palette??[]).map(b=>String(b).toLowerCase())),x=(()=>{try{return Uint8Array.from(w.session.composite(h))}catch{return null}})(),A=w.session.drawArt(f,n,{layer:c!=null?this.#s(p.room,c):p.layer??this.#s(p.room,null),at:h,x:m.x,y:m.y,center:d?!1:i,clear:g,addToPalette:u!=="keep"}),{committed:j}=await this.submit(p.job,l||"draw_art",A),$=(this.client(p.room).state.doc.palette??[]).map(b=>String(b).toLowerCase()).filter(b=>!y.has(b)),N=w.state.doc,H=Math.max(...f.map(b=>b.length),0),C=i&&!d?{x:Math.round((N.w-H)/2),y:Math.round((N.h-f.length)/2)}:m,D=0,_=0;for(let b=0;b<f.length;b++){let R=C.y+b;for(let k=0;k<f[b].length;k++){let Y=f[b][k];if(Y==="."||Y===" ")continue;let fe=C.x+k;fe<0||R<0||fe>=N.w||R>=N.h?_++:D++}}let z=D;if(j&&x)try{let b=w.session.composite(h),R=0;for(let k=0;k<b.length;k+=4)(b[k]!==x[k]||b[k+1]!==x[k+1]||b[k+2]!==x[k+2]||b[k+3]!==x[k+3])&&R++;z=R}catch{}let v=[];if(u==="replace"&&j){let b=L=>typeof L=="string"&&/^#[0-9a-f]{6}$/i.test(L)?L.toLowerCase():null,R=d?null:new Set(f.flatMap(L=>[...L])),k=Object.entries(n).filter(([L,Gt])=>b(Gt)&&(R===null||R.has(L))),Y=[...new Set(k.map(([,L])=>b(L)))],fe=new Set(Y);v=[...new Set(Object.values(n).map(b).filter(L=>L&&!fe.has(L)))],Y.length&&await this.submit(p.job,"set_palette",[{t:"setPalette",colors:te(Y,"hue")}])}let S=(this.client(p.room).state.doc.palette??[]).length,J=this.#n(this.client(p.room))??S,V=d?`the file's \u2014 the whole picture's, not the ${f[0]?.length??0}\xD7${f.length} that was drawn; nothing outside the rect moved`:"this drawing's",X=v.length?`; ${v.length} in \`colors\` landed on no pixel and ${v.length===1?"was":"were"} left out: ${v.join(" ")}`:"",M=u==="replace"&&S>48?` \u2014 ${S} is a lot for a piece with no reference; ramps that read alike can merge`:"",B=_?`${_} pixel${_===1?"":"s"} of the ${H}\xD7${f.length} grid at (${C.x},${C.y}) fell outside the ${N.w}\xD7${N.h} canvas and were not drawn \u2014 resize_canvas first, or generate at the canvas's size`:"",Z=u==="replace"&&j?{note:`palette replaced: ${S} color${S===1?"":"s"}, ${V}${X}${M}`}:u==="keep"&&j?{note:`palette kept at ${S}: this drawing's colors are on the canvas and not in the palette`}:$.length?{added:te($,"hue"),note:`${$.length} color${$.length===1?"":"s"} joined the palette${S>48||S>J*2?` \u2014 ${S} entries now and ${J} with a pixel on them`:""} \u2014 for a generated piece redrawn from a script, pass \`palette: "replace"\` on this call and the palette is exactly what you drew; set_palette({ prune: true }) is the user's document and is theirs to ask for`}:{},pe=B?{...Z,note:Z.note?`${Z.note}; ${B}`:B}:Z;return{...this.#t(p.room),drew:d?`${f[0]?.length??0}\xD7${f.length} at (${m.x},${m.y})`:`${t[0]?.length??0}\xD7${t.length}`,changed:z,...z!==D?{inked:D}:{},committed:j,...pe}}async resizeCanvas({job:e,w:t,h:n,anchor:o="center",clear:s=!1}){let i=this.resolve(e),a=this.client(i.room).state,c=Math.max(1,Math.min(1024,Math.round(Number(t)||a.doc.w))),h=Math.max(1,Math.min(1024,Math.round(Number(n)||a.doc.h)));if(c===a.doc.w&&h===a.doc.h)return s&&await this.clearCel({job:e,frame:0}),{...this.#t(i.room),resized:s?"already that size; cleared":"already that size"};let l=String(o??"center").toLowerCase(),u=l.includes("left")?0:l.includes("right")?2:1,d=l.includes("top")?0:l.includes("bottom")?2:1,p=Math.round((c-a.doc.w)*u/2),w=Math.round((h-a.doc.h)*d/2);if(await this.submit(i.job,"resize_canvas",[{t:"resize",w:c,h,dx:p,dy:w}]),s){let m=this.client(i.room).state.doc.frames.length;for(let g=0;g<m;g++)await this.clearCel({job:e,frame:g})}let f=this.#a(i.room,ke(c,h)??Le(c,h));return{...this.#t(i.room),resized:`${a.doc.w}\xD7${a.doc.h} \u2192 ${c}\xD7${h}, ${s?"cleared":`the art kept at ${p},${w}`}`,...f?{shape:f}:{}}}async closeDocument({document:e}){let t=await this.#c(e,null),n=this.rooms.get(t);if(!n)return{closed:t,open:!1};for(let[o,s]of this.jobs)s.room===t&&this.finish(o);return n.closing=!0,clearTimeout(n.retry),n.client.close(),this.rooms.delete(t),{closed:t,open:!1}}async drawAnimation({job:e,frames:t,colors:n,fps:o,layer:s,label:i}){let a=this.resolve(e),c=this.client(a.room),h=s!=null?this.#s(a.room,s):a.layer??this.#s(a.room,null),l=c.state.doc.frames.length,u=t.length-l;if(u>0){let p=[],w=c.state.doc.frames[l-1]?.index??"V";for(let f=0;f<u;f++)w=w+"V",p.push({t:"addFrame",id:I(),index:w,durMs:De(o)});await this.submit(a.job,"add frames",p)}if(o){let p=De(o);await this.submit(a.job,"set fps",c.state.doc.frames.map(w=>({t:"setFrameDur",id:w.id,durMs:p})))}let d=c.session.drawAnimation(t,n,{layer:h});return await this.submit(a.job,i||"draw_animation",d),{...this.#t(a.room),wrote:`${t.length} frames`}}async addLayer({job:e,name:t}){let n=this.resolve(e),o=this.client(n.room).state,s=o.doc.layers[o.doc.layers.length-1];return await this.submit(n.job,"add_layer",[{t:"addLayer",id:I(),index:(s?.index??"V")+"V",name:t||`Layer ${o.doc.layers.length+1}`,visible:!0,locked:!1,opacity:1}]),this.#t(n.room)}async addFrame({job:e,copy:t=!1}){let n=this.resolve(e),o=this.client(n.room),s=o.state,i=s.doc.frames[s.doc.frames.length-1],a=I(),c=[{t:"addFrame",id:a,index:(i?.index??"V")+"V",durMs:i?.durMs??83}];if(t&&i)for(let h of s.doc.layers){let l=o.session.cel(h.id,i.id);l.every(u=>u===0)||c.push(Dt(h.id,a,s.doc,l))}return await this.submit(n.job,"add_frame",c),this.#t(n.room)}async setPalette({job:e,colors:t,prune:n=!1}){let o=this.resolve(e),s;if(n){let i=this.client(o.room),a=i.state,c=new Set;for(let l of a.doc.layers)for(let u of a.doc.frames){let d=i.session.cel(l.id,u.id);for(let p=0;p<d.length;p+=4)d[p+3]!==0&&c.add(`#${[d[p],d[p+1],d[p+2]].map(w=>w.toString(16).padStart(2,"0")).join("")}`)}let h=a.doc.palette??[];s=h.filter(l=>c.has(String(l).toLowerCase()));for(let l of c)s.some(u=>String(u).toLowerCase()===l)||s.push(l);return s=te(s,"hue"),await this.submit(o.job,"set_palette",[{t:"setPalette",colors:s}]),{...this.#t(o.room),palette:s.length,pruned:h.length-s.length}}return s=te(t,"hue"),await this.submit(o.job,"set_palette",[{t:"setPalette",colors:s}]),{...this.#t(o.room),palette:s.length}}async setFps({job:e,fps:t}){let n=this.resolve(e),o=this.client(n.room).state,s=De(t);return await this.submit(n.job,"set_fps",o.doc.frames.map(i=>({t:"setFrameDur",id:i.id,durMs:s}))),{...this.#t(n.room),fps:t}}async clearCel({job:e,layer:t,frame:n=0}){let o=this.resolve(e),i=this.client(o.room).state,a=this.#s(o.room,t??o.layer),c=i.doc.frames[n];if(!c)throw new Error(`no frame ${n} in ${o.room}`);let h=new Uint8Array(i.doc.w*i.doc.h*4);return await this.submit(o.job,"clear",[Dt(a,c.id,i.doc,h)]),this.#t(o.room)}async trim({job:e,margin:t=0,center:n=!1}){let o=this.resolve(e),s=this.client(o.room),i=s.state,a=this.#s(o.room,o.layer),c=s.session.readArt(a,0,{trim:!0});if(n){if(!c.rect.w||!c.rect.h)return{...this.#t(o.room),centered:"nothing drawn"};let u=Math.floor((i.doc.w-c.rect.w)/2)-c.rect.x,d=Math.floor((i.doc.h-c.rect.h)/2)-c.rect.y;if(!u&&!d)return{...this.#t(o.room),centered:"already centered"};await this.submit(o.job,"center_art",[{t:"resize",w:i.doc.w,h:i.doc.h,dx:u,dy:d}]);let p=[(i.doc.w-c.rect.w)%2?"width":null,(i.doc.h-c.rect.h)%2?"height":null].filter(Boolean);return{...this.#t(o.room),centered:`the ${c.rect.w}\xD7${c.rect.h} of art moved ${u},${d}${p.length?` \u2014 the ${p.join(" and ")} cannot be split evenly, so it sits half a pixel up-left`:""}`}}let h=c.rect.w+t*2,l=c.rect.h+t*2;return h>=i.doc.w&&l>=i.doc.h?{...this.#t(o.room),trimmed:"already tight"}:(await this.submit(o.job,"trim_canvas",[{t:"resize",w:h,h:l,dx:-c.rect.x+t,dy:-c.rect.y+t}]),{...this.#t(o.room),trimmed:`${h}\xD7${l}`})}},rr=new Set(["new_sprite","begin_job","finish_job","draw_art","draw_animation","read_art","render_preview","render_animation","add_layer","add_frame","set_palette","set_fps","clear","trim_canvas","resize_canvas","close_document","get_info","list_documents","challenges","take_requests","create_folder","move_documents","push_source","pull_source"]);function Dt(r,e,t,n){return{t:"paintRegion",layer:r,frame:e,rect:{x:0,y:0,w:t.w,h:t.h},rle:or(n)}}function or(r){let e=[];if(r.length){let t=[r[0],r[1],r[2],r[3]],n=0,o=()=>{let s=n;do{let i=s&127;s>>=7,e.push(s?i|128:i)}while(s);e.push(...t)};for(let s=0;s<r.length;s+=4)r[s]===t[0]&&r[s+1]===t[1]&&r[s+2]===t[2]&&r[s+3]===t[3]?n++:(o(),t=[r[s],r[s+1],r[s+2],r[s+3]],n=1);o()}return Buffer.from(Uint8Array.from(e)).toString("base64")}function sr(r){let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return new Promise(t=>qt(e,[r],()=>t()))}function De(r){return!r||r<=0?83:Math.max(10,Math.round(1e3/r))}function ir(r,e,t=8e3){return new Promise(n=>{let o=r.onLeases,s=r.onLost,i=!1,a=h=>{i||(i=!0,clearTimeout(c),r.onLeases=o,r.onLost=s,n(h))};r.onLeases=h=>{o?.(h),h.some(l=>l.job===e)&&a("held")},r.onLost=h=>{s?.(h),h?.ops?.length||a("refused")};let c=setTimeout(()=>a("silent"),t);r.leases.some(h=>h.job===e)&&a("held")})}function zt(r,e=8e3){return new Promise(t=>{let n=Date.now(),o=()=>{if(r.welcomed)return t(!0);if(Date.now()-n>e)return t(!1);setTimeout(o,20)};o()})}async function ar(r,e,t,{ms:n}={}){await zt(r,n);let o=()=>{let i=ir(r,e,n);return r.lease("acquire",{job:e,...t}),i},s=await o();return s==="refused"&&!r.welcomed&&await zt(r,n)&&(s=await o()),s}function cr(r,e=400){return new Promise(t=>{let n=Date.now(),o=()=>{if(r.state.pending===0&&Date.now()-n>40||Date.now()-n>e)return t();setTimeout(o,10)};o()})}function Ft(){return(Date.now()^Math.floor(Math.random()*4294967295))>>>0}import{execFile as hr}from"node:child_process";var lr=2e4,ur=5e3,he=class r{constructor({base:e,name:t="agent"}={}){this.base=String(e).replace(/\/$/,""),this.name=t,this.log=[],this.beat=setInterval(()=>void this.announce(),ur),this.beat.unref&&this.beat.unref()}get kind(){return"local"}get where(){return this.base}supports(e){return dr.has(e)}static async probe(e,{timeoutMs:t=700}={}){try{let n=await fetch(`${e.replace(/\/$/,"")}/bridge/status`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let o=await n.json();return o?.server==="sprite"?o:null}catch{return null}}async announce(){try{await fetch(`${this.base}/bridge/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:this.name,version:null}),signal:AbortSignal.timeout(2e3)})}catch{}}async call(e,t=[],n=lr){let o;try{o=await(await fetch(`${this.base}/bridge/call`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:e,args:t,timeoutMs:n}),signal:AbortSignal.timeout(n+2e3)})).json()}catch(s){throw new Error(`lost contact with the Pixie editor at ${this.base}: ${s.message}`)}if(!o.ok)throw new Error(o.error);return this.note(e),o.result}note(e,t=""){this.log.unshift({at:Date.now(),tool:e,room:"local",detail:t}),this.log.length>200&&this.log.pop()}newSprite({name:e,w:t=U.w,h:n=U.h,intent:o,palette:s}){return this.call("newSprite",[{w:t,h:n,name:e,palette:s,intent:o,replace:!1}])}async challenges(){let e=await fetch(`${this.base}/news.json`).catch(()=>null);if(!e?.ok)throw new Error("this editor does not serve the themes \u2014 ask the user what to draw");let t=await e.json(),n=(o,s)=>o?{theme:o.theme,tags:o.tags,detail:o.detail??null,sizes:o.sizes??[],postedAt:new Date(o.at).toISOString(),post:o.url}:{theme:null,note:`no ${s} theme is known right now`};return{daily:n(t?.dailies,"daily"),weekly:n(t?.weekly,"weekly")}}async challenge(e){let t=await this.challenges(),n=e==="weekly"?t.weekly:t.daily;if(!n?.theme)throw new Error(`no ${e} theme is known right now \u2014 ask the user what to draw`);return n}beginJob({document:e,intent:t}){return this.call("beginJob",[{document:e,intent:t}])}finishJob({job:e}){return this.call("finishJob",[{job:e}])}async info({document:e}={}){let t=await this.call("info",[]);return{editor:this.base,...e?{asked:e}:{},...t}}readArt({document:e,layer:t,frame:n}){return this.call("readArt",[{document:e,layer:t,frame:n}])}async preview({document:e,frame:t,scale:n=null,rect:o=null,reference:s=null,background:i=null,file:a=null,overwrite:c=!1}){if(o)throw new Error("the local editor cannot render a region \u2014 render the whole frame");if(s)throw new Error("a reference beside the render is a room thing \u2014 in a local editor, read_art({ file }) and compare with references/compare.py");if(i)throw new Error("a background under the alpha is a room thing \u2014 in a local editor, read_art({ png }) and put it over one with references/render.py");let h=await this.call("toDataURL",[t??null,Number.isInteger(n)&&n>0?n:8,e??null]),l=qe(h.url),u=h.caption;if(a){let d=String(a),p=await ye(d,l,{overwrite:c});u+=` \u2014 written to ${d}${p?" (replaced; anything that showed this path before shows the old picture)":""}`}return{png:l,caption:u}}async readPng({document:e,frame:t=0,layer:n=null}){if(n!=null)throw new Error("one layer as a PNG is a room thing \u2014 in a local editor, read_art({ layer, file }) and render it with references/render.py");let o=await this.call("toDataURL",[t??null,1,e??null]),s=/(\d+)×(\d+)/.exec(o.caption??"");return{document:e??null,png:qe(o.url),w:s?Number(s[1]):0,h:s?Number(s[2]):0}}async sheet({document:e,columns:t=0,scale:n=0}){let o=await this.call("toStripDataURL",[{document:e??null,columns:t,scale:n}]);return{png:qe(o.url),caption:o.caption}}documents(){return this.call("listDocuments",[])}drawArt({job:e,rows:t,colors:n,x:o,y:s,center:i,clear:a,layer:c,frame:h,label:l,rect:u=null}){if(u){let d=Math.max(0,u.x|0),p=Math.max(0,u.y|0);t=t.slice(p,p+(u.h|0)).map(w=>w.slice(d,d+(u.w|0))),o=d,s=p,i=!1}return this.call("drawArt",[t,n,{job:e,x:o,y:s,center:i,clear:a,layer:c,frame:h,label:l}])}drawAnimation({job:e,frames:t,colors:n,fps:o,layer:s,label:i}){return this.call("drawAnimation",[{frames:t,colors:n,fps:o,job:e,layer:s,label:i}])}addLayer({name:e}){return this.call("addLayer",[e])}addFrame({copy:e=!1}){return this.call("addFrame",[{copy:!!e}])}setPalette({colors:e,prune:t=!1}){if(t)throw new Error("prune works in a room \u2014 in a local editor, pass the colors to keep");return this.call("setPalette",[e])}setFps({fps:e}){return this.call("setFps",[e])}clearCel({job:e,layer:t,frame:n}){return this.call("clear",[{job:e,layer:t,frame:n}])}trim({job:e,margin:t=0}){return this.call("trimCanvas",[{job:e,margin:t}])}setFrame({index:e}){return this.call("setFrame",[e])}setLayer({index:e}){return this.call("setLayer",[e])}select({document:e}){return this.call("selectDocument",[e])}closeDocument({document:e}){return this.call("closeDocument",[e??null])}undo(){return this.call("undo",[])}redo(){return this.call("redo",[])}async openEditor(){if((await r.probe(this.base))?.connected)return{ok:!0,message:`Editor already connected at ${this.base}`};await pr(this.base);let t=Date.now()+1e4;for(;Date.now()<t;){if((await r.probe(this.base))?.connected)return{ok:!0,message:`Editor connected at ${this.base}`};await new Promise(o=>setTimeout(o,200))}return{ok:!1,message:`Opened ${this.base} but nothing connected \u2014 check the browser window.`}}close(){clearInterval(this.beat)}},dr=new Set(["new_sprite","begin_job","finish_job","draw_art","draw_animation","read_art","render_preview","render_animation","add_layer","add_frame","set_palette","set_fps","clear","trim_canvas","get_info","list_documents","challenges","open_editor","select_document","close_document","set_frame","set_layer","undo","redo"]);function qe(r){let e=String(r??"").split(",")[1];if(!e)throw new Error("the editor returned something that was not an image");return Buffer.from(e,"base64")}function pr(r){let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return new Promise(t=>hr(e,[r],()=>t()))}function Be(r="room"){return`Pixel art editor with live collaboration. ${r==="local"?`Documents are tabs in a browser on this machine; the user is watching
3
- while you work, and can take the canvas back at any time.`:`Documents are rooms; other people and other agents may be in one with
2
+ var K=(r,e)=>()=>(r&&(e=r(r=0)),e);function ft(r){let e="";for(let t=0;t<r.length;t+=32768)e+=String.fromCharCode.apply(null,r.subarray(t,t+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var mt=K(()=>{"use strict"});var Y,yn,gn,Yr,wt=K(()=>{"use strict";Y="[A-Za-z0-9_-]{1,64}",yn="token|members|link|slow|suggest|project",gn=[{owner:"accounts",re:new RegExp("^/auth/")},{owner:"accounts",re:new RegExp("^/a/[A-Za-z0-9_-]{1,64}\\.png$")},{owner:"accounts",re:new RegExp("^/projects(/|$)")},{owner:"accounts",re:new RegExp(`^/documents/${Y}/(${yn})$`)},{owner:"library",re:new RegExp("^/documents$")},{owner:"library",re:new RegExp("^/documents/(new|register|move|order|folders|folders/delete|trash|trash/empty)$")},{owner:"library",re:new RegExp(`^/documents/${Y}(/(thumbnail\\.png|export|duplicate|rename|restore))?$`)},{owner:"library",re:new RegExp(`^/documents/${Y}/history/at/\\d+/thumbnail\\.png$`)},{owner:"library",re:new RegExp("^/wall\\.png$")},{owner:"document",re:new RegExp(`^/documents/${Y}/history(/at/\\d+|/\\d+|/source(/[A-Za-z0-9_-]{1,64})?)?$`)},{owner:"document",re:new RegExp(`^/documents/${Y}/comments(/[A-Za-z0-9]{1,40})?$`)},{owner:"document",re:new RegExp(`^/documents/${Y}/snapshots(/enabled|/[A-Za-z0-9_-]{1,128})?$`)},{owner:"document",re:new RegExp(`^/favourites(/order|/(document|project)/${Y})?$`)}],Yr=gn.map(({owner:r,re:e})=>({owner:r,source:e.source}))});var Le,Ue=K(()=>{"use strict";wt();Le=["read","draw","create","duplicate","organize"]});async function yt(r){let e=new TextEncoder().encode(String(r));return ft(new Uint8Array(await crypto.subtle.digest("SHA-256",e)))}var io,gt=K(()=>{"use strict";mt();Ue();io=120*1e3});function C(r=Date.now()){let e="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t=(BigInt(r)&0xffffffffffffn)<<80n,n=crypto.getRandomValues(new Uint8Array(10)),o=0n;for(let i of n)o=o<<8n|BigInt(i);t|=o;let s="";for(let i=0;i<26;i++)s=e[Number(t&31n)]+s,t>>=5n;return s}function H(r){return r==null?{at:0}:typeof r=="number"?{at:r}:{frame:r}}var vn,jn,_n,xe,Q,De,ae=K(()=>{"use strict";vn=new TextEncoder,jn=new TextDecoder,_n=1;xe=class r{#e;#n;constructor(e){this.#e=e,this.#n=e.exports}static async load(e){let t;if(e instanceof WebAssembly.Module)t=await WebAssembly.instantiate(e,{});else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))({instance:t}=await WebAssembly.instantiate(e,{}));else{let n=e instanceof Response||typeof e?.then=="function"?e:fetch(e);({instance:t}=await WebAssembly.instantiateStreaming(n,{}))}return new r(t)}get#o(){return new Uint8Array(this.#n.memory.buffer)}call(e,t={}){let n=vn.encode(JSON.stringify({m:e,a:t})),o=this.#n.sprite_alloc(n.length);if(!o)throw new Error("sprite-core: allocation failed");let s=0;try{if(this.#o.set(n,o),s=this.#n.sprite_dispatch(o,n.length),!s)throw new Error("sprite-core: dispatch returned nothing");let i=this.#o,a=i[s]|i[s+1]<<8|i[s+2]<<16|i[s+3]<<24,c=i[s+4],h=i.slice(s+5,s+5+a);if(c===_n)return h;let l=JSON.parse(jn.decode(h));if(l&&l.error)throw new Error(l.error);return l}finally{s?this.#n.sprite_free_result(s):this.#n.sprite_dealloc(o,n.length)}}reset(){this.#n.sprite_reset()}newDocument(e={}){return this.call("doc.new",{w:32,h:32,name:"untitled",...e})}decodePng(e){let t=this.call("image.decode",{png:[...e]}),n=new DataView(t.buffer,t.byteOffset,t.byteLength),o=n.getUint32(0,!0),s=n.getUint32(4,!0);return{w:o,h:s,pixels:t.subarray(8)}}openSession(e,t,n=1){let{h:o}=this.call("session.new",{doc:e,author:t,seed:n});return new Q(this,o)}openRoom(e,{seq:t=0}={}){let{h:n}=this.call("room.new",{doc:e,...t>0?{seq:t}:{}});return new De(this,n)}},Q=class{constructor(e,t){this.core=e,this.h=t}#e(e,t={}){return this.core.call(e,{h:this.h,...t})}state(){return this.#e("session.state")}apply(e,{now:t=Date.now(),label:n="Edit",job:o=null}={}){let s={now:t,label:n,bodies:Array.isArray(e)?e:[e]};return o&&(s.job=o),this.#e("session.apply",s).ops}remote(e){return this.#e("session.remote",{sop:e})}reject(e){return this.#e("session.reject",{op:e})}undo(e=Date.now()){return this.#e("session.undo",{now:e}).ops}redo(e=Date.now()){return this.#e("session.redo",{now:e}).ops}pending(){return this.#e("session.pending")}checkpoint({doc:e=!0}={}){return this.#e("session.checkpoint",{doc:e})}save(){return this.#e("session.save")}drawArt(e,t,n={}){return this.#e("session.drawArt",{rows:e,colors:t,...n}).bodies}drawAnimation(e,t,n={}){return this.#e("session.drawAnimation",{frames:e,colors:t,...n}).bodies}readArt(e,t,n={}){return this.#e("session.readArt",{layer:e,...H(t),...n})}cel(e,t){return this.#e("session.cel",{layer:e,...H(t)})}layerImage(e,t){return this.#e("session.layerImage",{layer:e,...H(t)})}tileCel(e,t){return this.#e("session.tileCel",{layer:e,...H(t)})}tile(e,t){return this.#e("session.tile",{tileset:e,index:t})}composite(e,{include:t="export"}={}){return this.#e("session.composite",{...H(e),include:t})}png(e,{scale:t=1,rect:n=null}={}){return this.#e("session.png",{...H(e),scale:Math.max(1,Math.round(t)||1),...n?{rect:n}:{}})}contactSheet({columns:e=4,scale:t=2}={}){return this.#e("session.sheet",{columns:e,scale:t})}thumbnail(e=48){return this.#e("session.thumbnail",{size:e})}card({frame:e=null,width:t=1200,height:n=630,framing:o=null,bleed:s=0,raw:i=!1}={}){return this.#e("session.card",{width:t,height:n,...o??{},...H(e),...s?{bleed:s}:{},...i?{raw:i}:{}})}cardLayout({frame:e=null,width:t=1200,height:n=630,framing:o=null}={}){return this.#e("session.cardLayout",{width:t,height:n,...o??{},...H(e)})}fit({width:e,height:t,margin:n=0,inscribed:o=!1,dx:s=0,dy:i=0,frame:a=null}){return this.#e("session.fit",{width:e,height:t,margin:n,inscribed:o,dx:s,dy:i,...H(a)})}close(){this.#e("session.free")}},De=class{constructor(e,t){this.core=e,this.h=t}#e(e,t={}){return this.core.call(e,{h:this.h,...t})}state(){return this.#e("room.state")}submit(e,t=Date.now()){return this.#e("room.submit",{op:e,now:t})}since(e){return this.#e("room.since",{seq:e})}compact(){return this.#e("room.compact")}save(){return this.#e("room.save")}lease(e,t){return this.#e("room.lease",{action:e,...t})}region(e,t,n){return this.#e("room.region",{layer:e,frame:t,rect:{x:n.x??0,y:n.y??0,w:n.w,h:n.h}})}close(){this.#e("room.free")}}});function jt(r){return JSON.stringify(r)}function At(r){let e=r.rle instanceof Uint8Array?r.rle:null,t=new TextEncoder().encode(JSON.stringify({...r,rle:void 0}));if(t.length>An)return null;let n=new Uint8Array(3+t.length+(e?.length??0));return n[0]=_t,n[1]=t.length&255,n[2]=t.length>>8&255,n.set(t,3),e&&n.set(e,3+t.length),n}function Rn(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):null}function Rt(r){if(typeof r!="string"){let e=Rn(r);if(!e||e.length<3||e[0]!==_t)return null;let t=e[1]|e[2]<<8;if(e.length<3+t)return null;try{let n=JSON.parse(new TextDecoder().decode(e.subarray(3,3+t)));if(!n||typeof n.t!="string")return null;let o=e.subarray(3+t);return n.rle=o.length?Uint8Array.from(o):null,n}catch{return null}}try{let e=JSON.parse(r);return e&&typeof e.t=="string"?e:null}catch{return null}}var T,Et,O,vt,_t,An,Tt=K(()=>{"use strict";T={HELLO:"hello",SUBMIT:"submit",PRESENCE:"presence",STROKE:"stroke",LEASE:"lease",REVIEW:"review",PING:"ping",PROMPT:"prompt",ANSWER:"answer",STOP:"stop"},Et={DOCUMENT:"document",LIBRARY:"library"},O={WELCOME:"welcome",REHELLO:"rehello",OPS:"ops",REJECT:"reject",PRESENCE:"presence",STROKE:"stroke",LEASE:"lease",INK:"ink",SUGGESTIONS:"suggestions",SUGGESTION:"suggestion",ERROR:"error",PONG:"pong",PROMPT:"prompt",ANSWER:"answer",STOP:"stop"},vt={OPS:"ops",SNAPSHOT:"snapshot"};_t=157,An=65535});function Ot(r){return C().toLowerCase().slice(0,16)}var Pt=K(()=>{"use strict";ae()});function On(r){let e=[];if(!r.length)return new Uint8Array;let t=r[0],n=r[1],o=r[2],s=r[3],i=0,a=()=>{let c=i;do{let h=c&127;c>>>=7,e.push(c?h|128:h)}while(c);e.push(t,n,o,s)};for(let c=0;c<r.length;c+=4)r[c]===t&&r[c+1]===n&&r[c+2]===o&&r[c+3]===s?i++:(a(),t=r[c],n=r[c+1],o=r[c+2],s=r[c+3],i=1);return a(),new Uint8Array(e)}function Pn(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode.apply(null,r.subarray(n,n+32768));return btoa(e)}function Nn(r){return Pn(On(r))}function It(r,e,t,n){return{t:"paintRegion",layer:r,frame:e,rect:{x:t.x,y:t.y,w:t.w,h:t.h},rle:Nn(n)}}var Mt=K(()=>{"use strict"});import{readFile as Ir}from"node:fs/promises";import{readFile as cn,writeFile as hn,mkdir as ln,chmod as un}from"node:fs/promises";import{readFileSync as dn}from"node:fs";import{homedir as pn,hostname as fn}from"node:os";import{join as Me}from"node:path";import{execFile as mn}from"node:child_process";var k=r=>String(r??"").replace(/\/+$/,"").replace(/^ws/,"http"),et=r=>String(r??"").replace(/\/+$/,"").replace(/^http/,"ws");async function tt(r,e){if(!r?.ok||!(r.headers.get("content-type")??"").includes("json"))return null;let t=await r.json().catch(()=>null);return!t||typeof t!="object"?null:e.some(n=>n in t)?t:null}async function nt(r,{timeoutMs:e=3e3,fetchImpl:t=fetch}={}){try{let n=await t(`${k(r)}/setup`,{signal:AbortSignal.timeout(e)});return await tt(n,["accounts","expectedPort","install"])}catch{return null}}var Ie=new Map;function rt(r,{fetchImpl:e=fetch,timeoutMs:t=3e3}={}){let n=k(r);return Ie.has(n)||Ie.set(n,an(r,{fetchImpl:e,timeoutMs:t})),Ie.get(n)}async function an(r,{fetchImpl:e,timeoutMs:t}){try{let n=await e(`${k(r)}/config.json`,{signal:AbortSignal.timeout(t)}),s=(await tt(n,["rooms","accounts"]))?.rooms;if(typeof s=="string"&&/^(wss?|https?):\/\/./.test(s))return et(s)}catch{}return et(r)}var se=process.env.SPRITE_PUBLIC_SERVER||wn()||null;function wn(){return"wss://drawpixie.com"}var ot=Me(process.env.XDG_CONFIG_HOME||Me(pn(),".config"),"sprite"),Ce=Me(ot,"agent.json"),st=r=>String(r??"").replace(/\/+$/,"");function it(){return`${fn().replace(/\.local$/,"")}`.slice(0,60)||"a computer"}async function at(){try{let r=JSON.parse(await cn(Ce,"utf8"));return r&&typeof r=="object"&&r.servers?r:{servers:{}}}catch{return{servers:{}}}}async function ie(r){return process.env.SPRITE_TOKEN?{token:process.env.SPRITE_TOKEN,from:"the environment"}:(await at()).servers[st(r)]??null}async function ct(r,e){await ln(ot,{recursive:!0,mode:448});let t=await at();t.servers[st(r)]={...e,at:Date.now()};let n=`${Ce}.tmp`;await hn(n,JSON.stringify(t,null,2),{mode:384}),await un(n,384);let{rename:o}=await import("node:fs/promises");await o(n,Ce)}async function ht(r,{timeoutMs:e=3e3}={}){try{let t=await fetch(`${k(r)}/setup`,{signal:AbortSignal.timeout(e)});return t.ok?!!(await t.json()).accounts:!1}catch{return!1}}async function lt(r,e,{session:t=null}={}){let n=t??await ie(r);if(!n?.token)return;let o=await fetch(`${k(r)}/documents/${encodeURIComponent(e)}/token`,{headers:{Authorization:`Bearer ${n.token}`}});if(o.status===401)throw new Error("this machine is signed out \u2014 pair it again");if(o.status===403)throw new Error(`no access to ${e}`);if(!o.ok)throw new Error(`could not get access to ${e}`);return(await o.json()).token}async function ut(r,{name:e,w:t,h:n},{session:o=null}={}){let s=o??await ie(r);if(!s?.token)return;let i=await fetch(`${k(r)}/documents/new`,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:e,w:t,h:n})});if(i.status===401)throw new Error("this machine is signed out \u2014 pair it again");if(!i.ok)throw new Error(`could not make a document: the server said ${i.status}`);let{id:a}=await i.json();if(typeof a!="string"||!a)throw new Error("could not make a document: the server named none");return a}async function dt(r,e,{method:t="GET",body:n=null,session:o=null}={}){let s=o??await ie(r);if(!s?.token)return;let i=await fetch(`${k(r)}${e}`,{method:t,headers:{Authorization:`Bearer ${s.token}`,...n!==null?{"Content-Type":"application/json"}:{}},body:n!==null?JSON.stringify(n):void 0});if(i.status===401)throw new Error("this machine is signed out \u2014 pair it again");let a=await i.json().catch(()=>({}));if(!i.ok)throw new Error(a?.error?String(a.error):`the server said ${i.status}`);return a}function pt(r){let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return new Promise(t=>mn(e,[r],()=>t()))}gt();Ue();import{createServer as bn}from"node:http";import{randomBytes as xt}from"node:crypto";var xn=300*1e3,$n=()=>xt(32).toString("base64url"),Sn=()=>xt(16).toString("base64url");function bt(r,e){return`<!doctype html><meta charset="utf-8"><title>Pixie</title><body style="background:#101014;color:#d8d8e0;font:14px/1.6 system-ui,sans-serif;display:grid;place-items:center;height:100vh;margin:0;text-align:center"><div><p style="font-size:16px">${r}</p><p style="color:#8a8a99;font-size:12px">${e}</p></div>`}async function kn({state:r,timeoutMs:e}){let t,n,o=new Promise((c,h)=>{t=c,n=h}),s=bn((c,h)=>{let l=new URL(c.url,"http://127.0.0.1");if(l.pathname!=="/callback"){h.writeHead(404).end();return}if(l.searchParams.get("state")!==r){h.writeHead(404).end();return}let u=l.searchParams.get("error");h.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}).end(u?bt("Nothing was granted.","You can close this window."):bt("This computer can now draw in your sprites.","You can close this window and go back to what you were doing.")),t(l.searchParams)});await new Promise((c,h)=>{s.once("error",h),s.listen(0,"127.0.0.1",c)});let i=setTimeout(()=>n(new Error("nobody answered the browser in time")),e);i.unref?.();let{port:a}=s.address();return{redirect:`http://127.0.0.1:${a}/callback`,wait:o,close:()=>{clearTimeout(i),s.close(),s.closeAllConnections?.()}}}async function $t(r,{onUrl:e=()=>{},open:t=pt,label:n="the Pixie agent",scope:o=Le,timeoutMs:s=xn}={}){let i=$n(),a=await yt(i),c=Sn(),h=await kn({state:c,timeoutMs:s});try{let l=new URL(`${k(r)}/authorize`);l.searchParams.set("challenge",a),l.searchParams.set("state",c),l.searchParams.set("redirect",h.redirect),l.searchParams.set("scope",o.join(",")),l.searchParams.set("name",n),e(l.toString()),await t(l.toString());let u=await h.wait,d=u.get("error");if(d)throw new Error(d==="access_denied"?"you said no on that screen, so nothing was granted":`that request was refused: ${d}`);let p=u.get("code");if(!p)throw new Error("the browser came back without an authorization");let w=await fetch(`${k(r)}/auth/authorize/exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:p,verifier:i,name:it()})}),f=await w.json().catch(()=>({}));if(!w.ok||!f.token)throw new Error(f.error||"that authorization could not be exchanged");return await ct(r,{token:f.token,name:f.name,email:f.email,scope:f.scope??null}),f}finally{h.close()}}import{realpathSync as St}from"node:fs";import{fileURLToPath as En}from"node:url";function kt(r){let e=process.argv[1];if(!e)return!1;try{return St(En(r))===St(e)}catch{return!1}}ae();import{execFile as Yt}from"node:child_process";Tt();ae();var Tn=5e3,$e=class{#e=null;constructor(e,t,n){if(!n||!n.author)throw new Error("DocumentClient needs an author");if(this.core=e,this.author=n.author,this.name=n.name||"anonymous",this.agent=n.agent===!0,this.answers=n.answers===!0,this.seed=n.seed??1,this.epoch=0,this.resumed=null,n.resume){let{h:o,dropped:s}=e.call("session.resume",{doc:t,author:this.author,seed:this.seed,seq:n.resume.seq??0,pending:n.resume.pending??[]});this.session=new Q(e,o),this.resumed={seq:n.resume.seq??0,dropped:s??[]}}else this.session=e.openSession(t,this.author,this.seed);this.getToken=n.getToken??null,this.transport=null,this.connected=!1,this.welcomed=!1,this.ready=new Promise(o=>{this.#e=o}),this.participants=[],this.leases=[],this.presence=null,this.you=null,this.onChange=()=>{},this.onPresence=()=>{},this.onStroke=()=>{},this.strokePreview=!0,this.onLeases=()=>{},this.ink=null,this.onInk=()=>{},this.proposals=new Map,this.suggesting=!1,this.onSuggestions=()=>{},this.onLost=()=>{},this.waiters=new Set,this.onPrompt=()=>{},this.onAnswer=()=>{},this.onStop=()=>{},this.onStatus=()=>{}}apply(e,t={}){let n=this.session.apply(e,t);return this.#t(n),this.onChange(),n}acked(e,{timeoutMs:t=3e4}={}){let n=new Set((Array.isArray(e)?e:[e]).map(o=>o?.opId??o).filter(Boolean));return new Promise((o,s)=>{let i={ids:n,resolve:o,reject:s,timer:null};i.timer=setTimeout(()=>{this.waiters.delete(i);let a=[...n].filter(c=>this.session.pending().some(h=>h.opId===c)).length;s(new Error(`${a} operation${a===1?"":"s"} not confirmed by the room after ${Math.round(t/1e3)}s \u2014 `+(this.connected?"it is answering slowly":`the connection dropped; nothing since sequence ${this.session.state().seq} has been saved`)))},t),this.waiters.add(i),this.#n()})}#n(){if(!this.waiters.size)return;let e=new Set(this.session.pending().map(t=>t.opId));for(let t of this.waiters)[...t.ids].some(n=>e.has(n))||(this.waiters.delete(t),clearTimeout(t.timer),t.resolve())}#o(e,t){for(let n of this.waiters)n.ids.has(e)&&(this.waiters.delete(n),clearTimeout(n.timer),n.reject(new Error(t)))}undo(e=Date.now()){let t=this.session.undo(e);return this.#t(t),this.onChange(),t}redo(e=Date.now()){let t=this.session.redo(e);return this.#t(t),this.onChange(),t}setPresence(e){this.presence=e,this.connected&&this.#r({t:T.PRESENCE,...e})}sendStroke({layer:e,frame:t,rect:n,rle:o,done:s=!1}){if(!this.connected||!this.welcomed||!this.strokePreview||this.suggesting)return;this._strokeSentAt=Date.now();let i=At({t:T.STROKE,layer:e,frame:t,rect:n,rle:o,done:s});i&&this.#u(i)}suggest(e){if(!e.length||!this.connected||!this.welcomed)return[];let t=this.session.state().seq,n=e.map(o=>({opId:C(),author:this.author,parentSeq:t,...o}));return this.#r({t:T.SUBMIT,ops:n}),n}review(e,t){!this.connected||!this.welcomed||this.#r({t:T.REVIEW,author:e,verdict:t})}lease(e,t={}){this.#r({t:T.LEASE,action:e,...t})}prompt(e,{where:t=Et.DOCUMENT}={}){if(!this.connected)return null;let n=String(e??"").trim().slice(0,2e3);if(!n)return null;let o=C();return this.#r({t:T.PROMPT,id:o,text:n,where:t}),o}answer(e,t="",{reply:n=null,made:o=null,model:s=null}={}){return this.connected?(this.#r({t:T.ANSWER,state:e,text:String(t??"").slice(0,2e3),reply:n,made:o,model:s}),!0):!1}stopAnswer(e){return!this.connected||!e?!1:(this.#r({t:T.STOP,id:e}),!0)}get state(){return this.session.state()}checkpoint({doc:e=!0}={}){return{epoch:this.epoch,author:this.author,...this.session.checkpoint({doc:e})}}composite(e){return this.session.composite(e)}connect(e){return this.transport=e,this.pendingToken=this.getToken?this.getToken():void 0,this.pendingToken?.catch?.(()=>{}),e.onopen=async()=>{this.connected=!0,this.welcomed=!1,clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.connected&&this.#r({t:T.PING})},Tn),await this.#i()},e.onmessage=t=>this.#p(t),e.onclose=()=>{this.connected=!1,this.welcomed=!1,clearInterval(this.heartbeat),this.onStatus({connected:!1})},e.readyState===1&&e.onopen(),this}disconnect(){if(this.transport){this.connected=!1,this.welcomed=!1,clearInterval(this.heartbeat);try{this.transport.close()}catch{}this.transport=null,this.onStatus({connected:!1})}}async#i(){let e;if(this.pendingToken!==void 0){let n=this.pendingToken;this.pendingToken=void 0,e=await n}else e=this.getToken?await this.getToken():void 0;let t=this.session.state();this.#r({t:T.HELLO,author:this.author,name:this.name,token:e,since:t.seq,...this.agent?{agent:!0}:{},...this.answers?{answers:!0}:{},...this.presence?.active===!1?{active:!1}:{},docId:t.doc.id})}#p(e){let t=Rt(e);if(t)switch(t.t){case O.WELCOME:return this.#s(t);case O.REHELLO:return this.welcomed=!1,void this.#i();case O.OPS:return this.#a(t);case O.REJECT:return this.#f(t);case O.PRESENCE:return this.participants=t.participants||[],this.onPresence(this.participants);case O.STROKE:return this.onStroke(t);case O.LEASE:return this.leases=t.leases||[],this.onLeases(this.leases);case O.INK:return this.ink={left:t.left,cap:t.cap,refillMs:t.refillMs,nextInMs:t.nextInMs??0,at:Date.now()},this.onInk(this.ink);case O.SUGGESTIONS:return this.proposals=new Map((t.proposals??[]).map(n=>[n.author,{...n,ops:[...n.ops??[]]}])),this.onSuggestions(this.proposals);case O.SUGGESTION:{if(t.gone)return this.proposals.delete(t.author),this.onSuggestions(this.proposals,{author:t.author,name:t.name??null,gone:t.gone,by:t.by??null,applied:t.applied??0});let n=this.proposals.get(t.author)??{author:t.author,name:t.name??null,cc:t.cc??null,ops:[],at:t.at};if(n.name=t.name??n.name,n.at=t.at??n.at,t.replaced?.length){let o=new Set(t.replaced);n.ops=n.ops.filter(s=>!(s.rect?.w===1&&s.rect?.h===1&&o.has(`${s.rect.x},${s.rect.y}`)))}return n.ops.push(...t.ops??[]),this.proposals.set(t.author,n),this.onSuggestions(this.proposals,{author:t.author,added:t.ops?.length??0})}case O.PROMPT:return this.onPrompt(t);case O.ANSWER:return this.onAnswer(t);case O.STOP:return this.onStop(t);case O.ERROR:if(this.#m(t.message)){this.strokePreview=!1;return}return this.onLost({kind:t.fatal?"fatal":"protocol",message:t.message});default:return}}#s(e){this.you=e.you,this.suggesting=e.you?.suggest===!0,this.welcomed=!0;let t=this.session.pending();if(e.catchup.kind===vt.SNAPSHOT){let{h:n,dropped:o}=this.core.call("session.resume",{doc:e.catchup.doc,author:this.author,seed:this.seed,seq:e.catchup.seq,pending:t});if(this.session.close(),this.session=new Q(this.core,n),this.epoch++,o&&o.length){for(let s of o)this.#o(s,"could not be replayed onto the current document");this.onLost({kind:"rebased",ops:o,message:`${o.length} edit${o.length>1?"s":""} could not be replayed onto the current document`})}}else for(let n of e.catchup.ops||[])this.#l(n);if(this.#n(),this.participants=e.participants||[],this.leases=e.leases||[],t.length&&this.suggesting)for(let n of t)this.session.reject(n.opId);else t.length&&this.#r({t:T.SUBMIT,ops:t});this.presence&&this.#r({t:T.PRESENCE,...this.presence}),this.onStatus({connected:!0,resent:t.length}),this.onPresence(this.participants),this.onLeases(this.leases),this.onChange(),this.#e?.(),this.#e=null}#a(e){let t=!1;for(let n of e.ops||[])this.#l(n),t=!0;t&&(this.#n(),this.onChange())}#l(e){let t=this.session.remote(e);t.dropped&&t.dropped.length&&this.onLost({kind:"obsolete",ops:t.dropped,message:`${t.dropped.length} of your edits no longer apply and were dropped`})}#f(e){e.opId&&this.session.reject(e.opId),e.opId&&this.#o(e.opId,e.message),this.onLost({kind:e.kind,ops:e.opId?[e.opId]:[],message:e.message}),this.onChange()}#t(e){!e.length||!this.connected||!this.welcomed||this.#r({t:T.SUBMIT,ops:e})}#r(e){this.#u(jt(e))}#m(e){return typeof e!="string"?!1:e===`unknown message: ${T.STROKE}`?!0:e==="unreadable message"&&Date.now()-(this._strokeSentAt??0)<2e3}#u(e){if(this.transport)try{this.transport.send(e)}catch{this.connected=!1}}close(){this.disconnect(),this.session.close()}};ae();Pt();var G=r=>{let e=String(r).replace("#","");return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]};var ee=([r,e,t])=>.3*r+.59*e+.11*t;function Se([r,e,t]){let n=Math.max(r,e,t),o=Math.min(r,e,t),s=n-o,i=0;return s&&(n===r?i=(e-t)/s%6:n===e?i=(t-r)/s+2:i=(r-e)/s+4,i*=60,i<0&&(i+=360)),[i,n?s/n:0,n/255]}var Nt={luminance:(r,e)=>ee(G(r))-ee(G(e)),hue:(r,e)=>{let[t,n]=Se(G(r)),[o,s]=Se(G(e));return n<.08||s<.08?n<.08&&s<.08?ee(G(r))-ee(G(e)):n<.08?-1:1:Math.round(t/20)!==Math.round(o/20)?t-o:ee(G(r))-ee(G(e))},saturation:(r,e)=>Se(G(r))[1]-Se(G(e))[1]};function te(r,e="hue"){let t=Nt[e]??Nt.hue;return[...r].sort(t)}Mt();import{readFile as de,writeFile as sr,mkdir as ir}from"node:fs/promises";import{access as In,mkdir as Mn,writeFile as Cn}from"node:fs/promises";import{dirname as Ln}from"node:path";async function ke(r,e,{overwrite:t=!1,seq:n=null}={}){let o=await In(r).then(()=>!0,()=>!1);if(o&&!t){let s=r.replace(/(\.png)?$/i,`-seq${n??"N"}$1`);throw new Error(`${r} already exists \u2014 a chat that showed it once will keep showing the old picture, so a preview gets a new name each time: ${s}. Pass overwrite: true only for a file nothing has shown yet.`)}return await Mn(Ln(r),{recursive:!0}),await Cn(r,e),o}function Ct(r,e){let t=r.inputSchema??{},n=t.properties??{},o=Object.keys(n),s=e&&typeof e=="object"?e:{},i={};for(let[c,h]of Object.entries(s)){if(!(c in n)){let l=qe(c,o),u=o.length?`${r.name} takes: ${o.join(", ")}.`:`${r.name} takes no arguments.`;throw new Error(`no such argument \`${c}\`${l?` \u2014 did you mean \`${l}\`?`:""} ${u}`)}i[c]=Un(r.name,c,n[c],h)}let a=(t.required??[]).filter(c=>i[c]===void 0);if(a.length)throw new Error(`${r.name} needs ${a.map(c=>`\`${c}\``).join(" and ")}. It takes: ${o.join(", ")}.`);return i}function Un(r,e,t,n){if(n==null)return n;let o=t.type;if(o==="integer"||o==="number"){let s=typeof n=="string"&&n.trim()!==""?Number(n):n;if(typeof s!="number"||!Number.isFinite(s))throw new Error(`\`${e}\` must be a number, got ${ne(n)}. ${r} takes \`${e}\` as ${o==="integer"?"an integer":"a number"}.`);if(o==="integer"&&!Number.isInteger(s))throw new Error(`\`${e}\` must be a whole number, got ${s}.`);if(t.minimum!==void 0&&s<t.minimum)throw new Error(`\`${e}\` must be at least ${t.minimum}, got ${s}.`);if(t.maximum!==void 0&&s>t.maximum)throw new Error(`\`${e}\` must be at most ${t.maximum}, got ${s}.`);return s}if(o==="boolean"){if(n==="true")return!0;if(n==="false")return!1;if(typeof n!="boolean")throw new Error(`\`${e}\` must be true or false, got ${ne(n)}.`);return n}if(o==="string"&&typeof n!="string"){if(typeof n=="number")return String(n);throw new Error(`\`${e}\` must be text, got ${ne(n)}.`)}if(o==="array"&&!Array.isArray(n))throw new Error(`\`${e}\` must be a list, got ${ne(n)}.`);if(o==="object"&&(typeof n!="object"||Array.isArray(n)))throw new Error(`\`${e}\` must be an object, got ${ne(n)}.`);if(t.enum&&!t.enum.includes(n))throw new Error(`\`${e}\` must be one of ${t.enum.map(s=>`\`${s}\``).join(", ")}, got ${ne(n)}.`);return n}function ne(r){return typeof r=="string"?`"${r.length>40?r.slice(0,37)+"\u2026":r}"`:Array.isArray(r)?"a list":r&&typeof r=="object"?"an object":String(r)}function qe(r,e){let t=r.toLowerCase(),n=e.filter(i=>{let a=i.toLowerCase();return(t.startsWith(a)||a.startsWith(t))&&a!==t});if(n.length)return n.sort((i,a)=>Math.abs(i.length-t.length)-Math.abs(a.length-t.length))[0];let o=null,s=3;for(let i of e){let a=Dn(t,i.toLowerCase());a<s&&(s=a,o=i)}return o}function Dn(r,e){let t=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=r.length;n++){let o=t[0];t[0]=n;for(let s=1;s<=e.length;s++){let i=t[s];t[s]=Math.min(t[s]+1,t[s-1]+1,o+(r[n-1]===e[s-1]?0:1)),o=i}}return t[e.length]}import{createHash as ar}from"node:crypto";import{tmpdir as cr}from"node:os";import{join as He,basename as Ae,extname as hr,resolve as lr}from"node:path";function ze(r){try{return/^(localhost|127\.0\.0\.1|\[::1\]|::1)$/.test(new URL(k(r)).hostname)}catch{return!1}}function Lt(r,{publicServer:e=se}={}){let t=k(r);return e&&r===e?`nothing is answering at ${t} \u2014 this machine is offline, or the site is down`:ze(r)?`nothing is answering at ${t} \u2014 start the editor with \`npm start\` in the Pixie repository, then try again`:`nothing is answering at ${t} \u2014 check the address and that whatever serves it is up`}import{appendFile as Vn,mkdir as Dt,readFile as Kn,writeFile as Fe}from"node:fs/promises";import{dirname as qt}from"node:path";var qn=new Set(["note","unfinished","takes","intent","finished","run","label"]);function Z(r,e=0,t=120){if(r==null||typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return r.length>t?`${r.slice(0,t-1)}\u2026`:r;if(Array.isArray(r)){if(r.length&&r.every(n=>typeof n=="string")){let n=new Set(r.map(o=>o.length));return`${r.length}\xD7${n.size===1?r[0].length:`${Math.min(...n)}\u2013${Math.max(...n)}`}`}return`[${r.length}]`}if(typeof r=="object"){let n=Object.keys(r),o=n.length<=8&&n.every(i=>r[i]==null||typeof r[i]!="object");if(n.length>32||e>0&&!o)return`{${n.length}}`;let s={};for(let i of n)s[i]=Z(r[i],e+1,qn.has(i)&&typeof r[i]=="string"?2e3:120);return s}return String(r)}function zn(r){if(r&&typeof r=="object"&&Array.isArray(r.content)){let e=r.content.find(n=>n.type==="image"),t=r.content.find(n=>n.type==="text")?.text??"";if(r.isError)return{ok:!1,error:Z(t)};if(e)return{ok:!0,result:`image \u2014 ${Z(t)}`};try{return{ok:!0,result:Z(JSON.parse(t))}}catch{return{ok:!0,result:Z(t)}}}return{ok:!0,result:Z(r)}}var Ee=class{constructor(){this.entries=[],this.next=1,this.open=new Map,this.starts=new Map,this.idleFrom=1,this.lead=new Map}async record(e,t,n){let o=Date.now(),s={i:this.next++,t:new Date(o).toISOString(),tool:e,args:Z(t??{})};try{let i=await n();return Object.assign(s,zn(i),{ms:Date.now()-o}),this.#e(s),i}catch(i){throw Object.assign(s,{ok:!1,error:Z(i?.message??String(i)),ms:Date.now()-o}),this.#e(s),i}}#e(e){this.entries.push(e),this.entries.length>4e3&&this.entries.splice(0,this.entries.length-4e3)}began(e){if(!e)return;let t=this.entries.at(-1)?.i??this.next;this.open.size===0&&this.idleFrom<t&&this.lead.set(e,this.idleFrom),this.open.set(e,t),this.starts.set(t,e)}all(e=500){let t=this.entries.length,n=new Map,o=null;for(let s of this.entries){let i=this.starts.get(s.i);i&&(o=i),n.set(s.i,s.args?.job??o??null),s.tool==="finish_job"&&(s.args?.job??o)===o&&(o=null)}return{calls:t,dropped:Math.max(0,t-e),entries:this.entries.slice(-e).map(s=>n.get(s.i)?{...s,job:n.get(s.i)}:s)}}finished(e){let t=e??(this.open.size===1?[...this.open.keys()][0]:null);if(!t||!this.open.has(t))return[];let n=this.open.get(t);this.open.delete(t);let o=this.lead.get(t)??n;return this.lead.delete(t),this.open.size===0&&(this.idleFrom=this.next),this.entries.filter(s=>s.i>=o&&(s.args?.job==null||s.args.job===t)&&(this.starts.get(s.i)??t)===t).map(s=>s.i<n?{...s,between:!0}:s)}};import{readFileSync as Fn}from"node:fs";import{execFileSync as Bn}from"node:child_process";import{fileURLToPath as Wn}from"node:url";import{dirname as Gn}from"node:path";var Ut="0.7.7";function Jn(){let r=new URL("./version.json",import.meta.url);try{let e=JSON.parse(Fn(r,"utf8"))?.version;if(typeof e=="string"&&e)return e;throw new Error("it names no version")}catch(e){throw new Error(`${r.pathname} could not be read as a version: ${e.message}`)}}var ce=Ut??Jn();function Hn(){if(Ut)return null;let r=Gn(Wn(import.meta.url)),e=(...t)=>Bn("git",t,{cwd:r,stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();try{let t=e("rev-parse","--short=12","HEAD");return t?e("status","--porcelain","--",".","../../edge/src","../../core/js")?`${t}-dirty`:t:null}catch{return null}}var he=Hn();var ve={type:"string",description:"#rrggbb"};async function Zn(r,e){let t=await Kn(r).catch(s=>{throw new Error(`could not read ${r}: ${s.code==="ENOENT"?"no such file":s.message}`)});if(t.length>8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71){if(!e.core?.decodePng)throw new Error("this server cannot decode a PNG \u2014 send rows and colors");return Xn(e.core.decodePng(t))}let o;try{o=JSON.parse(t.toString("utf8"))}catch{throw new Error(`${r} is neither a PNG nor JSON`)}if(!o||typeof o!="object"||!Array.isArray(o.rows)||typeof o.colors!="object")throw new Error(`${r} needs "rows" (an array of strings) and "colors" (a map of character to #rrggbb)`);return o}function Xn({w:r,h:e,pixels:t}){let n={},o=new Map,s=33,i=h=>{let l=o.get(h);if(l)return l;for(;;)if(s===34||s===46||s===92||s===95||s===127)s+=1;else if(s>=128&&s<161)s=161;else if(s>=55296&&s<57344)s=57344;else break;return l=String.fromCodePoint(s),s+=1,o.set(h,l),n[l]=h,l},a=h=>h.toString(16).padStart(2,"0"),c=[];for(let h=0;h<e;h++){let l="";for(let u=0;u<r;u++){let d=(h*r+u)*4,p=t[d+3];if(p===0){l+=".";continue}let w=p===255?`#${a(t[d])}${a(t[d+1])}${a(t[d+2])}`:`#${a(t[d])}${a(t[d+1])}${a(t[d+2])}${a(p)}`;l+=i(w)}c.push(l)}return{rows:c,colors:n}}var P={type:"string",description:"The job this call belongs to. May be omitted when exactly one job is open."},le={type:"string",description:"Which document. Omit to use the one your job owns. The id \u2014 the one new_sprite, get_info and list_documents hand back \u2014 or the exact name when only one document has it. A share link (`https://\u2026/s/<document>_<snapshot>`) or an editor link (`\u2026/d/<document>`) names its document too, so a link the user pasted can be passed straight in. In a local editor a 0-based tab index works too."},zt={type:"integer",description:"A PAST state of the document, rebuilt from the room's history: the sequence number get_info reports and every draw_art result carries. Omit for now. This is how to compare a pass with the one it replaced \u2014 the check that catches a revision that is locally better and worse as a picture: read or render the seq before your change, render now, and stack them small and in grays (references/judge.py). A read, never a restore; the document does not move."};function Yn(r){let e=String(r).trim();if(!/[:/]/.test(e))return e;let t=e;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))try{t=new URL(e).pathname}catch{return e}let n=/(?:^|\/)s\/([A-Za-z0-9_-]{1,128})(?:\/|$)/.exec(t);if(n)return n[1].split("_")[0];let o=/(?:^|\/)d\/([A-Za-z0-9-]{1,64})(?:\/|$)/.exec(t);return o?o[1]:e}var Qn=r=>({isError:!0,content:[{type:"text",text:r}]}),re=r=>({content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r)}]}),Ft=(r,e)=>({content:[{type:"image",data:Buffer.from(r).toString("base64"),mimeType:"image/png"},{type:"text",text:e}]}),U={w:240,h:126},Bt={w:80,h:42},er="40\xD721, 80\xD742, 120\xD763, 160\xD784, 240\xD7126, 480\xD7252, 600\xD7315",tr="40\xD740, 50\xD750, 80\xD780, 100\xD7100",nr="60\xD720, 75\xD725, 150\xD750, 300\xD7100";function Be(r,e){if(!r||!e)return null;let t=r/e,n=1200/630;if(Math.abs(t-n)<.15){let o=Math.round(r/n);return`${r}\xD7${e} is ${t.toFixed(2)}:1; the link-card shape at this width is ${r}\xD7${o} \u2014 resize_canvas if it is meant to be posted.`}return Math.abs(t-1)<.1?`${r}\xD7${e} is nearly square; ${Math.max(r,e)}\xD7${Math.max(r,e)} would be a profile picture.`:Math.abs(t-3)<.25?`${r}\xD7${e} is nearly 3:1; ${r}\xD7${Math.round(r/3)} would be a profile banner.`:null}function je(r,e){return!r||!e?null:r===e?"This is square, the shape of a profile picture: in the editor, file \u25B8 Save as profile picture (400\xD7400) fits it inside the circle it will be cropped to. Tell the user.":r===3*e?"This is 3:1, the shape of a profile banner: in the editor, file \u25B8 Save as profile banner (1500\xD7500) exports it at the size X wants. Tell the user.":Math.abs(r/e-1200/630)<.02?"This is the link-card shape: the share button posts it edge to edge.":null}function rr(r){let e=String(r??"").trim();if(!/^[A-Za-z0-9]+([-_][A-Za-z0-9]+)+$/.test(e))return e;let t=e.split(/[-_]+/).join(" ");return t[0].toUpperCase()+t.slice(1)}var or=[{name:"new_sprite",description:"Create a sprite and claim it. Call this FIRST \u2014 before writing a script, computing a grid, or thinking about pixels. It costs milliseconds and puts a labeled document in front of the user immediately, so they can see what you are making and where. The tab opens in the background and never steals their focus. The size is `w` and `h` (not width/height), as everywhere here.",inputSchema:{type:"object",properties:{name:{type:"string",description:'The title, the way a person would write it: "Blue cake", not "blue-cake". Shown on the tab and in the library; the URL is minted from it. A hyphenated lowercase name is turned into words.'},w:{type:"integer",default:U.w,description:`Width in pixels. WHAT THE USER ASKED FOR WINS: a stated size or shape is used as stated, and a named artist, piece or style is matched in scale and detail. The rest is defaults for when nothing was said: ${U.w}\xD7${U.h} \u2014 1.91:1, the ratio link cards crop to, so a piece drawn on it posts edge to edge, and big enough for a subject with parts (a dish with its slice and garnish, a figure with props, a room). ${Bt.w}\xD7${Bt.h} when the user asks for something SIMPLE \u2014 "simple", "quick", "small", "minimal", "a little", "basic", "rough", "doodle", "icon-like" \u2014 bold shapes and big pixels. Any multiple of 40\xD721 fills the card (${er}: examples, not limits). A PROFILE PICTURE is square and cropped to a circle \u2014 keep the subject inside it: ${tr}. A BANNER is 3:1: ${nr}. Use a game asset's own size (8\xD78, 16\xD716, 32\xD732) only when the user asks for a tile, icon, or sprite for a game.`},h:{type:"integer",default:U.h,description:"Height in pixels. See w."},palette:{type:"array",items:ve,description:"Optional starting palette. Kept in ramp order \u2014 by hue, then dark to light \u2014 not the order given, so a script that indexes the document's palette by position will be off: map by hex."},intent:{type:"string",description:'One line on what you are making, including the VIEW. Shown while you work. The default view is three-quarter: the camera above and to one side, so an object shows its top and two sides and a scene has depth \u2014 unless the user says "flat", "side view", "front", "profile", "top-down", "icon" or "tile", which mean what they say and no perspective at all.'},folder:{type:"string",description:'Optional folder to file it in, by path (`food/sushi`). Made if it does not exist. Use this when the user asks for sprites "in a folder" rather than moving them afterwards.'},challenge:{type:"string",enum:["daily","weekly","inktober"],description:'"daily" when the user asks for the sprite of the day / today\'s theme / the Pixel Dailies; "weekly" for the sprite of the week / this week\'s word / Weekly Pixels; "inktober" for today\'s Inktober prompt, which runs the 31 days of October. The name comes from the prompt itself (pass `name` only to override), and finish_job will say how to post it as an entry. Call `challenges` first if you want to see the prompt before drawing.'}},required:["intent"]},run:async(r,e)=>{let t=r.name?rr(r.name):null,n=r.w??null,o=r.h??null;if(r.challenge){let s=await e.challenge(r.challenge);if(t??=s.theme,n===null&&o===null&&s.sizes?.length){let i=s.sizes[Math.floor((s.sizes.length-1)/2)],[a,c]=i.split(/[x×]/).map(Number);a&&c&&([n,o]=[a,c])}}if(!t)throw new Error("new_sprite needs a name, or a challenge to take one from");return e.newSprite({name:t,w:n??U.w,h:o??U.h,intent:r.intent,palette:r.palette,folder:r.folder??null,challenge:r.challenge??null})}},{name:"challenges",description:`The standing prompts: Pixel Dailies sets a theme every day ("Today's theme is #Gateway"), Weekly Pixels a word every week with sizes, and Inktober a prompt for each of the 31 days of October. When the user says "the sprite of the day", "today's theme", "the daily", "the weekly", "this week's word", "Inktober" or "today's Inktober prompt" \u2014 or names any of the three \u2014 this is what they mean: read it here rather than asking them. The server reads the accounts and keeps the answer, and holds Inktober's published list; nothing is fetched from Bluesky or inktober.com by you. An entry whose \`theme\` is null is one nobody has set \u2014 Inktober's is null for the other eleven months.`,inputSchema:{type:"object",properties:{}},run:(r,e)=>e.challenges()},{name:"begin_job",description:"Claim an existing document for one piece of work \u2014 the other way to start, where new_sprite is the one for new art. Refused by name if another job holds it, which is what keeps parallel requests from colliding. With no `document` and no job open, it picks up the document you last finished IN THIS SESSION \u2014 one more pass on the same sprite is begin_job({ intent }); a document from an earlier session has to be named (list_documents has them).",inputSchema:{type:"object",properties:{document:{type:"string",description:"Which document: the id, or the exact name when only one document has it. Omit, with no job open, for the one you last finished in this session; a document from an earlier one has to be named."},intent:{type:"string"},layer:{type:"string",description:"Restrict the claim to one layer, leaving the rest free. Rooms only."}},required:["intent"]},run:(r,e)=>e.beginJob({document:r.document,intent:r.intent,layer:r.layer??null})},{name:"finish_job",description:'Release the document. Call this when the sprite is done, so the user knows to look. The result says what to do next for a profile picture, a banner or a card \u2014 pass that on to the user \u2014 and carries `trace`: every call of this job, as the server saw it \u2014 and, marked `between: true`, any made with no job open since the last finish. When the task asked for a report back, do NOT assemble trace.jsonl out of these: `get_info({ trace: true, file: "\u2026/trace.jsonl" })` writes the whole session to that file itself, and three reports that retyped the record by hand lost something each \u2014 two lost `versions` and one abbreviated every result \u2014 which is a sibling of `trace` here, travels inside this call\'s own trace entry, and is what feedback.py stamps the report with. Without it a current server is labeled ancient and every friction item struck.',inputSchema:{type:"object",properties:{job:P,note:{type:"string",description:`One line on what shipped \u2014 "8 roses, hooked thorns, ivy; crown at CY 69" \u2014 which becomes the history's line for this job in place of the intent written before the work. Optional; up to 200 characters.`},trace:{type:"string",description:"APPEND this job's calls to this path as JSONL, as the server saw them. For a report that outlives the session that made the art: `get_info({ trace: true })` is this PROCESS's record and a new session starts an empty one, so a report written the next day cannot reach the work it is about \u2014 one was rebuilt by retyping four finish_job returns. Pass the same path on every finish_job of the piece (`feedback/<name>/trace.jsonl`) and the file is complete whatever happens to the session. Written beside `get_info`'s, not instead of it: that one writes the session, this one adds a job."}}},run:async(r,e)=>({...await e.finishJob({job:r.job,note:r.note??""}),versions:{mcp:ce,...he?{commit:he}:{}}})},{name:"push_source",description:"Push the generator behind this job \u2014 the script(s) that made the sprite \u2014 so the next agent (or you, tomorrow) can pick the work up rather than redraw it from the pixels. Stored beside the job's mark in the document's version history, with the seq it reproduces; READABLE BY THIS ACCOUNT ONLY, never by anyone else in the room. Push the source, not its output: the .py, and anything it imports that is yours; not the grid JSON or a PNG, which it regenerates (text, \u2264 16 files, \u2264 96 KiB). `run` is the exact command; `takes` what it needs that is not in the push (a reference from Commons: its URL; the skill's references/ helpers by name); `unfinished` what you would do next. Push before finish_job, and again after a real change.",inputSchema:{type:"object",properties:{files:{type:"array",items:{type:"string"},description:'Paths on this machine to the files to push. The basename is kept, the directory is not \u2014 so two generators both called `mint.py` need `{ from: "<path on disk>", path: "<name to push it as>" }` instead of a plain path.'},run:{type:"string",description:'The command that regenerates the sprite from these files, e.g. "python3 buche.py .context/yule/solo.json && draw_art({ file })".'},takes:{type:"string",description:"What it needs that is not in the push: reference URLs, the references/ helpers it imports, a palette. Empty if nothing."},unfinished:{type:"string",description:"What is not done, or what you would change next. The next agent reads this first."},job:P},required:["files","run"]},run:(r,e)=>e.pushSource({job:r.job,files:r.files,run:r.run,takes:r.takes??"",unfinished:r.unfinished??""})},{name:"pull_source",description:"What this account pushed on a document: with no `job`, the list (job, seq, run, unfinished, file names) \u2014 with a `job`, its files written to disk under `into` (default .context/source/<job>/) with how to run them, what they take and what was unfinished. Call it before redrawing a sprite an agent made: if there is a push, start from it. Only your own pushes come back; a mark with `source: true` in the history that is not listed here is somebody else's. READ THE FILES BEFORE RUNNING THEM, and run them in the workspace with nothing the task does not need \u2014 they are code somebody pushed.",inputSchema:{type:"object",properties:{document:le,job:{type:"string",description:"The job whose push to write to disk. Omit to list."},into:{type:"string",description:"Directory to write the files into. Default .context/source/<job>/. A file that exists with different content is not overwritten."}}},run:(r,e)=>e.pullSource({document:r.document??null,job:r.job??null,into:r.into??null})},{name:"draw_art",description:'Returns when the room has confirmed the drawing \u2014 `seq` is the room\'s number for it and `committed` is true \u2014 or fails saying why; if it says the connection dropped, wait a moment and check get_info before drawing more. Draw a character grid. Each string in `rows` is one row of pixels and each character maps to a color via `colors`. A key is any single character except "." and " " \u2014 letters, digits, punctuation, any Unicode symbol \u2014 so a generator that runs past 62 colors keeps going. "." and " " leave existing pixels alone; a color mapped to null erases. Every character is resolved before a pixel moves, so a typo fails rather than half-drawing. With no style reference, keep the palette small \u2014 four to eight colors, reused for shading \u2014 because that is what makes a small sprite read as pixel art rather than as a downscaled photograph. When matching an artist or a piece, use as many colors as their work does. A canvas past ~300 wide goes in bands: several calls with `y`, a few dozen rows each. A LARGE OR GENERATED GRID SHOULD NOT PASS THROUGH YOU: have the script write it to a file and pass `file` instead of `rows` \u2014 a JSON file of {rows, colors, x?, y?, \u2026}, or a PNG. Either is the whole canvas or, with `rect`, one region of it: a pass that touched only the fire base sends the same file and names the rect, and the history says "fire base", not everything. The reply says how many pixels are not what they were (`changed`; `inked` is how many the grid painted, when the two differ \u2014 a full-canvas redraw that moved a corner says 180 and 30240) and which colors joined the palette, so growth is never silent (with `palette: "replace"` nothing joins: the palette becomes this drawing\'s colors plus whatever the other layers are drawn in, and the reply says so). read here on the same machine. Then the call is fifty bytes, whatever the canvas.',inputSchema:{type:"object",properties:{file:{type:"string",description:'Path to a grid on this machine, instead of rows and colors: a JSON file of draw_art arguments, or a PNG. A PNG\'s colors are used as they are \u2014 not quantized to the palette; each distinct color joins it (or with `palette: "replace"`, becomes it) \u2014 so read_art({ png }) \u2192 edit \u2192 draw_art({ file }) round-trips exactly. Anything given in the call as well wins.'},rows:{type:"array",items:{type:"string"}},colors:{type:"object",additionalProperties:{oneOf:[ve,{type:"null"}]}},x:{type:"integer"},y:{type:"integer"},center:{type:"boolean"},clear:{type:"boolean",description:"Erase the cel first."},rect:{type:"object",description:"With `file`, JSON or PNG: replace only this region `{x, y, w, h}` of the canvas from a full-canvas file \u2014 a one-object change is not a whole-canvas redraw. With `clear`, only the region is emptied first.",properties:{x:{type:"integer"},y:{type:"integer"},w:{type:"integer"},h:{type:"integer"}}},palette:{type:"string",enum:["add","replace","keep"],description:"What this drawing's colors do to the document palette: `add` (default) joins them; `replace` makes them the whole palette \u2014 for a generated piece redrawn several times, so the palette does not pile up, and on a multi-layer document it keeps what the OTHER layers are drawn in too, since the palette is the document's; `keep` leaves the palette as it is \u2014 for a pass the user may send back (a glow tried three ways left 120 tints behind), or a generator whose blends are not colors anybody will pick."},layer:{type:"string",description:"Layer name or index. Defaults to the top one."},frame:{type:"integer",description:"Frame index. Defaults to the first."},label:{type:"string",description:"What this shows as in the undo history."},job:P}},run:async(r,e)=>{let t=r.file?{...await Zn(r.file,e),...r}:r;if(!Array.isArray(t.rows)||!t.colors)throw new Error("draw_art needs rows and colors, or a file that has them");return e.drawArt({job:t.job,rows:t.rows,colors:t.colors,x:t.x??0,y:t.y??0,center:t.center??!1,clear:t.clear??!1,layer:t.layer,frame:t.frame??0,label:t.label,palette:t.palette??"add",rect:t.rect??null})}},{name:"draw_animation",description:"Write every frame in ONE call, as a single undo step. Use copyPrevious so a frame carries the last one forward and sends only the pixels that moved \u2014 that is what takes a six-frame loop from four thousand tokens of restated grid to under a thousand. Never loop draw_art. SILHOUETTE FIRST: at 32px a front-on animal is any animal; when the subject could go several ways, draw 2-3 rough silhouettes as frames, look with render_animation, keep the one that reads, then add detail \u2014 three candidates cost barely more than one.",inputSchema:{type:"object",properties:{frames:{type:"array",minItems:1,items:{type:"object",properties:{rows:{type:"array",items:{type:"string"}},copyPrevious:{type:"boolean"},x:{type:"integer"},y:{type:"integer"},center:{type:"boolean"}},required:["rows"]}},colors:{type:"object",additionalProperties:{oneOf:[ve,{type:"null"}]}},fps:{type:"number"},layer:{type:"string"},label:{type:"string"},job:P},required:["frames","colors"]},run:(r,e)=>e.drawAnimation({job:r.job,frames:r.frames,colors:r.colors,fps:r.fps,layer:r.layer,label:r.label})},{name:"read_art",description:"Read a cel back as a grid \u2014 the exact inverse of draw_art, so you can extend art a human drew rather than only replacing it. Reads never need a job and never wait: with no job open they read the document last finished in this session, or the `document` named. The fallback is this process's memory, so the first call of a new session names its document. `seq` reads a PAST state instead of now \u2014 the grid as it stood at that document sequence, rebuilt from the room's history \u2014 which is how to get the pixels of the pass you replaced.",inputSchema:{type:"object",properties:{document:le,layer:{type:"string"},frame:{type:"integer"},trim:{type:"boolean",description:"Return only the drawn area. Rooms only."},seq:zt,file:{type:"string",description:"Write the grid to this path on this machine as JSON \u2014 the shape draw_art takes as `file` \u2014 instead of returning it, so a script can round-trip art without it passing through you. The reply says where it went and how big it is."},png:{type:"string",description:"Write the document to this path as a PNG, one image pixel per sprite pixel \u2014 the composite, or one `layer` \u2014 so an image tool, `references/compare.py` or `references/scene.py guides` can open the room's truth directly. A local editor writes the composite only."},job:P}},run:async(r,e)=>{if(r.png){if(!e.readPng)throw new Error("a PNG of the document is a room thing \u2014 in a local editor, read_art({ file }) and render it");let i=await e.readPng({document:r.document,job:r.job,layer:r.layer??null,frame:r.frame??0,seq:r.seq??null});return await Fe(r.png,i.png).catch(a=>{throw new Error(`could not write ${r.png}: ${a.message}`)}),{document:i.document,...i.at!==void 0?{at:i.at}:{},png:r.png,size:`${i.w}\xD7${i.h}`,layer:r.layer??"composite"}}let t=await e.readArt({document:r.document,job:r.job,layer:r.layer,frame:r.frame??0,trim:r.trim??!1,seq:r.seq??null});if(!r.file)return t;let{rows:n,colors:o,...s}=t;return await Fe(r.file,JSON.stringify({rows:n,colors:o},null,0)).catch(i=>{throw new Error(`could not write ${r.file}: ${i.message}`)}),{...s,file:r.file,size:`${n[0]?.length??0}\xD7${n.length}`,colors:Object.keys(o??{}).length}}},{name:"render_preview",description:"See one frame as an image, so you can check your own work rather than working blind. Needs no job: with none open it renders the document last finished in this session, or the `document` named \u2014 the first look of a new session names it, the fallback being this process's. Rendered at a readable size by default (about a thousand pixels on the long side); `scale` is screen pixels per sprite pixel if you want a particular one. To look closely at one part of a big canvas \u2014 a cell of a sprite sheet \u2014 pass `rect` `{x, y, w, h}` in sprite pixels, or `rects` to put several objects side by side in ONE image, which is what the per-object audit wants (an agent wrote its own tiler rather than make eight calls, and spent the audit looking at its own render instead of the room's). The text beside the image says exactly what was rendered, at what scale, and at which document seq \u2014 the room's confirmed state, never a queued or stale mirror: a render waits for the room to confirm what you sent and is refused while the connection is down. WHEN MATCHING A REFERENCE, pass `reference` (a path on this machine \u2014 PNG, or a JPEG on a Mac): the reference is brought to the canvas grid and shown on the LEFT of the render, same rect, same scale \u2014 the only comparison that catches an object built nothing like the original. A reference that is not the shape of the canvas is fitted whole (black where it does not reach) \u2014 into the `rect` when one is given, so one icon beside the one cell it was drawn into is the icon filling that cell; `referenceRect` brings one part of it \u2014 the object you are checking, in reference pixels \u2014 into the `rect` instead (into the whole canvas when there is no `rect`), fitted by the side that limits it, so the two sides are one object at one scale; the caption gives that scale in reference pixels per canvas pixel. That is how to compare one thing up close. To give rects in canvas pixels instead, pass the reference already resampled to the canvas's size (analyze_reference.py --resample): a reference the canvas's shape maps 1:1, so `referenceRect` is then the same numbers as `rect`. Judge per object from that, never from the whole image or from memory \u2014 and judge construction, not resemblance: count the faces, name the light, say where the shadow falls, on theirs and on yours. `values` renders both as grays \u2014 the squint test for a value plan and a focal point. ON A TRANSPARENT CANVAS pass `background` (\"checker\" or a #rrggbb): alpha is shown over white, so a white tip or a pale sparkle is invisible and cannot be judged at all.",inputSchema:{type:"object",properties:{document:le,frame:{type:"integer"},scale:{type:"integer",description:"Screen pixels per sprite pixel. Default: whatever makes the long side about 1000px."},rect:{type:"object",description:"A window onto the canvas in sprite pixels, cropped before scaling. Omit w/h to run to the edge.",properties:{x:{type:"integer"},y:{type:"integer"},w:{type:"integer"},h:{type:"integer"}}},rects:{type:"array",description:"Several windows instead of one, tiled left to right into a single image with a magenta line between them \u2014 the per-object audit in one call rather than one call per object. Each crop is NUMBERED in the magenta strip under it, 1 upwards, so a 32-cell sheet audit can name the cell it means instead of counting along the row; give each one a `label` and the caption says which number is which. Not with `reference`.",items:{type:"object",properties:{x:{type:"integer"},y:{type:"integer"},w:{type:"integer"},h:{type:"integer"},label:{type:"string",description:'What this crop is \u2014 "cruller", "head". Said in the caption against the number drawn under the crop; a name does not fit on an icon-sized tile.'}}}},reference:{type:"string",description:"Path to a reference image on this machine: a PNG anywhere, a JPEG on a Mac (converted on the way; elsewhere convert it first). Shown beside the render at the same crop and scale, fitted whole to the canvas grid and centered \u2014 or the part of it `referenceRect` names."},referenceRect:{type:"object",description:"The part of the reference to bring to the grid, in reference pixels: `{x, y, w, h}`. Omit for the whole picture. With a `rect`, this region is fitted into that rect (centered, black where it does not reach); pick the region that holds the object `rect` shows, at the same proportions, and the two sides are that object at one scale.",properties:{x:{type:"integer"},y:{type:"integer"},w:{type:"integer"},h:{type:"integer"}}},values:{type:"boolean",description:"Render as values only (grayscale) \u2014 the render, and the reference when one is given. A picture that is mid-tone everywhere shows it here and nowhere else."},background:{type:"string",description:'What the transparent pixels show as: `"checker"` or a `#rrggbb`. Default is nothing \u2014 the alpha arrives as alpha, which a viewer paints white, so white or near-white art on a transparent canvas is INVISIBLE in the preview. Pass this whenever the canvas is transparent and the art has light pixels: a white tip, a sparkle, snow, a highlight. A sparkle was once shipped unseen for want of it.'},file:{type:"string",description:"Also write the image to this path \u2014 exactly what is returned: the rect, the scale, the reference beside it, the values. For `final.png` and the crops a report keeps, for any check that wants the room's picture rather than a local re-render, and for showing the user. A path that already exists is REFUSED unless `overwrite` is true: a chat that has shown a path once keeps showing the old picture under it, so a preview meant to be seen gets a new name every time (`preview-<seq>.png`; the caption says the seq)."},overwrite:{type:"boolean",description:"Let `file` replace a file that exists. Only for a file nothing has shown yet \u2014 a report's `final.png` being redone \u2014 never for a preview embedded in a reply."},seq:zt,job:P}},async run(r,e){let t=await e.preview({document:r.document,job:r.job,frame:r.frame??0,scale:r.scale??null,rect:r.rect??null,rects:r.rects??null,reference:r.reference??null,referenceRect:r.referenceRect??null,values:r.values===!0,background:r.background??null,file:r.file??null,overwrite:r.overwrite===!0,seq:r.seq??null});return Ft(t.png,t.caption)}},{name:"render_animation",description:"Every frame as one numbered contact sheet. Stills inspected one call at a time, minutes apart, cannot tell you whether motion reads; a contact sheet can, in one call. Check any animation with this before calling it done.",inputSchema:{type:"object",properties:{document:le,columns:{type:"integer",default:4},scale:{type:"integer",default:2},job:P}},async run(r,e){let t=await e.sheet({document:r.document,job:r.job,columns:r.columns??4,scale:r.scale??2});return Ft(t.png,t.caption)}},{name:"add_layer",description:"Add a layer above the others. Anything you will revise while the rest stays \u2014 a figure over a background, a caption over a figure \u2014 goes on its own layer, so a revision is one draw_art with `clear: true` on that layer and the base is never redrawn or at risk.",inputSchema:{type:"object",properties:{name:{type:"string"},job:P}},run:(r,e)=>e.addLayer({job:r.job,name:r.name})},{name:"add_frame",description:"Add an animation frame after the last one.",inputSchema:{type:"object",properties:{copy:{type:"boolean",description:"Start from the previous frame."},job:P}},run:(r,e)=>e.addFrame({job:r.job,copy:r.copy??!1})},{name:"set_palette",description:"Replace the palette. Constraining yourself to a small fixed palette is the single biggest quality lever in pixel art \u2014 choose it before you draw, because every draw_art adds its colors. With `prune: true` and no `colors`, drop every palette entry no pixel uses instead: the way to clean up after a session that did not. Never done for you on finish_job.",inputSchema:{type:"object",properties:{colors:{type:"array",items:ve,minItems:1},prune:{type:"boolean",description:"Keep only the colors some pixel uses. `colors` is ignored."},job:P}},run:(r,e)=>!r.prune&&!r.colors?.length?Qn("set_palette wants `colors`, or `prune: true`"):e.setPalette({job:r.job,colors:r.colors??[],prune:r.prune===!0})},{name:"set_fps",description:"Set playback speed for every frame. Eight to twelve suits character animation.",inputSchema:{type:"object",properties:{fps:{type:"integer",minimum:1,maximum:60},job:P},required:["fps"]},run:(r,e)=>e.setFps({job:r.job,fps:r.fps})},{name:"clear",description:"Erase a cel. Destructive, so it goes through a job like every other write.",inputSchema:{type:"object",properties:{layer:{type:"string"},frame:{type:"integer"},job:P}},run:(r,e)=>e.clearCel({job:r.job,layer:r.layer,frame:r.frame??0})},{name:"trim_canvas",description:'Crop the canvas to the drawn pixels. Call this before finish_job on every GAME ASSET \u2014 a tile, an icon, a sprite for a sheet: you cannot know its extent before you have drawn it, so overshoot at new_sprite and trim afterwards, or empty space is inherited by every export and sheet. Do NOT trim a piece made to be posted: its canvas is the card, and the space around the subject is the composition. `center: true` instead KEEPS the canvas and moves the art to the middle of it \u2014 "make it horizontally and vertically centered", which arrives on every transparent sprite; `get_info`\'s `bbox` is where the art is now. Both measure the art on EVERY layer and frame, because the crop is of the document and what falls outside it is gone.',inputSchema:{type:"object",properties:{margin:{type:"integer",default:0},center:{type:"boolean",description:"Do not crop: keep the canvas and move the drawn pixels to its center. `margin` is ignored."},job:P}},run:(r,e)=>e.trim({job:r.job,margin:r.margin??0,center:r.center===!0})},{name:"resize_canvas",description:"Change the canvas size, keeping the art \u2014 the fix for a sprite made at the wrong size, in place, on the same document. `anchor` says where the old canvas sits on the new one: `center` (default), `top-left`, `top`, `top-right`, `left`, `right`, `bottom-left`, `bottom`, `bottom-right`. Never make a second document for a size change. The old art is kept at `anchor`; pass `clear: true` to start the new size blank in the same call \u2014 otherwise the room shows the old picture in the corner until the next full draw_art. `clear` empties EVERY layer and frame: a resize is of the document, so a blank canvas is a blank one.",inputSchema:{type:"object",properties:{w:{type:"integer",minimum:1,maximum:1024},h:{type:"integer",minimum:1,maximum:1024},anchor:{type:"string"},clear:{type:"boolean",description:"Erase everything after resizing, so a full redraw at the new size does not follow an old picture in the corner."},job:P},required:["w","h"]},run:(r,e)=>e.resizeCanvas({job:r.job,w:r.w,h:r.h,anchor:r.anchor??"center",clear:r.clear===!0})},{name:"get_info",description:"What is in a document \u2014 size, layers, frames, palette \u2014 and who else is looking at it; `layers: true` makes each layer an object with its pixel count and bounding box, which is how to check a layer split without reading every layer back; `connected` says whether the room is on the other end and `pending` how many operations it has not confirmed. Both should be true and zero before you trust a read. `trace: true` adds this session's whole call record \u2014 every call, not one job's, the same entries finish_job hands back \u2014 which is what a report's Trace section is written from when it spans several jobs. Per process: a new session starts an empty one. With `file` as well, the record is written there as JSONL and the result is a summary: that is `trace.jsonl`, in the server's own words rather than retyped through you. The result carries `versions` \u2014 which pixie-mcp this was \u2014 so the file stamps itself and a report never has to.",inputSchema:{type:"object",properties:{document:le,job:P,trace:{type:"boolean",description:"Add every call this session has made, oldest first, as `trace`, each entry carrying the `job` it belongs to \u2014 for a report over more than one job."},layers:{type:"boolean",description:"Make `layers` an object per layer instead of a name \u2014 `{ name, pixels, bbox }`, bottom to top, counted over every frame. What verifies a layer split without reading each one back and stacking it: a pass that landed nowhere is `pixels: 0`, and a layer reaching further than the one above it is the trim you are about to regret."},file:{type:"string",description:"With `trace: true`: write the trace to this path as JSONL \u2014 one entry per line, which is exactly what a report's `trace.jsonl` is \u2014 and return a summary instead of the entries. The file is the server's copy: a trace that comes back through the model and is typed out again loses the long fields (a report's was \"the payload re-emitted, with the repeated document metadata abbreviated\"). Replaced if it exists, because a report gets rebuilt."}}},run:async(r,e)=>{if(r.file&&r.trace!==!0)throw new Error("`file` here writes the trace \u2014 pass trace: true with it. For the document as a picture or a grid, that is render_preview({ file }) and read_art({ file }).");let t=await e.info({document:r.document,job:r.job,layers:r.layers===!0});return r.trace===!0?{...t,versions:{mcp:ce,...he?{commit:he}:{}}}:t}},{name:"list_documents",description:'Every document you can reach, and every job currently open. Call this when the user names a sprite ("add a frame to the hamster") so you can pass it to begin_job. Never guess a name.',inputSchema:{type:"object",properties:{}},run:(r,e)=>e.documents()},{name:"create_folder",description:"Make a folder in the library, by path \u2014 `food/sushi` nests. Already existing is fine. Prefer passing `folder` to new_sprite when the sprites are new; use this for an empty folder or before move_documents.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The folder path."}},required:["name"]},run:(r,e)=>e.createFolder({name:r.name})},{name:"move_documents",description:"File documents into a folder, or back to the top level with folder null. Takes document ids from list_documents. The folder is made if it does not exist.",inputSchema:{type:"object",properties:{documents:{type:"array",items:{type:"string"},description:"Document ids."},folder:{type:["string","null"],description:"Folder path, or null for the top level."}},required:["documents"]},run:(r,e)=>e.moveDocuments({documents:r.documents,folder:r.folder??null,make:!0})},{name:"take_requests",description:"Requests people have typed into the editor and not yet been answered. Call this when the user asks you to check, or after joining a room they are in. Each one is somebody asking for a sprite in words \u2014 treat it exactly as if they had said it to you directly. Each carries what it wants: a `room` to answer in, or `room: null` for a request typed at the library, which wants a brand new sprite rather than a change to any existing one.",inputSchema:{type:"object",properties:{}},run:(r,e)=>e.takeRequests()},{name:"open_editor",description:"Open the Pixie editor in the default browser and wait for it to connect. Run this first if nothing is connected.",inputSchema:{type:"object",properties:{}},async run(r,e){let t=await e.openEditor();return re(t.message)}},{name:"select_document",description:"Bring a document to the front for the USER to look at. This does not give you the right to draw in it \u2014 begin_job does that.",inputSchema:{type:"object",properties:{document:{type:["string","integer"]}},required:["document"]},run:(r,e)=>e.select({document:r.document})},{name:"close_document",description:"Close a document: in a local editor its tab, in a room the connection and any job you hold on it. The document stays in the library, so this tidies the workspace rather than deleting anything.",inputSchema:{type:"object",properties:{document:{type:["string","integer"]}}},run:(r,e)=>e.closeDocument({document:r.document??null})},{name:"set_frame",description:"Move the user to a frame, by 0-based index.",inputSchema:{type:"object",properties:{index:{type:"integer"}},required:["index"]},run:(r,e)=>e.setFrame({index:r.index})},{name:"set_layer",description:"Move the user to a layer, by 0-based index counting from the bottom.",inputSchema:{type:"object",properties:{index:{type:"integer"}},required:["index"]},run:(r,e)=>e.setLayer({index:r.index})},{name:"undo",description:"Undo the last change, so the user can always reject generated art.",inputSchema:{type:"object",properties:{}},run:(r,e)=>e.undo()},{name:"redo",description:"Redo the last undone change.",inputSchema:{type:"object",properties:{}},run:(r,e)=>e.redo()}];function Wt(r){let e=r.trace??=new Ee,t=n=>n&&typeof n=="object"&&Array.isArray(n.content);return or.filter(n=>r.supports(n.name)).map(n=>({name:n.name,description:n.description,inputSchema:n.inputSchema,run:async o=>{let s=await e.record(n.name,o,()=>{let i=Ct(n,o);return typeof i.document=="string"&&(i.document=Yn(i.document)),n.run(i,r)});if((n.name==="new_sprite"||n.name==="begin_job")&&s?.job&&e.began(s.job),n.name==="finish_job"&&s&&typeof s=="object"&&!t(s)){let i=e.finished(s.job??o?.job);if(typeof o?.trace=="string"&&o.trace){let a=String(o.trace);return await Dt(qt(a),{recursive:!0}).catch(()=>{}),await Vn(a,`${i.map(c=>JSON.stringify(c)).join(`
3
+ `)}
4
+ `).catch(c=>{throw new Error(`could not append the trace to ${a}: ${c.message}`)}),re({...s,traceFile:a,traceCalls:i.length,traceNote:`${i.length} entr${i.length===1?"y":"ies"} appended to ${a}. Pass the same path on every finish_job of this piece and the file survives a session boundary; get_info({ trace: true, file }) writes this session's whole record instead.`})}return re({...s,trace:i})}if(n.name==="get_info"&&o?.trace===!0&&s&&typeof s=="object"&&!t(s)){let{calls:i,dropped:a,entries:c}=e.all();if(o.file){let h=String(o.file),l=`${c.map(d=>JSON.stringify(d)).join(`
5
+ `)}
6
+ `;await Dt(qt(h),{recursive:!0}).catch(()=>{}),await Fe(h,l).catch(d=>{throw new Error(`could not write ${h}: ${d.message}`)});let u=c.filter(d=>d.ok===!1).length;return re({...s,traceFile:h,traceCalls:i,traceFailed:u,...a?{traceDropped:a}:{},traceNote:`${c.length} entr${c.length===1?"y":"ies"} written to ${h}, one JSON object per line, oldest first \u2014 this call is the last of them, and its result carries \`versions\`, so the file says which pixie-mcp wrote it. That file is the report's Trace section; say under the heading what stands out in it.`})}return re({...s,trace:c,traceCalls:i,...a?{traceDropped:a}:{},traceNote:"every call this session made, oldest first \u2014 save as trace.jsonl, one entry per line. This call is in it. Or pass `file` and the server writes it."})}return t(s)?s:re(s)}}))}var Gt=/^[A-Za-z0-9_-]{1,64}$/,ur={daily:{label:"Pixel Dailies",whose:"today's Pixel Dailies",puts:"the theme and the tags"},weekly:{label:"Weekly Pixels",whose:"this week's Weekly Pixels",puts:"the tags and the account"},inktober:{label:"Inktober",whose:"today's Inktober",puts:"#inktober and the year's tag"}},dr=6e3;function Jt(r,e){return Math.max(1,Math.min(32,Math.round(1e3/Math.max(r,e,1))))}function Ht(r,e,t,n=null){let o=pr(n,r.w,r.h),s=o.x===0&&o.y===0&&o.w===r.w&&o.h===r.h?r:fr(r,o),i=Math.min(e/o.w,t/o.h),a=Math.max(1,Math.round(o.w*i)),c=Math.max(1,Math.round(o.h*i)),h=wr(s,a,c),l=Math.floor((e-a)/2),u=Math.floor((t-c)/2),d=new Uint8Array(e*t*4);for(let p=0;p<c;p++)d.set(h.pixels.subarray(p*a*4,(p+1)*a*4),((u+p)*e+l)*4);return{w:e,h:t,pixels:d,placed:{x:l,y:u,w:a,h:c},region:o,by:e/o.w<=t/o.h?"width":"height"}}function pr(r,e,t){let n=Math.max(0,Math.min(e-1,Math.floor(Number(r?.x??0))||0)),o=Math.max(0,Math.min(t-1,Math.floor(Number(r?.y??0))||0)),s=Math.max(1,Math.min(e-n,Math.floor(Number(r?.w??e-n))||e-n)),i=Math.max(1,Math.min(t-o,Math.floor(Number(r?.h??t-o))||t-o));return{x:n,y:o,w:s,h:i}}function fr(r,e){let t=new Uint8Array(e.w*e.h*4);for(let n=0;n<e.h;n++){let o=((e.y+n)*r.w+e.x)*4;t.set(r.pixels.subarray(o,o+e.w*4),n*e.w*4)}return{w:e.w,h:e.h,pixels:t}}async function mr(r,e){if(e.length>8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return e;let n=e[0]===255&&e[1]===216?"JPEG":e.subarray(0,4).toString()==="GIF8"?"GIF":e.subarray(8,12).toString()==="WEBP"?"WebP":"not a PNG",o="convert it first: python3 references/pngio.py in.jpg out.png (Pillow, or `sips` on a Mac), or any image tool";if(process.platform!=="darwin")throw new Error(`the reference ${r} is ${n==="not a PNG"?n:`a ${n}`}, and this server reads PNG \u2014 ${o}`);let s=He(cr(),`pixie-ref-${ar("sha256").update(e).digest("hex").slice(0,16)}-${Ae(r,hr(r))}.png`),i=await de(s).catch(()=>null);return i||(await new Promise((a,c)=>{Yt("sips",["-s","format","png",r,"--out",s],(h,l,u)=>{h?c(new Error(`the reference ${r} is ${n==="not a PNG"?n:`a ${n}`}, and sips could not convert it (${String(u||h.message).trim()}) \u2014 ${o}`)):a()})}),de(s))}function wr(r,e,t){let n=new Uint8Array(e*t*4),o=r.w/e,s=r.h/t;for(let i=0;i<t;i++){let a=Math.floor(i*s),c=Math.max(a+1,Math.floor((i+1)*s));for(let h=0;h<e;h++){let l=Math.floor(h*o),u=Math.max(l+1,Math.floor((h+1)*o)),d=0,p=0,w=0,f=0,m=0;for(let b=a;b<c&&b<r.h;b++)for(let x=l;x<u&&x<r.w;x++){let $=(b*r.w+x)*4;d+=r.pixels[$],p+=r.pixels[$+1],w+=r.pixels[$+2],f+=r.pixels[$+3],m++}let y=(i*e+h)*4;m&&n.set([Math.round(d/m),Math.round(p/m),Math.round(w/m),Math.round(f/m)],y)}}return{w:e,h:t,pixels:n}}function _e(r,e=new Uint8Array(r.length)){for(let t=0;t<r.length;t+=4){let n=Math.round(.299*r[t]+.587*r[t+1]+.114*r[t+2]);e[t]=e[t+1]=e[t+2]=n,e[t+3]=r[t+3]}return e}function yr(r){if(r==null||r===!1||r==="")return null;let e=String(r).trim().toLowerCase();if(e==="checker"||e==="true")return{checker:!0};let t=/^#?([0-9a-f]{6})$/.exec(e);if(!t)throw new Error(`background: "checker" or a #rrggbb color, not ${JSON.stringify(r)}`);let n=parseInt(t[1],16);return{rgb:[n>>16&255,n>>8&255,n&255]}}var gr=[[204,204,204],[153,153,153]],Ve=4;function We(r,e,t,n,o){if(!o)return r;for(let s=0;s<t;s++)for(let i=0;i<e;i++){let a=(s*e+i)*4,c=r[a+3]/255;if(c===1)continue;let h=o.rgb??gr[(((n.x+i)/Ve|0)+((n.y+s)/Ve|0))%2];for(let l=0;l<3;l++)r[a+l]=Math.round(r[a+l]*c+h[l]*(1-c));r[a+3]=255}return r}function Vt(r){return r?`, on ${r.rgb?`#${r.rgb.map(t=>t.toString(16).padStart(2,"0")).join("")}`:`a ${Ve}px checker`} where the canvas is transparent`:""}function Kt(r,e,t){let n=new Uint8Array(t.w*t.h*4);for(let o=0;o<t.h;o++){let s=((t.y+o)*e+t.x)*4;n.set(r.subarray(s,s+t.w*4),o*t.w*4)}return n}var br=["###,#.#,#.#,#.#,###",".#.,##.,.#.,.#.,###","###,..#,###,#..,###","###,..#,###,..#,###","#.#,#.#,###,..#,..#","###,#..,###,..#,###","###,#..,###,#.#,###","###,..#,..#,..#,..#","###,#.#,###,#.#,###","###,#.#,###,..#,..#"].map(r=>r.split(",")),Re=5;function xr(r,e,t,n,o,s,i){let a=String(i).split("").map(l=>br[Number(l)]),c=a.length*3+(a.length-1);if(c>s||o+Re>t)return;let h=n+Math.floor((s-c)/2);for(let l of a){for(let u=0;u<Re;u++)for(let d=0;d<3;d++)l[u][d]==="#"&&r.set([0,0,0,255],((o+u)*e+h+d)*4);h+=4}}var Qt=24;function $r(r,e=Qt,t=4){let n=a=>/^#[0-9a-f]{6}$/i.test(a)?[1,3,5].map(c=>parseInt(a.slice(c,c+2),16)):null,o=r.map(a=>[a,n(a)]).filter(([,a])=>a),s=[];for(let a=0;a<o.length;a++)for(let c=a+1;c<o.length;c++){let h=Math.hypot(...o[a][1].map((l,u)=>l-o[c][1][u]));h<e&&s.push({a:o[a][0],b:o[c][0],d:Math.round(h)})}s.sort((a,c)=>a.d-c.d);let i=new Set(s.flatMap(a=>[a.a,a.b])).size;return{pairs:s.slice(0,t),total:s.length,crowded:i}}function ue(r,e,t){let n=(c,h)=>Number.isFinite(+c)?Math.max(0,Math.round(+c)):h,o=Math.min(n(r?.x,0),e),s=Math.min(n(r?.y,0),t),i=Math.min(n(r?.w,e-o),e-o),a=Math.min(n(r?.h,t-s),t-s);return{x:o,y:s,w:i,h:a}}var Te=class{constructor(e,t){this.core=e,this.author=t.author,this.name=t.name||"agent",this.connectTransport=t.connect,this.getToken=t.getToken??null,this.createDocument=t.createDocument??null,this.control=t.control??null,this.probe=t.probe??null,this.rooms=new Map,this.asked=[],this.onAsked=null,this.jobs=new Map,this.shapeSaid=new Map,this.log=[]}async open(e,{w:t=32,h:n=32,name:o=e}={}){let s=this.rooms.get(e);if(s)return s.client;let i=this.core.newDocument({w:t,h:n,name:o,seed:Xt(),now:Date.now()}),a=new $e(this.core,i,{author:this.author,name:this.name,seed:Xt(),agent:!0,getToken:this.getToken?()=>this.getToken(e):null});a.onLost=u=>{this.lastRefusal=u},a.onPrompt=u=>{if(u.author===this.author)return;let d=u.where==="library";this.asked.push({text:u.text,from:u.name,at:u.at,wants:d?"a new sprite":"a change to this one",room:d?null:e,askedIn:e}),this.asked.length>32&&this.asked.shift(),this.onAsked?.()};let c=this.connectTransport(e,{w:t,h:n,name:o}),h=!1;return await new Promise((u,d)=>{let p=setTimeout(()=>d(new Error(`timed out joining ${e}`)),1e4);a.onStatus=f=>{f.connected&&(h=!0,clearTimeout(p),u())},a.connect(c);let w=c.onclose;c.onclose=()=>{if(w?.(),h)return this.#n(e,{w:t,h:n,name:o});clearTimeout(p),this.#e(e).then(f=>d(new Error(f)))}}),this.rooms.set(e,{client:a,attempts:0}),a}async#e(e){return this.serverUrl?(this.probe?await this.probe(this.serverUrl).catch(()=>!1):!1)?Gt.test(e)?`the room "${e}" would not open, and the server is up: try once more \u2014 a room can be away for a moment \u2014 and if it repeats, there is no such document or it is not this account's; list_documents names what it can`:`the room server refused "${e}": that is a name, not a document id \u2014 list_documents gives the id, and passing the exact name works when it is unique`:Lt(this.serverUrl):"nothing is answering at the room server"}#n(e,t){let n=this.rooms.get(e);if(!n||n.closing)return;let o=Math.min(15e3,1e3*2**Math.min(n.attempts,4));n.attempts+=1,n.retry=setTimeout(()=>{if(!this.rooms.get(e)||n.closing)return;let s=this.connectTransport(e,t),i=!1,a=s.onclose;n.client.onStatus=h=>{h.connected&&(i=!0,n.attempts=0)},n.client.connect(s);let c=s.onclose;s.onclose=()=>{c?.(),a?.(),this.#n(e,t)}},o),n.retry.unref?.()}client(e){let t=this.rooms.get(e);if(!t)throw new Error(`not in room ${e}`);return t.client}async peek(e){return this.rooms.has(e)?this.client(e):this.open(e)}async begin(e,t,{layer:n=null,open:o={}}={}){let s=await this.open(e,o),i=C();this.lastRefusal=null;let a=await jr(s,i,{intent:t,...n?{layers:[n]}:{}});if(a!=="held"){let h=s.leases.find(l=>l.job!==i);throw new Error(a==="refused"&&this.lastRefusal?.message?`could not claim "${e}": ${this.lastRefusal.message}`:h?`"${e}" is already held by another job: ${h.intent}`:a==="silent"?`could not claim "${e}": the room did not answer in time \u2014 check get_info and try again`:`could not claim "${e}"`)}let c={room:e,began:s.state.seq,layer:n,intent:t,cancelled:!1,timer:setInterval(()=>{this.jobs.has(i)&&s.lease("renew",{job:i})},dr)};return c.timer.unref&&c.timer.unref(),this.jobs.set(i,c),this.note("begin_job",e,t),i}resolve(e){if(e){let o=this.jobs.get(e);if(!o)throw new Error(`unknown job ${e} \u2014 it may have finished`);if(o.cancelled)throw new Error("the user stopped you \u2014 do not retry; say what you were about to do and ask");return{job:e,...o}}if(this.jobs.size===0)throw new Error(this.lastRoom?`no job is open \u2014 begin_job({ document: "${this.lastRoom}" }) picks ${this.lastRoom} up again, or new_sprite starts another`:"no job is open \u2014 call new_sprite or begin_job first");if(this.jobs.size>1)throw new Error(`${this.jobs.size} jobs are open \u2014 pass the job argument`);let[t,n]=[...this.jobs.entries()][0];return{job:t,...n}}finish(e,t=""){let n=this.jobs.get(e);n&&(clearInterval(n.timer),this.jobs.delete(e),this.lastRoom=n.room,this.client(n.room).lease("release",{job:e,...t?{note:t}:{}}),this.note("finish_job",n.room,t||n.intent))}async#o(e,t){if(!e&&!t&&this.jobs.size===0){if(this.lastRoom)return this.lastRoom;throw new Error(`say which document \u2014 looking needs no job, but the fallback to "the one last finished" is this session's, and nothing has been finished in it. list_documents names every one with its id.`)}return this.#a(e,t)}#i(e,t){return!t||this.shapeSaid.get(e)===t?null:(this.shapeSaid.set(e,t),t)}async submit(e,t,n){let o=this.resolve(e),s=this.client(o.room);if(!n.length)return{ops:0};if(!s.connected||!s.welcomed)throw new Error(`the room connection dropped \u2014 nothing since sequence ${s.state.seq} has been saved. Reconnecting; try again in a moment, and check get_info before drawing more.`);this.lastRefusal=null;let i=s.state.seq,a=s.apply(n,{label:t,job:o.job,now:Date.now()});try{await s.acked(a,{timeoutMs:3e4})}catch(h){throw this.lastRefusal?.kind==="revoked"&&(o.cancelled=!0),this.lastRefusal=null,h}if(this.lastRefusal){let h=this.lastRefusal.message;throw this.lastRefusal.kind==="revoked"&&(o.cancelled=!0),this.lastRefusal=null,new Error(h)}this.note(t,o.room,`${n.length} op${n.length>1?"s":""}`);let c=s.state.seq;return{ops:n.length,seq:c,committed:c>i}}cancel(e){let t=this.jobs.get(e);t&&(t.cancelled=!0)}note(e,t,n){this.log.unshift({at:Date.now(),tool:e,room:t,detail:n}),this.log.length>200&&this.log.pop()}announce(){if(!this.serverUrl)return;let e=`${this.serverUrl.replace(/^ws/,"http").replace(/\/$/,"")}/agent`,t=ze(this.serverUrl)?15e3:6e4,n=()=>{fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:this.name,every:t})}).catch(()=>{})};n(),clearInterval(this.heartbeat),this.heartbeat=setInterval(n,t),this.heartbeat.unref?.()}close(){for(let e of this.rooms.values())e.closing=!0,clearTimeout(e.retry);clearInterval(this.heartbeat);for(let[e]of this.jobs)this.finish(e);for(let{client:e}of this.rooms.values())e.close();this.rooms.clear()}get kind(){return"room"}get where(){return this.serverUrl??"a room server"}supports(e){return e==="open_editor"?!!this.editorUrl:Sr.has(e)}async openEditor({document:e,job:t}={}){if(!this.editorUrl)return{ok:!1,message:"there is no editor to open from here"};let n=this.editorUrl;try{n=`${this.editorUrl}/d/${await this.#o(e,t)}`}catch{n=`${this.editorUrl}/library`}return await Er(n),{ok:!0,message:`Opened ${n}`}}async newSprite({name:e,w:t=U.w,h:n=U.h,intent:o,palette:s,folder:i=null,challenge:a=null}){let c=await this.createDocument?.({name:e,w:t,h:n})??Ot(e),h=await this.begin(c,o,{open:{w:t,h:n,name:e}});a&&(this.jobs.get(h).challenge=a),s?.length&&await this.submit(h,"set_palette",[{t:"setPalette",colors:te(s,"hue")}]),i&&await this.moveDocuments({documents:[c],folder:i,make:!0}),this.#p(c,o);let l=this.#i(c,je(t,n)??Be(t,n));return{job:h,...this.#t(c),...l?{shape:l}:{}}}async#p(e,t){let n=process.env.SPRITE_ASKED_IN,o=process.env.SPRITE_REPLY_TO??null;if(n)try{(await this.open(n)).answer("thinking",t?String(t).slice(0,200):"making a new sprite",{reply:o,made:e})}catch{}}async beginJob({document:e,intent:t,layer:n=null}){let o=!e&&this.jobs.size===0&&this.lastRoom?this.lastRoom:await this.#a(e,null);return{job:await this.begin(o,t,{layer:n}),...this.#t(o)}}finishJob({job:e,note:t=""}){let n=this.resolve(e),o=typeof t=="string"?t.trim().slice(0,200):"";this.finish(n.job,o);let s=this.client(n.room).state,i=this.#i(n.room,je(s.doc.w,s.doc.h)),a=ur[n.challenge],h=[a?`This is ${a.whose} entry: tell the user to post it from the share button with the ${a.label} switch on, which puts ${a.puts} on the post.`:null,i].filter(Boolean).join(" "),l=s.seq!==n.began,u=n.pushed?{source:n.pushed}:l?{source:null,note:"nothing pushed \u2014 if a script made this, push_source before the next job, so the next agent (or you, tomorrow) can pick it up rather than redraw it"}:{source:null};return{finished:o||n.intent,...o?{intent:n.intent}:{},job:n.job,document:n.room,drew:l,...h?{next:h}:{},...u}}async#s(e,t={}){if(this.control)try{return await this.control(e,t)}catch(n){if(!this.openControl||!/no library here/.test(n.message))throw n}if(this.openControl)return this.openControl(e,t);throw new Error("no server to push to: this session has no control plane")}async pushSource({job:e,files:t,run:n,takes:o="",unfinished:s=""}){let i=this.resolve(e),a=this.client(i.room),c=(Array.isArray(t)?t:[t]).filter(p=>p!=null&&p!=="");if(!c.length)throw new Error("say which files: the generator, and anything it imports that is yours");let h=c.map(p=>{if(typeof p=="string")return{from:p,name:Ae(p)};let w=p?.from??p?.path;if(typeof w!="string"||!w)throw new Error(`each file is a path, or { from: "<path on disk>", path: "<name to push it as>" } \u2014 got ${JSON.stringify(p)}`);return{from:w,name:Ae(String(p.path??w))}}),l=[];for(let{from:p,name:w}of h){let f=await de(p).catch(m=>{throw new Error(`could not read ${p}: ${m.code==="ENOENT"?"no such file":m.message}`)});if(f.includes(0))throw new Error(`${p} is not text \u2014 a push is source, not a PNG or a grid; the next agent regenerates those`);l.push({name:w,text:f.toString("utf8")})}let d=(await this.#s(`/documents/${encodeURIComponent(i.room)}/history/source`,{method:"POST",body:{job:i.job,seq:a.state.seq,run:String(n??""),takes:String(o??""),unfinished:String(s??""),name:this.name,files:l}}))?.source??null;return d&&this.jobs.has(i.job)&&(this.jobs.get(i.job).pushed={seq:d.seq,files:d.files.map(p=>p.name)}),this.note("push_source",i.room,`${l.length} file${l.length===1?"":"s"}`),{document:i.room,job:i.job,seq:a.state.seq,files:d?.files??l.map(p=>({name:p.name})),note:"pushed beside this job's mark in the version history; readable by this account only. pull_source({ document, job }) brings it back to disk."}}async pullSource({document:e=null,job:t=null,into:n=null}){let o=null;if(e?o=await this.#a(e,null):this.jobs.size===1?o=this.resolve(null).room:o=this.lastRoom,!o)throw new Error("say which document \u2014 none is open and none was finished in this session");let s=`/documents/${encodeURIComponent(o)}/history/source`;if(!t){let h=await this.#s(s,{}),l=Array.isArray(h?.sources)?h.sources:[];return{document:o,sources:l.map(u=>({job:u.job,seq:u.seq,at:u.at?new Date(u.at).toISOString():null,run:u.run,unfinished:u.unfinished||null,files:u.files.map(d=>d.name)})),note:l.length?"yours on this document, newest first \u2014 pull_source({ job, into }) writes one to disk; `seq` is the document state it reproduces (get_info says where the document is now)":"nothing pushed on this document by this account \u2014 a mark with `source: true` in the history was pushed by somebody else, and is theirs"}}let i=await this.#s(`${s}/${encodeURIComponent(String(t))}`,{});if(!i?.files)throw new Error(`no source of yours under job ${t} on ${o}`);let a=lr(n?String(n):He(".context","source",String(t)));await ir(a,{recursive:!0});let c=[];for(let h of i.files){let l=He(a,Ae(h.name)),u=await de(l,"utf8").catch(()=>null);if(u!==null&&u!==h.text)throw new Error(`${l} exists and differs \u2014 pull into another directory, or move it first`);await sr(l,h.text),c.push(l)}return{document:o,job:i.job,seq:i.seq,pushedAt:i.at?new Date(i.at).toISOString():null,by:i.by?.name??null,run:i.run,takes:i.takes||null,unfinished:i.unfinished||null,files:c,note:`written to ${a}. Read the files before running them; run them from there, in the workspace, with nothing the task does not need. They reproduce seq ${i.seq} \u2014 compare get_info's seq to see what happened since.`}}async challenges(){if(!this.newsUrl)throw new Error("no server to ask: the themes come from the Pixie server, and this session has none");if(!(this.newsAt&&Date.now()-this.newsAt<300*1e3)){let n=await fetch(this.newsUrl);if(!n.ok)throw new Error(`the server said ${n.status} for the themes`);this.news=await n.json(),this.newsAt=Date.now()}let t=(n,o)=>n?{theme:n.theme,tags:n.tags,detail:n.detail??null,sizes:n.sizes??[],...n.day?{day:n.day}:{},postedAt:new Date(n.at).toISOString(),post:n.url}:{theme:null,note:`no ${o} prompt is known right now`};return{daily:t(this.news?.dailies,"daily"),weekly:t(this.news?.weekly,"weekly"),inktober:t(this.news?.inktober,"Inktober"),how:'new_sprite({ challenge: "daily" | "weekly" | "inktober", intent }) names the sprite after the prompt; finish_job says how to post it as an entry.'}}async challenge(e){let n=(await this.challenges())[e];if(!n?.theme)throw new Error(e==="inktober"?"no Inktober prompt is known right now \u2014 it runs the 31 days of October, and the list is a year at a time. Ask the user what to draw.":`no ${e} theme is known right now \u2014 ask the user what to draw`);return n}async#a(e,t){if(!e)return this.resolve(t).room;let n=String(e).trim();if(this.rooms.has(n))return n;let o=await this.#l();if(o===null||o.some(a=>a.id===n))return n;let s=o.filter(a=>(a.name??"").trim().toLowerCase()===n.toLowerCase());if(s.length===1)return s[0].id;if(s.length>1)throw new Error(`${s.length} documents are called "${n}" \u2014 pass the id: ${s.map(a=>a.id).join(", ")}`);let i=/^([A-Za-z0-9]{8,64})_([A-Za-z0-9]{8,64})$/.exec(n);if(i&&o.some(a=>a.id===i[1]))return i[1];if(Gt.test(n))return n;throw new Error(`no document is called "${n}" \u2014 list_documents names every one with its id; pass the id`)}async#l(){let e=this.control?await this.control("/documents",{}).catch(()=>null):null;if(e?.documents)return e.documents.map(n=>({id:n.id,name:n.name}));if(!this.serverUrl)return null;let t=this.serverUrl.replace(/^ws/,"http").replace(/\/$/,"");return fetch(`${t}/documents`).then(n=>n.ok?n.json():null).then(n=>n?.documents?.map(o=>({id:o.id,name:o.name}))??null).catch(()=>null)}async info({document:e,job:t,layers:n=!1}={}){let o=await this.#o(e,t),s=await this.peek(o),i=this.#t(o);return n?{...i,layers:this.#f(s)}:i}#f(e){let t=e.state,{w:n,h:o}=t.doc;return t.doc.layers.map(s=>{let i=0,a=n,c=o,h=-1,l=-1;for(let u=0;u<t.doc.frames.length;u++){let d;try{d=e.session.layerImage(s.id,u)}catch{continue}for(let p=0;p<o;p++)for(let w=0;w<n;w++)d[(p*n+w)*4+3]!==0&&(i++,w<a&&(a=w),w>h&&(h=w),p<c&&(c=p),p>l&&(l=p))}return{name:s.name,pixels:i,bbox:h<0?null:{x:a,y:c,w:h-a+1,h:l-c+1}}})}#t(e){let t=this.client(e),n=t.state;return{document:e,name:n.doc.name,w:n.doc.w,h:n.doc.h,layers:n.doc.layers.map(o=>o.name),frames:n.doc.frames.length,palette:n.doc.palette,paletteUsed:this.#y(t),bbox:this.#m(t),tags:n.doc.tags.map(o=>o.name),seq:n.seq,connected:!!(t.connected&&t.welcomed),pending:n.pending,participants:t.participants.map(o=>o.name)}}#r(e){let t=e.state,{w:n,h:o}=t.doc,s=n,i=o,a=-1,c=-1;for(let h of t.doc.layers)for(let l=0;l<t.doc.frames.length;l++){let u;try{u=e.session.layerImage(h.id,l)}catch{continue}for(let d=0;d<o;d++)for(let p=0;p<n;p++)u[(d*n+p)*4+3]!==0&&(p<s&&(s=p),p>a&&(a=p),d<i&&(i=d),d>c&&(c=d))}return a<0?null:{x:s,y:i,w:a-s+1,h:c-i+1}}#m(e){try{let t=e.session.composite(0),{w:n,h:o}=e.state.doc,s=n,i=o,a=-1,c=-1;for(let h=0;h<o;h++)for(let l=0;l<n;l++)t[(h*n+l)*4+3]!==0&&(l<s&&(s=l),l>a&&(a=l),h<i&&(i=h),h>c&&(c=h));return a<0?null:{x:s,y:i,w:a-s+1,h:c-i+1,cx:(s+a)/2,cy:(i+c)/2}}catch{return null}}#u(e,t=null){let n=e.state,{w:o,h:s}=n.doc,i=new Set,a=c=>c.toString(16).padStart(2,"0");for(let c of n.doc.layers)if(c.id!==t)for(let h=0;h<n.doc.frames.length;h++){let l;try{l=e.session.layerImage(c.id,h)}catch{continue}for(let u=0;u<o*s*4;u+=4)l[u+3]!==0&&i.add(`#${a(l[u])}${a(l[u+1])}${a(l[u+2])}`)}return[...i]}#y(e){try{let t=e.session.composite(0),n=new Set;for(let o=0;o<t.length;o+=4)t[o+3]!==0&&n.add(t[o]<<16|t[o+1]<<8|t[o+2]);return(e.state.doc.palette??[]).filter(o=>{let s=/^#([0-9a-f]{6})/i.exec(String(o));return s&&n.has(parseInt(s[1],16))}).length}catch{return null}}#g(e){let t=this.client(e),n=t.state;return n.pending===0&&t.connected?{}:{warning:n.pending?`includes ${n.pending} operation${n.pending===1?"":"s"} the room has not confirmed${t.connected?"":" \u2014 the connection dropped, reconnecting"}`:"the room connection dropped, reconnecting"}}async#w(e,t){let n=Math.trunc(Number(t));if(!Number.isFinite(n)||n<0)throw new Error(`\`seq\` is a document sequence \u2014 the number get_info reports and every draw_art result carries; got ${JSON.stringify(t)}`);let s=(await this.peek(e)).state.seq,i=await this.#s(`/documents/${encodeURIComponent(e)}/history/at/${n}`,{}).catch(async c=>{let l=((await this.#s(`/documents/${encodeURIComponent(e)}/history`,{}).catch(()=>null))?.versions??[]).map(d=>d.seq).filter(d=>Number.isFinite(d)),u=l.length?` Replay starts from an anchor: ${[...new Set(l)].sort((d,p)=>d-p).join(", ")}.`:"";throw new Error(`seq ${n} of ${e} cannot be rebuilt (${c.message}) \u2014 the document is at seq ${s}.${u}`)});if(!i||typeof i!="object")throw new Error(`seq ${n} of ${e} came back empty \u2014 the history has the operations but no document to replay them onto`);let a=this.core.openSession(i,this.author,1);return{past:!0,now:s,state:{doc:a.state().doc,seq:n,pending:0},session:a,connected:!0,welcomed:!0,close:()=>{try{a.close()}catch{}}}}async readArt({document:e,job:t,layer:n,frame:o=0,trim:s=!1,seq:i=null}){let a=await this.#o(e,t);if(i!=null){let h=await this.#w(a,i);try{return{document:a,at:h.state.seq,...h.session.readArt(this.#h(h.state.doc,n,a),o,{trim:s}),note:`the document as it stood at seq ${h.state.seq}, rebuilt from the history; the room is now at ${h.now}. A read of the past, not a restore.`}}finally{h.close()}}let c=await this.peek(a);return{document:a,...c.session.readArt(this.#c(a,n),o,{trim:s}),...this.#g(a)}}async readPng({document:e,job:t,layer:n=null,frame:o=0,seq:s=null}){let i=await this.#o(e,t),a=s!=null?await this.#w(i,s):null,c=a??await this.peek(i);try{let h=c.state.doc,l=a?{at:a.state.seq}:{};if(n==null)return{document:i,...l,png:c.session.png(o,{scale:1}),w:h.w,h:h.h};let u=c.session.cel(this.#h(h,n,i),o);return{document:i,...l,png:this.#d(h.w,h.h,u),w:h.w,h:h.h}}finally{a?.close()}}#d(e,t,n,o=1){let s=this.core.newDocument({w:e,h:t,name:"scratch",seed:1,now:Date.now()}),i=this.core.openSession(s,C(),1);try{let a=i.state();return i.apply([It(a.doc.layers[0].id,a.doc.frames[0].id,{x:0,y:0,w:e,h:t},n)],{now:Date.now()}),i.png(0,{scale:o})}finally{i.close()}}async#$(e,t,n,o,s,i=!1,a=null,c=!1,h=null){let l=await de(t).catch(j=>{throw new Error(`could not read the reference ${t}: ${j.code==="ENOENT"?"no such file":j.message}`)}),u=this.core.decodePng(await mr(t,l)),d=e.state.doc,p=Math.abs(u.w/u.h-d.w/d.h)<.01,w=c&&(!!a||!p),f=w?Ht(u,n.w,n.h,a):Ht(u,d.w,d.h,a),m=e.session.composite(o);h&&We(m,d.w,d.h,{x:0,y:0},h);let y=i?_e(m):m;i&&_e(f.pixels,f.pixels);let b=n.w,x=n.h,$=new Uint8Array((b*2+1)*x*4),v=(b*2+1)*4;for(let j=0;j<x;j++){for(let I=0;I<b;I++){let B=n.x+I,A=n.y+j,X=w?I:B,M=w?j:A,W=(M*f.w+X)*4,J=M<f.h&&X<f.w;$.set(J?f.pixels.subarray(W,W+4):[0,0,0,255],j*v+I*4);let ye=(A*d.w+B)*4;$.set(y.subarray(ye,ye+4),j*v+(b+1+I)*4)}$.set([255,0,255,255],j*v+b*4)}let _=f.placed,N=f.region.w===u.w&&f.region.h===u.h,D=!!a&&N,q=N?D?`\`referenceRect\` ${f.region.w}\xD7${f.region.h} at (${f.region.x}, ${f.region.y}) covers the whole ${u.w}\xD7${u.h} reference, so this is all of it`:`the reference is ${u.w}\xD7${u.h}`:`the region ${f.region.w}\xD7${f.region.h} at (${f.region.x}, ${f.region.y}) of the ${u.w}\xD7${u.h} reference`,V=f.region.w/_.w,E=`${V>=10?Math.round(V):V.toFixed(1)} reference px per canvas px`,z=w?N?`fitted whole into the ${n.w}\xD7${n.h} rect by ${f.by} (${_.w}\xD7${_.h}, centered; black where it does not reach; ${E}) \u2014 the whole reference against this part of the canvas${D?", as asked; name a SMALLER `referenceRect` to bring one part of it":"; pass `referenceRect` to bring one part of it instead"}`:`fitted into the ${n.w}\xD7${n.h} rect by ${f.by} (${_.w}\xD7${_.h}, centered; black where it does not reach; ${E}) \u2014 that part of the reference against this part of the canvas, at one scale`:_.w===d.w&&_.h===d.h?`brought to the ${d.w}\xD7${d.h} canvas (${E})`:`fitted whole to ${_.w}\xD7${_.h} by ${f.by}, centered on the ${d.w}\xD7${d.h} canvas (black where it does not reach; ${E})`,F=N&&_.w===d.w&&_.h===d.h?Math.abs(V-1)<.05?"":` \u2014 ${E}`:` \u2014 ${q}, ${z}${N&&!D&&!w&&(_.w!==d.w||_.h!==d.h)?"; pass `referenceRect` to bring one part of it to the grid instead":""}`;return{png:this.#d(b*2+1,x,$,s),note:F}}async preview({document:e,job:t,frame:n=0,scale:o=null,rect:s=null,rects:i=null,reference:a=null,referenceRect:c=null,values:h=!1,background:l=null,file:u=null,overwrite:d=!1,seq:p=null}){let w=await this.#E({document:e,job:t,frame:n,scale:o,rect:s,rects:i,reference:a,referenceRect:c,values:h,background:l,seq:p});if(u){let f=String(u),m=await ke(f,w.png,{overwrite:d,seq:w.seq});w.caption+=` \u2014 written to ${f}${m?" (replaced; anything that showed this path before shows the old picture)":""}`}return w}async#S(e){let t=await this.peek(e);if(t.state.pending>0&&await _r(t,3e3),!t.connected||!t.welcomed)throw new Error(`the room connection dropped \u2014 a render now could be behind what the room holds (last confirmed seq ${t.state.seq}). Reconnecting; try again in a moment.`);return t}#k(e,t,n,o,s,i,a){let c=o.map(m=>ue(m,t.w,t.h)),h=1,l=c.reduce((m,y)=>m+y.w,0)+h*(c.length-1),u=Math.max(...c.map(m=>m.h)),d=u+Re+2,p=new Uint8Array(l*d*4),w=e.session.composite(n),f=0;return c.forEach((m,y)=>{let b=Kt(w,t.w,m);We(b,m.w,m.h,m,a),i&&_e(b,b);for(let x=0;x<d;x++)for(let $=0;$<m.w;$++){let v=(x*l+f+$)*4;x>=m.h?p.set([255,0,255,255],v):p.set(b.subarray((x*m.w+$)*4,(x*m.w+$)*4+4),v)}if(xr(p,l,d,f,u+1,m.w,y+1),f+=m.w,f<l){for(let x=0;x<d;x++)p.set([255,0,255,255],(x*l+f)*4);f+=h}}),{png:this.#d(l,d,p,s),wins:c,w:l,h:d}}async#E({document:e,job:t,frame:n=0,scale:o=null,rect:s=null,rects:i=null,reference:a=null,referenceRect:c=null,values:h=!1,background:l=null,seq:u=null}){let d=yr(l),p=await this.#o(e,t),w=u!=null?await this.#w(p,u):null;try{return await this.#v({room:p,view:w??await this.#S(p),past:w,frame:n,scale:o,rect:s,rects:i,reference:a,referenceRect:c,values:h,bg:d})}finally{w?.close()}}async#v({room:e,view:t,past:n,frame:o,scale:s,rect:i,rects:a,reference:c,referenceRect:h,values:l,bg:u}){let d=t,{warning:p}=n?{}:this.#g(e),w=d.state.seq,f=n?` (rebuilt from the history; the room is now at ${n.now})`:"",m=d.state.doc;if(Array.isArray(a)&&a.length){if(c)throw new Error("one rect at a time against a reference \u2014 `rects` tiles crops of the render alone");let E=a.reduce((M,W)=>M+ue(W,m.w,m.h).w,0)+a.length-1,z=Math.max(...a.map(M=>ue(M,m.w,m.h).h))+Re+2,F=Number.isInteger(s)&&s>0?s:Jt(E,z),j=Math.max(1,Math.min(F,Math.floor(8192/Math.max(E,z,1)))),{png:I,wins:B}=this.#k(d,m,o,a,j,l,u),A=j<F?` \u2014 asked for \xD7${F}, held to \xD7${j} so a side stays under 8192px; fewer or smaller rects to look closer`:"",X=B.map((M,W)=>`${W+1}${a[W]?.label?` ${String(a[W].label).slice(0,48)}`:""} ${M.w}\xD7${M.h} at (${M.x},${M.y})`).join(", ");return{png:I,seq:w,caption:`${e} at seq ${w}${f}, frame ${o+1}: ${B.length} crops of ${m.w}\xD7${m.h} side by side at \xD7${j}, magenta between, each numbered in the strip under it \u2014 ${X}${l?", values only":""}${Vt(u)}${A}${p?` \u2014 ${p}`:""}`}}let y=i?ue(i,m.w,m.h):null,b=y?y.w:m.w,x=y?y.h:m.h,$=Number.isInteger(s)&&s>0?s:Jt(c?b*2:b,x),v=Math.max(1,Math.min($,Math.floor(8192/Math.max(c?b*2:b,x,1)))),_=y?`${y.w}\xD7${y.h} at (${y.x},${y.y}) of ${m.w}\xD7${m.h}`:`${m.w}\xD7${m.h}`,N=v<$?` \u2014 asked for \xD7${$}, held to \xD7${v} so a side stays under 8192px; render a smaller rect to look closer`:"",D=Vt(u);if(c){let{png:E,note:z}=await this.#$(d,String(c),y??{x:0,y:0,w:m.w,h:m.h},o,v,l,h,!!y,u);return{png:E,seq:w,caption:`${e} at seq ${w}${f}, frame ${o+1}: reference (left) beside the render (right), ${_} at \xD7${v}${l?", values only":""}${D}${z}${N}${p?` \u2014 ${p}`:""}. Per object, say how each is built \u2014 count the faces, name the light, say where the shadow falls \u2014 and what differs; "reads as" is not a verdict.`}}let q=y??{x:0,y:0,w:m.w,h:m.h};return{png:l||u?this.#d(b,x,(()=>{let E=Kt(d.session.composite(o),m.w,q);return We(E,b,x,q,u),l?_e(E,E):E})(),v):d.session.png(o,{scale:v,...y?{rect:y}:{}}),seq:w,caption:`${e} at seq ${w}${f}, frame ${o+1}: ${_} at \xD7${v} (${b*v}\xD7${x*v}px)${l?", values only \u2014 squint: is there a focal point, and where is the darkest dark":""}${D}${N}${p?` \u2014 ${p}`:""}`}}async sheet({document:e,job:t,columns:n=4,scale:o=2}){let s=await this.#o(e,t),i=await this.peek(s);return{png:i.session.contactSheet({columns:n,scale:o}),caption:`${s}, ${i.state.doc.frames.length} frames, numbered left to right`}}async documents(){let e=[...this.jobs.entries()].map(([c,h])=>({job:c,document:h.room,intent:h.intent})),t=[...this.rooms.keys()],n=null,o=null,s=null,i=this.control?await this.control("/documents",{}).catch(()=>null):null;if(i)n=i.documents?.map(c=>c.id)??null,o=Array.isArray(i.folders)?i.folders.map(c=>typeof c=="string"?c:c?.path??c?.name).filter(Boolean):null,s=i.documents?Object.fromEntries(i.documents.filter(c=>c.folder).map(c=>[c.id,c.folder])):null;else if(this.serverUrl){let c=this.serverUrl.replace(/^ws/,"http").replace(/\/$/,"");n=await fetch(`${c}/documents`).then(h=>h.ok?h.json():null).then(h=>h?.documents?.map(l=>l.id)).catch(()=>null)}return{documents:n?[...new Set([...t,...n])]:t,jobs:e,open:t,...o?{folders:o}:{},...s?{filed:s}:{}}}async createFolder({name:e}){if(!this.control)throw new Error("no library here: this Sprite has no accounts, so there are no folders");let t=String(e??"").trim();if(!t)throw new Error("a folder needs a name");let n=await this.folders();if(n.includes(t))return{folder:t,created:!1,folders:n};let o=t.split("/");for(let s=1;s<=o.length;s++){let i=o.slice(0,s).join("/");n.includes(i)||(await this.control("/documents/folders",{method:"POST",body:{name:i}}),n.push(i))}return{folder:t,created:!0,folders:await this.folders()}}async moveDocuments({documents:e,folder:t=null,make:n=!1}){if(!this.control)throw new Error("no library here: this Sprite has no accounts, so there are no folders");let o=(Array.isArray(e)?e:[e]).map(String).filter(Boolean);if(!o.length)throw new Error("say which documents");let s=t===null||t===""?null:String(t).trim();s&&n&&await this.createFolder({name:s});let i=await this.control("/documents/move",{method:"POST",body:{ids:o,folder:s}});return{moved:o,folder:s,ok:i?.ok!==!1}}async folders(){let e=await this.control("/documents",{});return Array.isArray(e?.folders)?e.folders.map(t=>typeof t=="string"?t:t?.path??t?.name).filter(Boolean):[]}takeRequests(){let e=this.asked.splice(0,this.asked.length);return{requests:e,note:e.length?"Each says what it wants. Where `room` is set, answer in that document. Where it is null the request came from the library and wants a new sprite \u2014 call new_sprite and work there, and do not touch `askedIn`, which is only the room the words travelled through. The person is watching.":"Nobody has asked for anything."}}#c(e,t){return this.#h(this.client(e).state.doc,t,e)}async#b(e,t){let n=this.client(e.room).state.doc;if(typeof t!="string"||t==="")return{id:this.#h(n,t,e.room),added:null};if(n.layers.some(s=>s.name===t||s.id===t))return{id:this.#h(n,t,e.room),added:null};let o=qe(t,n.layers.map(s=>s.name));if(o)throw new Error(`no layer ${JSON.stringify(t)} in ${e.room} \u2014 did you mean ${JSON.stringify(o)}? A name this close to one that exists is a typo, and making it would put this pass on a layer nobody is looking at. add_layer({ name }) if it really is a new one.`);return await this.addLayer({job:e.job,name:t}),{id:this.#c(e.room,t),added:t}}#h(e,t,n){if(t!=null&&t!==""){let o=typeof t=="number"?e.layers[t]:e.layers.find(s=>s.name===t||s.id===t);if(!o)throw new Error(`no layer ${JSON.stringify(t)} in ${n}`);return o.id}return e.layers[e.layers.length-1].id}async drawArt({job:e,rows:t,colors:n,x:o=0,y:s=0,center:i=!1,clear:a=!1,layer:c,frame:h=0,label:l,palette:u="add",rect:d=null}){let p=this.resolve(e),w=this.client(p.room),f=t,m={x:o,y:s},y=a;if(d){let g=ue(d,Math.max(...t.map(R=>R.length),1),t.length);if(f=t.slice(g.y,g.y+g.h).map(R=>R.slice(g.x,g.x+g.w).padEnd(g.w,".")),m={x:g.x,y:g.y},a){let R=[..."~^`|"].find(S=>!(S in n))??"\xA1";f=f.map(S=>S.replace(/[. ]/g,R)),n={...n,[R]:null},y=!1}}let b=new Set((w.state.doc.palette??[]).map(g=>String(g).toLowerCase())),x=(()=>{try{return Uint8Array.from(w.session.composite(h))}catch{return null}})(),{id:$,added:v}=c!=null?await this.#b(p,c):{id:p.layer??this.#c(p.room,null),added:null},_=w.session.drawArt(f,n,{layer:$,at:h,x:m.x,y:m.y,center:d?!1:i,clear:y,addToPalette:u!=="keep"}),{committed:N}=await this.submit(p.job,l||"draw_art",_),D=(this.client(p.room).state.doc.palette??[]).map(g=>String(g).toLowerCase()).filter(g=>!b.has(g)),q=w.state.doc,V=Math.max(...f.map(g=>g.length),0),E=i&&!d?{x:Math.round((q.w-V)/2),y:Math.round((q.h-f.length)/2)}:m,z=0,F=0;for(let g=0;g<f.length;g++){let R=E.y+g;for(let S=0;S<f[g].length;S++){let oe=f[g][S];if(oe==="."||oe===" ")continue;let be=E.x+S;be<0||R<0||be>=q.w||R>=q.h?F++:z++}}let j=z;if(N&&x)try{let g=w.session.composite(h),R=0;for(let S=0;S<g.length;S+=4)(g[S]!==x[S]||g[S+1]!==x[S+1]||g[S+2]!==x[S+2]||g[S+3]!==x[S+3])&&R++;j=R}catch{}let I=[],B=w.state.doc.layers.length-1;if(u==="replace"&&N){let g=L=>typeof L=="string"&&/^#[0-9a-f]{6}$/i.test(L)?L.toLowerCase():null,R=d?null:new Set(f.flatMap(L=>[...L])),S=Object.entries(n).filter(([L,sn])=>g(sn)&&(R===null||R.has(L))),oe=[...new Set(S.map(([,L])=>g(L)))],be=new Set(oe);I=[...new Set(Object.values(n).map(g).filter(L=>L&&!be.has(L)))];let on=B>0?this.#u(this.client(p.room),$):[],Qe=[...new Set([...oe,...on])];Qe.length&&await this.submit(p.job,"set_palette",[{t:"setPalette",colors:te(Qe,"hue")}])}let A=(this.client(p.room).state.doc.palette??[]).length,X=this.#y(this.client(p.room))??A,M=(d?`the file's \u2014 the whole picture's, not the ${f[0]?.length??0}\xD7${f.length} that was drawn; nothing outside the rect moved`:"this drawing's")+(u==="replace"&&B>0?`, and what the other ${B} layer${B===1?" is":"s are"} drawn in \u2014 a replace is of the document, so it keeps them`:""),W=I.length?`; ${I.length} in \`colors\` landed on no pixel and ${I.length===1?"was":"were"} left out: ${I.join(" ")}`:"",J=u==="replace"&&A>48?$r(this.client(p.room).state.doc.palette??[]):{pairs:[],total:0,crowded:0},ye=J.crowded*3>A,nn=J.pairs.length&&!ye?` \u2014 ${A} colors, and ${J.total} pair${J.total===1?"":"s"} of them within ${Qt} RGB of each other (${J.pairs.map(g=>`${g.a}\u2248${g.b}`).join(", ")}${J.total>J.pairs.length?", \u2026":""}): ramps that read alike, and a merge if they are not separate materials`:"",Ne=F?`${F} pixel${F===1?"":"s"} of the ${V}\xD7${f.length} grid at (${E.x},${E.y}) fell outside the ${q.w}\xD7${q.h} canvas and were not drawn \u2014 resize_canvas first, or generate at the canvas's size`:"",ge=u==="replace"&&N?{note:`palette replaced: ${A} color${A===1?"":"s"}, ${M}${W}${nn}`}:u==="keep"&&N?{note:`palette kept at ${A}: this drawing's colors are on the canvas and not in the palette`}:D.length?{added:te(D,"hue"),note:`${D.length} color${D.length===1?"":"s"} joined the palette${A>48||A>X*2?` \u2014 ${A} entries now and ${X} with a pixel on them`:""} \u2014 for a generated piece redrawn from a script, pass \`palette: "replace"\` on this call and the palette is exactly what you drew; set_palette({ prune: true }) is the user's document and is theirs to ask for`}:{},rn=Ne?{...ge,note:ge.note?`${ge.note}; ${Ne}`:Ne}:ge;return{...this.#t(p.room),drew:d?`${f[0]?.length??0}\xD7${f.length} at (${m.x},${m.y})`:`${t[0]?.length??0}\xD7${t.length}`,changed:j,...v?{layerAdded:v}:{},...j!==z?{inked:z}:{},committed:N,...rn}}async resizeCanvas({job:e,w:t,h:n,anchor:o="center",clear:s=!1}){let i=this.resolve(e),a=this.client(i.room).state,c=Math.max(1,Math.min(1024,Math.round(Number(t)||a.doc.w))),h=Math.max(1,Math.min(1024,Math.round(Number(n)||a.doc.h)));if(c===a.doc.w&&h===a.doc.h)return s&&await this.#x(i),{...this.#t(i.room),resized:s?"already that size; cleared":"already that size"};let l=String(o??"center").toLowerCase(),u=l.includes("left")?0:l.includes("right")?2:1,d=l.includes("top")?0:l.includes("bottom")?2:1,p=Math.round((c-a.doc.w)*u/2),w=Math.round((h-a.doc.h)*d/2);await this.submit(i.job,"resize_canvas",[{t:"resize",w:c,h,dx:p,dy:w}]),s&&await this.#x(i);let f=this.#i(i.room,je(c,h)??Be(c,h));return{...this.#t(i.room),resized:`${a.doc.w}\xD7${a.doc.h} \u2192 ${c}\xD7${h}, ${s?"cleared":`the art kept at ${p},${w}`}`,...f?{shape:f}:{}}}async closeDocument({document:e}){let t=await this.#a(e,null),n=this.rooms.get(t);if(!n)return{closed:t,open:!1};for(let[o,s]of this.jobs)s.room===t&&this.finish(o);return n.closing=!0,clearTimeout(n.retry),n.client.close(),this.rooms.delete(t),{closed:t,open:!1}}async drawAnimation({job:e,frames:t,colors:n,fps:o,layer:s,label:i}){let a=this.resolve(e),c=this.client(a.room),{id:h}=s!=null?await this.#b(a,s):{id:a.layer??this.#c(a.room,null)},l=c.state.doc.frames.length,u=t.length-l;if(u>0){let p=[],w=c.state.doc.frames[l-1]?.index??"V";for(let f=0;f<u;f++)w=w+"V",p.push({t:"addFrame",id:C(),index:w,durMs:Je(o)});await this.submit(a.job,"add frames",p)}if(o){let p=Je(o);await this.submit(a.job,"set fps",c.state.doc.frames.map(w=>({t:"setFrameDur",id:w.id,durMs:p})))}let d=c.session.drawAnimation(t,n,{layer:h});return await this.submit(a.job,i||"draw_animation",d),{...this.#t(a.room),wrote:`${t.length} frames`}}async addLayer({job:e,name:t}){let n=this.resolve(e),o=this.client(n.room).state,s=o.doc.layers[o.doc.layers.length-1];return await this.submit(n.job,"add_layer",[{t:"addLayer",id:C(),index:(s?.index??"V")+"V",name:t||`Layer ${o.doc.layers.length+1}`,visible:!0,locked:!1,opacity:1}]),this.#t(n.room)}async addFrame({job:e,copy:t=!1}){let n=this.resolve(e),o=this.client(n.room),s=o.state,i=s.doc.frames[s.doc.frames.length-1],a=C(),c=[{t:"addFrame",id:a,index:(i?.index??"V")+"V",durMs:i?.durMs??83}];if(t&&i)for(let h of s.doc.layers){let l=o.session.cel(h.id,i.id);l.every(u=>u===0)||c.push(Ge(h.id,a,s.doc,l))}return await this.submit(n.job,"add_frame",c),this.#t(n.room)}async setPalette({job:e,colors:t,prune:n=!1}){let o=this.resolve(e),s;if(n){let i=this.client(o.room),a=i.state,c=new Set;for(let l of a.doc.layers)for(let u of a.doc.frames){let d=i.session.cel(l.id,u.id);for(let p=0;p<d.length;p+=4)d[p+3]!==0&&c.add(`#${[d[p],d[p+1],d[p+2]].map(w=>w.toString(16).padStart(2,"0")).join("")}`)}let h=a.doc.palette??[];s=h.filter(l=>c.has(String(l).toLowerCase()));for(let l of c)s.some(u=>String(u).toLowerCase()===l)||s.push(l);return s=te(s,"hue"),await this.submit(o.job,"set_palette",[{t:"setPalette",colors:s}]),{...this.#t(o.room),palette:s.length,pruned:h.length-s.length}}return s=te(t,"hue"),await this.submit(o.job,"set_palette",[{t:"setPalette",colors:s}]),{...this.#t(o.room),palette:s.length}}async setFps({job:e,fps:t}){let n=this.resolve(e),o=this.client(n.room).state,s=Je(t);return await this.submit(n.job,"set_fps",o.doc.frames.map(i=>({t:"setFrameDur",id:i.id,durMs:s}))),{...this.#t(n.room),fps:t}}async#x(e){let t=this.client(e.room).state,n=new Uint8Array(t.doc.w*t.doc.h*4),o=[];for(let s of t.doc.layers)for(let i of t.doc.frames)o.push(Ge(s.id,i.id,t.doc,n));o.length&&await this.submit(e.job,"clear",o)}async clearCel({job:e,layer:t,frame:n=0}){let o=this.resolve(e),i=this.client(o.room).state,a=this.#c(o.room,t??o.layer),c=i.doc.frames[n];if(!c)throw new Error(`no frame ${n} in ${o.room}`);let h=new Uint8Array(i.doc.w*i.doc.h*4);return await this.submit(o.job,"clear",[Ge(a,c.id,i.doc,h)]),this.#t(o.room)}async trim({job:e,margin:t=0,center:n=!1}){let o=this.resolve(e),s=this.client(o.room),i=s.state,a=this.#r(s),c=i.doc.layers.length>1?` every one of the ${i.doc.layers.length} layers`:"";if(n){if(!a)return{...this.#t(o.room),centered:"nothing drawn"};let u=Math.floor((i.doc.w-a.w)/2)-a.x,d=Math.floor((i.doc.h-a.h)/2)-a.y;if(!u&&!d)return{...this.#t(o.room),centered:"already centered"};await this.submit(o.job,"center_art",[{t:"resize",w:i.doc.w,h:i.doc.h,dx:u,dy:d}]);let p=[(i.doc.w-a.w)%2?"width":null,(i.doc.h-a.h)%2?"height":null].filter(Boolean);return{...this.#t(o.room),centered:`the ${a.w}\xD7${a.h} of art${c?` on${c}`:""} moved ${u},${d}${p.length?` \u2014 the ${p.join(" and ")} cannot be split evenly, so it sits half a pixel up-left`:""}`}}if(!a)return{...this.#t(o.room),trimmed:"nothing drawn"};let h=a.w+t*2,l=a.h+t*2;return h>=i.doc.w&&l>=i.doc.h?{...this.#t(o.room),trimmed:"already tight"}:(await this.submit(o.job,"trim_canvas",[{t:"resize",w:h,h:l,dx:-a.x+t,dy:-a.y+t}]),{...this.#t(o.room),trimmed:`${h}\xD7${l}${c?`, to the art on${c}`:""}`})}},Sr=new Set(["new_sprite","begin_job","finish_job","draw_art","draw_animation","read_art","render_preview","render_animation","add_layer","add_frame","set_palette","set_fps","clear","trim_canvas","resize_canvas","close_document","get_info","list_documents","challenges","take_requests","create_folder","move_documents","push_source","pull_source"]);function Ge(r,e,t,n){return{t:"paintRegion",layer:r,frame:e,rect:{x:0,y:0,w:t.w,h:t.h},rle:kr(n)}}function kr(r){let e=[];if(r.length){let t=[r[0],r[1],r[2],r[3]],n=0,o=()=>{let s=n;do{let i=s&127;s>>=7,e.push(s?i|128:i)}while(s);e.push(...t)};for(let s=0;s<r.length;s+=4)r[s]===t[0]&&r[s+1]===t[1]&&r[s+2]===t[2]&&r[s+3]===t[3]?n++:(o(),t=[r[s],r[s+1],r[s+2],r[s+3]],n=1);o()}return Buffer.from(Uint8Array.from(e)).toString("base64")}function Er(r){let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return new Promise(t=>Yt(e,[r],()=>t()))}function Je(r){return!r||r<=0?83:Math.max(10,Math.round(1e3/r))}function vr(r,e,t=8e3){return new Promise(n=>{let o=r.onLeases,s=r.onLost,i=!1,a=h=>{i||(i=!0,clearTimeout(c),r.onLeases=o,r.onLost=s,n(h))};r.onLeases=h=>{o?.(h),h.some(l=>l.job===e)&&a("held")},r.onLost=h=>{s?.(h),h?.ops?.length||a("refused")};let c=setTimeout(()=>a("silent"),t);r.leases.some(h=>h.job===e)&&a("held")})}function Zt(r,e=8e3){return new Promise(t=>{let n=Date.now(),o=()=>{if(r.welcomed)return t(!0);if(Date.now()-n>e)return t(!1);setTimeout(o,20)};o()})}async function jr(r,e,t,{ms:n}={}){await Zt(r,n);let o=()=>{let i=vr(r,e,n);return r.lease("acquire",{job:e,...t}),i},s=await o();return s==="refused"&&!r.welcomed&&await Zt(r,n)&&(s=await o()),s}function _r(r,e=400){return new Promise(t=>{let n=Date.now(),o=()=>{if(r.state.pending===0&&Date.now()-n>40||Date.now()-n>e)return t();setTimeout(o,10)};o()})}function Xt(){return(Date.now()^Math.floor(Math.random()*4294967295))>>>0}import{execFile as Ar}from"node:child_process";var Rr=2e4,Ke="a past seq is a room thing \u2014 the history lives beside the document in a room, and a local editor keeps none. Save each pass with render_preview({ file }) and stack them with references/judge.py",Tr=5e3,pe=class r{constructor({base:e,name:t="agent"}={}){this.base=String(e).replace(/\/$/,""),this.name=t,this.log=[],this.beat=setInterval(()=>void this.announce(),Tr),this.beat.unref&&this.beat.unref()}get kind(){return"local"}get where(){return this.base}supports(e){return Or.has(e)}static async probe(e,{timeoutMs:t=700}={}){try{let n=await fetch(`${e.replace(/\/$/,"")}/bridge/status`,{signal:AbortSignal.timeout(t)});if(!n.ok)return null;let o=await n.json();return o?.server==="sprite"?o:null}catch{return null}}async announce(){try{await fetch(`${this.base}/bridge/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:this.name,version:null}),signal:AbortSignal.timeout(2e3)})}catch{}}async call(e,t=[],n=Rr){let o;try{o=await(await fetch(`${this.base}/bridge/call`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:e,args:t,timeoutMs:n}),signal:AbortSignal.timeout(n+2e3)})).json()}catch(s){throw new Error(`lost contact with the Pixie editor at ${this.base}: ${s.message}`)}if(!o.ok)throw new Error(o.error);return this.note(e),o.result}note(e,t=""){this.log.unshift({at:Date.now(),tool:e,room:"local",detail:t}),this.log.length>200&&this.log.pop()}newSprite({name:e,w:t=U.w,h:n=U.h,intent:o,palette:s}){return this.call("newSprite",[{w:t,h:n,name:e,palette:s,intent:o,replace:!1}])}async challenges(){let e=await fetch(`${this.base}/news.json`).catch(()=>null);if(!e?.ok)throw new Error("this editor does not serve the themes \u2014 ask the user what to draw");let t=await e.json(),n=(o,s)=>o?{theme:o.theme,tags:o.tags,detail:o.detail??null,sizes:o.sizes??[],...o.day?{day:o.day}:{},postedAt:new Date(o.at).toISOString(),post:o.url}:{theme:null,note:`no ${s} prompt is known right now`};return{daily:n(t?.dailies,"daily"),weekly:n(t?.weekly,"weekly"),inktober:n(t?.inktober,"Inktober")}}async challenge(e){let n=(await this.challenges())[e];if(!n?.theme)throw new Error(e==="inktober"?"no Inktober prompt is known right now \u2014 it runs the 31 days of October. Ask the user what to draw.":`no ${e} theme is known right now \u2014 ask the user what to draw`);return n}beginJob({document:e,intent:t}){return this.call("beginJob",[{document:e,intent:t}])}finishJob({job:e}){return this.call("finishJob",[{job:e}])}async info({document:e,layers:t=!1}={}){if(t)throw new Error("a per-layer bbox is a room thing \u2014 the frozen editor reports no such detail. read_art({ layer, png }) per layer and measure them with references/pngio.py");let n=await this.call("info",[]);return{editor:this.base,...e?{asked:e}:{},...n}}readArt({document:e,layer:t,frame:n,seq:o=null}){if(o!=null)throw new Error(Ke);return this.call("readArt",[{document:e,layer:t,frame:n}])}async preview({document:e,frame:t,scale:n=null,rect:o=null,rects:s=null,reference:i=null,referenceRect:a=null,values:c=!1,background:h=null,file:l=null,overwrite:u=!1,seq:d=null}){if(o)throw new Error("the local editor cannot render a region \u2014 render the whole frame");if(s)throw new Error("the local editor cannot render regions \u2014 render the whole frame, or read_art({ png }) and tile the crops with references/compare.py");if(c)throw new Error("the local editor cannot render values only \u2014 read_art({ png }) and convert it, or run the squint test with references/compare.py");if(i||a)throw new Error("a reference beside the render is a room thing \u2014 in a local editor, read_art({ file }) and compare with references/compare.py");if(h)throw new Error("a background under the alpha is a room thing \u2014 in a local editor, read_art({ png }) and put it over one with references/render.py");if(d!=null)throw new Error(Ke);let p=await this.call("toDataURL",[t??null,Number.isInteger(n)&&n>0?n:8,e??null]),w=Ze(p.url),f=p.caption;if(l){let m=String(l),y=await ke(m,w,{overwrite:u});f+=` \u2014 written to ${m}${y?" (replaced; anything that showed this path before shows the old picture)":""}`}return{png:w,caption:f}}async readPng({document:e,frame:t=0,layer:n=null,seq:o=null}){if(o!=null)throw new Error(Ke);if(n!=null)throw new Error("one layer as a PNG is a room thing \u2014 in a local editor, read_art({ layer, file }) and render it with references/render.py");let s=await this.call("toDataURL",[t??null,1,e??null]),i=/(\d+)×(\d+)/.exec(s.caption??"");return{document:e??null,png:Ze(s.url),w:i?Number(i[1]):0,h:i?Number(i[2]):0}}async sheet({document:e,columns:t=0,scale:n=0}){let o=await this.call("toStripDataURL",[{document:e??null,columns:t,scale:n}]);return{png:Ze(o.url),caption:o.caption}}documents(){return this.call("listDocuments",[])}drawArt({job:e,rows:t,colors:n,x:o,y:s,center:i,clear:a,layer:c,frame:h,label:l,rect:u=null}){if(u){let d=Math.max(0,u.x|0),p=Math.max(0,u.y|0);t=t.slice(p,p+(u.h|0)).map(w=>w.slice(d,d+(u.w|0))),o=d,s=p,i=!1}return this.call("drawArt",[t,n,{job:e,x:o,y:s,center:i,clear:a,layer:c,frame:h,label:l}])}drawAnimation({job:e,frames:t,colors:n,fps:o,layer:s,label:i}){return this.call("drawAnimation",[{frames:t,colors:n,fps:o,job:e,layer:s,label:i}])}addLayer({name:e}){return this.call("addLayer",[e])}addFrame({copy:e=!1}){return this.call("addFrame",[{copy:!!e}])}setPalette({colors:e,prune:t=!1}){if(t)throw new Error("prune works in a room \u2014 in a local editor, pass the colors to keep");return this.call("setPalette",[e])}setFps({fps:e}){return this.call("setFps",[e])}clearCel({job:e,layer:t,frame:n}){return this.call("clear",[{job:e,layer:t,frame:n}])}trim({job:e,margin:t=0}){return this.call("trimCanvas",[{job:e,margin:t}])}setFrame({index:e}){return this.call("setFrame",[e])}setLayer({index:e}){return this.call("setLayer",[e])}select({document:e}){return this.call("selectDocument",[e])}closeDocument({document:e}){return this.call("closeDocument",[e??null])}undo(){return this.call("undo",[])}redo(){return this.call("redo",[])}async openEditor(){if((await r.probe(this.base))?.connected)return{ok:!0,message:`Editor already connected at ${this.base}`};await Pr(this.base);let t=Date.now()+1e4;for(;Date.now()<t;){if((await r.probe(this.base))?.connected)return{ok:!0,message:`Editor connected at ${this.base}`};await new Promise(o=>setTimeout(o,200))}return{ok:!1,message:`Opened ${this.base} but nothing connected \u2014 check the browser window.`}}close(){clearInterval(this.beat)}},Or=new Set(["new_sprite","begin_job","finish_job","draw_art","draw_animation","read_art","render_preview","render_animation","add_layer","add_frame","set_palette","set_fps","clear","trim_canvas","get_info","list_documents","challenges","open_editor","select_document","close_document","set_frame","set_layer","undo","redo"]);function Ze(r){let e=String(r??"").split(",")[1];if(!e)throw new Error("the editor returned something that was not an image");return Buffer.from(e,"base64")}function Pr(r){let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return new Promise(t=>Ar(e,[r],()=>t()))}function Xe(r="room"){return`Pixel art editor with live collaboration. ${r==="local"?`Documents are tabs in a browser on this machine; the user watches as you
7
+ work and can take the canvas back at any time.`:`Documents are rooms; other people and other agents may be in one with
4
8
  you, and they see what you do as you do it.`}
5
9
 
6
10
  A \`pixel-art\` SKILL, IF YOUR CLIENT LISTS ONE, IS LOADED BEFORE THE FIRST
7
11
  JOB: this block is the mechanics, the skill is the craft and the audit
8
12
  scripts. An agent did ten jobs from this block alone, never felt
9
- under-instructed, and found the tool that measures its work only once the
10
- user called it finished.
13
+ under-instructed, and met the audit scripts only after the user called its
14
+ art done.
11
15
 
12
16
  CALL new_sprite FIRST \u2014 before a script, a grid, or a thought about pixels.
13
17
  It needs w, h, a name and a line of intent, and puts a labeled document in
@@ -24,7 +28,7 @@ walls, mine one" is.
24
28
 
25
29
  JOBS. A job claims one document; drawing is refused without one. Looking
26
30
  (render_preview, read_art, get_info) needs none and between jobs sees the
27
- last finished \u2014 as does begin_job with no document. One job open: omit the
31
+ last finished THIS SESSION \u2014 as does begin_job with no document. One job open: omit the
28
32
  job argument. finish_job({ note }) says what shipped. If a call says the
29
33
  user stopped you, do NOT retry: say what you meant to do and ask.
30
34
 
@@ -32,13 +36,13 @@ WHAT THE USER SAYS BEATS EVERY DEFAULT \u2014 size, shape, palette, ratio,
32
36
  artist, view. Only when nobody said what it should look like do the
33
37
  defaults apply: 240\xD7126 (80\xD742 if they said "simple"), a three-quarter view
34
38
  (flat only if they said flat, side, front, top-down, icon or tile);
35
- challenges has the daily and weekly themes.
39
+ challenges: the daily, weekly and Inktober prompts.
36
40
 
37
41
  A BIG OR GENERATED GRID DOES NOT PASS THROUGH YOU: write it to a file and
38
42
  call draw_art with file. Do not ask abstract questions: commit to a good
39
- default and show something.`}var fr=Be("room"),_e=class{constructor({name:e="pixie",version:t=xe,tools:n=[],instructions:o=fr}={}){this.name=e,this.version=t,this.tools=n,this.instructions=o,this.client=null,this.onCall=null}async handle(e){if(!e||e.jsonrpc!=="2.0")return null;let t=e.id===void 0||e.id===null;try{let n=await this.#e(e);return t?null:{jsonrpc:"2.0",id:e.id,result:n}}catch(n){return t?null:{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:n?.message??String(n)}}}}async#e(e){switch(e.method){case"initialize":return this.client=e.params?.clientInfo??null,{protocolVersion:e.params?.protocolVersion??"2024-11-05",capabilities:{tools:{}},serverInfo:{name:this.name,version:this.version},instructions:this.instructions};case"notifications/initialized":case"notifications/cancelled":return{};case"ping":return{};case"tools/list":return{tools:this.tools.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))};case"tools/call":{let t=this.tools.find(n=>n.name===e.params?.name);if(!t)throw new Error(`unknown tool: ${e.params?.name}`);this.onCall?.(t.name,e.params?.arguments??{});try{return await t.run(e.params?.arguments??{})}catch(n){return{isError:!0,content:[{type:"text",text:n?.message??String(n)}]}}}case"resources/list":return{resources:[]};case"prompts/list":return{prompts:[]};default:throw new Error(`unknown method: ${e.method}`)}}serve(e=process.stdin,t=process.stdout){let n="";return e.setEncoding("utf8"),e.on("data",async o=>{n+=o;let s;for(;(s=n.indexOf(`
43
+ default and show it.`}var Nr=Xe("room"),Oe=class{constructor({name:e="pixie",version:t=ce,tools:n=[],instructions:o=Nr}={}){this.name=e,this.version=t,this.tools=n,this.instructions=o,this.client=null,this.onCall=null}async handle(e){if(!e||e.jsonrpc!=="2.0")return null;let t=e.id===void 0||e.id===null;try{let n=await this.#e(e);return t?null:{jsonrpc:"2.0",id:e.id,result:n}}catch(n){return t?null:{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:n?.message??String(n)}}}}async#e(e){switch(e.method){case"initialize":return this.client=e.params?.clientInfo??null,{protocolVersion:e.params?.protocolVersion??"2024-11-05",capabilities:{tools:{}},serverInfo:{name:this.name,version:this.version},instructions:this.instructions};case"notifications/initialized":case"notifications/cancelled":return{};case"ping":return{};case"tools/list":return{tools:this.tools.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))};case"tools/call":{let t=this.tools.find(n=>n.name===e.params?.name);if(!t)throw new Error(`unknown tool: ${e.params?.name}`);this.onCall?.(t.name,e.params?.arguments??{});try{return await t.run(e.params?.arguments??{})}catch(n){return{isError:!0,content:[{type:"text",text:n?.message??String(n)}]}}}case"resources/list":return{resources:[]};case"prompts/list":return{prompts:[]};default:throw new Error(`unknown method: ${e.method}`)}}serve(e=process.stdin,t=process.stdout){let n="";return e.setEncoding("utf8"),e.on("data",async o=>{n+=o;let s;for(;(s=n.indexOf(`
40
44
  `))!==-1;){let i=n.slice(0,s).trim();if(n=n.slice(s+1),!i)continue;let a;try{a=JSON.parse(i)}catch{continue}let c=await this.handle(a);c&&t.write(JSON.stringify(c)+`
41
- `)}}),this}};var le=(r,e)=>{let t=process.argv.indexOf(`--${r}`);return t>-1?process.argv[t+1]:e},We=process.env.SPRITE_EDITOR||"http://127.0.0.1:4242",Ae=process.env.SPRITE_SERVER||"ws://127.0.0.1:4243",wr=new URL("./sprite_core.wasm",import.meta.url);function gr(r){let e=String(r??"").trim();return!e||!/^[a-z0-9]+([-_][a-z0-9]+)*$/.test(e)?e||"an agent":e.split(/[-_]/).map(t=>yr.has(t)?t.toUpperCase():t[0].toUpperCase()+t.slice(1)).join(" ")}var yr=new Set(["cli","ai","api","ide","mcp","sdk","gpt","llm"]);function br(r){let e=new WebSocket(r),t={readyState:0,onopen:null,onmessage:null,onclose:null,send:n=>e.send(n),close:()=>e.close()};return e.addEventListener("open",()=>{t.readyState=1,t.onopen?.()}),e.addEventListener("message",n=>t.onmessage?.(n.data)),e.addEventListener("close",()=>{t.readyState=3,t.onclose?.()}),e.addEventListener("error",()=>{}),t}async function Wt(r,{timeoutMs:e=700}={}){if(await Je(r,{timeoutMs:e}))return!0;try{let t=await fetch(`${E(r)}/health`,{signal:AbortSignal.timeout(e)});return!t.ok||!(t.headers.get("content-type")??"").includes("json")?!1:(await t.json().catch(()=>null))?.ok===!0}catch{return!1}}async function xr({editor:r=We,server:e=Ae,allowHost:t=!0,publicServer:n=re}={}){if(n)return{kind:"room",url:n,why:`the Pixie this agent belongs to, at ${E(n)}`};let o=await he.probe(r);return o?{kind:"local",url:r,why:o.connected?`a Pixie editor is open at ${r}`:`a Pixie server is running at ${r}, with no editor open yet`}:await Wt(e)?{kind:"room",url:e,why:`a room server is running at ${e}`}:t?{kind:"room",url:e,start:!0,why:"nothing was running, so this process is the server"}:{kind:"room",url:e,why:`nothing is running yet; waiting for one at ${e}`}}async function $r({kind:r=null,editor:e=We,server:t=Ae,wasm:n=wr,name:o="agent",allowHost:s=!0}={}){let i=r?{kind:r,url:r==="local"?e:t,why:"you said so"}:await xr({editor:e,server:t,allowHost:s}),a,c=null,h=null;if(i.kind==="local")a=new he({base:i.url,name:o}),a.announce();else{i.start;let d=Ve(i.url),p=n instanceof Uint8Array?n:await mr(n);c=await me.load(p);let w=await d;a=new je(c,{author:I(),name:o,connect:(f,m={})=>{let g=new URLSearchParams;m.w&&g.set("w",String(m.w)),m.h&&g.set("h",String(m.h)),m.name&&g.set("name",m.name);let y=g.toString();return br(`${w}/rooms/${f}${y?`?${y}`:""}`)},probe:()=>Wt(i.url)}),a.serverUrl=w,a.getToken=async f=>{let m=await tt(i.url,f);if(m!==void 0)return m;if(await ue(i.url))throw new Error(de(i.url))},a.createDocument=async f=>{let m=await nt(i.url,f);if(m!==void 0)return m;if(await ue(i.url))throw new Error(de(i.url))},a.control=async(f,m)=>{let g=await rt(i.url,f,m);if(g!==void 0)return g;throw new Error(await ue(i.url)?de(i.url):"no library here: this Sprite has no accounts, so there are no folders")},a.openControl=async(f,m={})=>{if(await ue(i.url))throw new Error(de(i.url));let g=await fetch(`${E(i.url)}${f}`,{method:m.method??"GET",headers:m.body!=null?{"Content-Type":"application/json"}:{},body:m.body!=null?JSON.stringify(m.body):void 0}),y=await g.json().catch(()=>({}));if(!g.ok)throw new Error(y?.error?String(y.error):`the server said ${g.status}`);return y},a.editorUrl=E(i.url),a.newsUrl=`${E(i.url)}/news.json`,a.hosted=h}let l=new _e({tools:Nt(a),instructions:Be(a.kind)}),u=l.handle.bind(l);return l.handle=async d=>{let p=await u(d);return d?.method==="initialize"&&l.client?.name&&(a.name=gr(l.client.name),a.announce()),p},{core:c,backend:a,mcp:l,chosen:i}}var Bt=null;function ue(r){return Bt??=et(r).catch(()=>!1),Bt}function Sr(r=process.argv){let e=r[1]??"";return/[\\/]pixie-mcp$/.test(e)?"pixie-mcp":/[\\/]sprite-mcp$/.test(e)?"sprite-mcp":"npx pixie-mcp"}function de(r,e=Sr()){return`this machine has not been given a credential for ${E(r)} yet. Run \`${e} login\` once, in a terminal \u2014 it opens a browser, and one button in it is the whole of it.`}if(ft(import.meta.url)){let r=le("server",null)?"room":le("editor",null)?"local":null;if(process.argv.includes("login")){let e=le("server",re||Ae);try{let t=await dt(e,{onUrl:n=>process.stderr.write(`
45
+ `)}}),this}};var fe=(r,e)=>{let t=process.argv.indexOf(`--${r}`);return t>-1?process.argv[t+1]:e},Ye=process.env.SPRITE_EDITOR||"http://127.0.0.1:4242",Pe=process.env.SPRITE_SERVER||"ws://127.0.0.1:4243",Mr=new URL("./sprite_core.wasm",import.meta.url);function Cr(r){let e=String(r??"").trim();return!e||!/^[a-z0-9]+([-_][a-z0-9]+)*$/.test(e)?e||"an agent":e.split(/[-_]/).map(t=>Lr.has(t)?t.toUpperCase():t[0].toUpperCase()+t.slice(1)).join(" ")}var Lr=new Set(["cli","ai","api","ide","mcp","sdk","gpt","llm"]);function Ur(r){let e=new WebSocket(r),t={readyState:0,onopen:null,onmessage:null,onclose:null,send:n=>e.send(n),close:()=>e.close()};return e.addEventListener("open",()=>{t.readyState=1,t.onopen?.()}),e.addEventListener("message",n=>t.onmessage?.(n.data)),e.addEventListener("close",()=>{t.readyState=3,t.onclose?.()}),e.addEventListener("error",()=>{}),t}async function tn(r,{timeoutMs:e=700}={}){if(await nt(r,{timeoutMs:e}))return!0;try{let t=await fetch(`${k(r)}/health`,{signal:AbortSignal.timeout(e)});return!t.ok||!(t.headers.get("content-type")??"").includes("json")?!1:(await t.json().catch(()=>null))?.ok===!0}catch{return!1}}async function Dr({editor:r=Ye,server:e=Pe,allowHost:t=!0,publicServer:n=se}={}){if(n)return{kind:"room",url:n,why:`the Pixie this agent belongs to, at ${k(n)}`};let o=await pe.probe(r);return o?{kind:"local",url:r,why:o.connected?`a Pixie editor is open at ${r}`:`a Pixie server is running at ${r}, with no editor open yet`}:await tn(e)?{kind:"room",url:e,why:`a room server is running at ${e}`}:t?{kind:"room",url:e,start:!0,why:"nothing was running, so this process is the server"}:{kind:"room",url:e,why:`nothing is running yet; waiting for one at ${e}`}}async function qr({kind:r=null,editor:e=Ye,server:t=Pe,wasm:n=Mr,name:o="agent",allowHost:s=!0}={}){let i=r?{kind:r,url:r==="local"?e:t,why:"you said so"}:await Dr({editor:e,server:t,allowHost:s}),a,c=null,h=null;if(i.kind==="local")a=new pe({base:i.url,name:o}),a.announce();else{i.start;let d=rt(i.url),p=n instanceof Uint8Array?n:await Ir(n);c=await xe.load(p);let w=await d;a=new Te(c,{author:C(),name:o,connect:(f,m={})=>{let y=new URLSearchParams;m.w&&y.set("w",String(m.w)),m.h&&y.set("h",String(m.h)),m.name&&y.set("name",m.name);let b=y.toString();return Ur(`${w}/rooms/${f}${b?`?${b}`:""}`)},probe:()=>tn(i.url)}),a.serverUrl=w,a.getToken=async f=>{let m=await lt(i.url,f);if(m!==void 0)return m;if(await me(i.url))throw new Error(we(i.url))},a.createDocument=async f=>{let m=await ut(i.url,f);if(m!==void 0)return m;if(await me(i.url))throw new Error(we(i.url))},a.control=async(f,m)=>{let y=await dt(i.url,f,m);if(y!==void 0)return y;throw new Error(await me(i.url)?we(i.url):"no library here: this Sprite has no accounts, so there are no folders")},a.openControl=async(f,m={})=>{if(await me(i.url))throw new Error(we(i.url));let y=await fetch(`${k(i.url)}${f}`,{method:m.method??"GET",headers:m.body!=null?{"Content-Type":"application/json"}:{},body:m.body!=null?JSON.stringify(m.body):void 0}),b=await y.json().catch(()=>({}));if(!y.ok)throw new Error(b?.error?String(b.error):`the server said ${y.status}`);return b},a.editorUrl=k(i.url),a.newsUrl=`${k(i.url)}/news.json`,a.hosted=h}let l=new Oe({tools:Wt(a),instructions:Xe(a.kind)}),u=l.handle.bind(l);return l.handle=async d=>{let p=await u(d);return d?.method==="initialize"&&l.client?.name&&(a.name=Cr(l.client.name),a.announce()),p},{core:c,backend:a,mcp:l,chosen:i}}var en=null;function me(r){return en??=ht(r).catch(()=>!1),en}function zr(r=process.argv){let e=r[1]??"";return/[\\/]pixie-mcp$/.test(e)?"pixie-mcp":/[\\/]sprite-mcp$/.test(e)?"sprite-mcp":"npx pixie-mcp"}function we(r,e=zr()){return`this machine has not been given a credential for ${k(r)} yet. Run \`${e} login\` once, in a terminal \u2014 it opens a browser, and one button in it is the whole of it.`}if(kt(import.meta.url)){let r=fe("server",null)?"room":fe("editor",null)?"local":null;if(process.argv.includes("login")){let e=fe("server",se||Pe);try{let t=await $t(e,{onUrl:n=>process.stderr.write(`
42
46
  ${n}
43
47
  `),label:"the Pixie MCP server"});process.stderr.write(`
44
48
  This machine can now draw as ${t.email??t.name??"you"}.
@@ -46,6 +50,6 @@ default and show something.`}var fr=Be("room"),_e=class{constructor({name:e="pix
46
50
  `)}catch(t){process.stderr.write(`
47
51
  ${t.message}
48
52
 
49
- `),process.exit(1)}}else{let{mcp:e,chosen:t}=await $r({kind:r,editor:le("editor",We),server:le("server",Ae),allowHost:!process.argv.includes("--no-host")});process.stderr.write(`sprite-mcp \u2192 ${t.kind} (${t.why})
50
- `),e.serve(),t.kind==="room"&&(async()=>(await oe(t.url))?.token||await ue(t.url)&&process.stderr.write(`sprite-mcp \u2192 ${de(t.url)}
51
- `))()}}export{We as DEFAULT_EDITOR,Ae as DEFAULT_SERVER,Sr as commandName,$r as createServer,xr as detect,gr as presentable,Wt as probeRooms,de as signInFirst,br as websocketTransport};
53
+ `),process.exit(1)}}else{let{mcp:e,chosen:t}=await qr({kind:r,editor:fe("editor",Ye),server:fe("server",Pe),allowHost:!process.argv.includes("--no-host")});process.stderr.write(`sprite-mcp \u2192 ${t.kind} (${t.why})
54
+ `),e.serve(),t.kind==="room"&&(async()=>(await ie(t.url))?.token||await me(t.url)&&process.stderr.write(`sprite-mcp \u2192 ${we(t.url)}
55
+ `))()}}export{Ye as DEFAULT_EDITOR,Pe as DEFAULT_SERVER,zr as commandName,qr as createServer,Dr as detect,Cr as presentable,tn as probeRooms,we as signInFirst,Ur as websocketTransport};