moi-computer 0.14.0 → 0.14.1

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 (30) hide show
  1. package/package.json +1 -1
  2. package/runtime/build-worker-entry.js +1 -1
  3. package/runtime/chunk-1drt3wyp.js +127 -0
  4. package/runtime/{chunk-00rk365r.js → chunk-1ttazyr4.js} +13 -13
  5. package/runtime/{chunk-w1fx9tsc.js → chunk-3xv43vzy.js} +2 -2
  6. package/runtime/chunk-8ktr8n5m.js +2 -0
  7. package/runtime/{chunk-kjp60rqs.js → chunk-bf4je23j.js} +2 -2
  8. package/runtime/{chunk-ewc55jga.js → chunk-f5vvtga3.js} +40 -40
  9. package/runtime/{chunk-4wj1jzhr.js → chunk-jcjcz9ae.js} +2 -2
  10. package/runtime/{chunk-k049dtaq.js → chunk-jrkbyrmq.js} +1 -1
  11. package/runtime/{chunk-r5s8rm8n.js → chunk-m4zx92xc.js} +2 -2
  12. package/runtime/{chunk-ggphq7nk.js → chunk-n5c20498.js} +4 -4
  13. package/runtime/{chunk-sdyqhxe1.js → chunk-p24qxcr3.js} +5 -5
  14. package/runtime/chunk-pdzpsbmy.js +3 -0
  15. package/runtime/{chunk-h2bwhk81.js → chunk-q7xvhh2t.js} +1 -1
  16. package/runtime/{chunk-j0nd7kw0.js → chunk-qghmmzct.js} +12 -12
  17. package/runtime/{chunk-8fvgvm56.js → chunk-sxs483zn.js} +1 -1
  18. package/runtime/chunk-tbwma23z.js +2 -0
  19. package/runtime/{chunk-zwvtkb81.js → chunk-vtxbnqhj.js} +4 -4
  20. package/runtime/{chunk-5egvk1rz.js → chunk-wbzwwpct.js} +1 -1
  21. package/runtime/{chunk-wvarpvem.js → chunk-wgjqjgj9.js} +17 -17
  22. package/runtime/{chunk-hjzfk1cr.js → chunk-yd4jjshe.js} +1 -1
  23. package/runtime/{chunk-gbkjshyt.js → chunk-yr67rvnq.js} +1 -1
  24. package/runtime/cli.js +46 -46
  25. package/runtime/functions-worker.js +1 -1
  26. package/runtime/gateway-client.js +1 -1
  27. package/runtime/chunk-c3qyet60.js +0 -128
  28. package/runtime/chunk-jb63ns1z.js +0 -2
  29. package/runtime/chunk-w6ksnv8y.js +0 -2
  30. package/runtime/chunk-zm7k0v1c.js +0 -3
package/runtime/cli.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{vt,Ls,p,H,C,tr,rr,nt,he}from"./chunk-kjp60rqs.js";import{w,W,ue,N,K,pt,ge,O,Pr,_e,Wt,M,fe,bs,vs,$r,gt,Jn,Xn,Ss,Ts,Es,Ke,Xr,ve,Ns,Ie,ti,z,D,bt}from"./chunk-c3qyet60.js";import"./chunk-zwvtkb81.js";import{ye,J,It,Sn,Ct,ct,Ne,dr,te,Dt}from"./chunk-r5s8rm8n.js";import{a,cn,hi,it,yi,t,un,st,Et,xt,we,qe,R,ot,Te,dn,fn,vi,Si,Ti,At,He,mn,lt,oe,V,hn,Ei,ar,xi,yn,gn,_n,or,Pi,bn,vn,lr,Pt,Je,le,Ee,xe,ki,ce,De}from"./chunk-wvarpvem.js";import{ut}from"./chunk-4wj1jzhr.js";import{$i}from"./chunk-hjzfk1cr.js";import{r,m,s,Qt,o}from"./chunk-ggphq7nk.js";if(!process.stdout.isTTY&&!process.env.FORCE_COLOR&&process.env.NO_COLOR==null)process.env.NO_COLOR="1";var Nt=["MOI_AGENT","CLAUDECODE","CODEX_SANDBOX","CURSOR_TRACE_ID"];function Qe(e=process.env){return Nt.some((n)=>!!e[n])}import{resolve as zt}from"path";var q={type:"string",description:'Limit to "widgets", "views", "widgets/<id>", or "views/<id>"'};function F(e){if(e===void 0)return;if(it(e))return e;console.error(`
3
+ import{vt,Ls,p,H,C,tr,rr,we,he}from"./chunk-bf4je23j.js";import{w,W,ue,N,K,pt,ge,O,Pr,_e,Wt,M,fe,bs,vs,$r,gt,Jn,Xn,Ss,Ts,Es,Ge,Xr,ve,Ns,Ie,ti,z,D,bt}from"./chunk-1drt3wyp.js";import"./chunk-vtxbnqhj.js";import{ye,J,It,Sn,Ct,ct,Oe,dr,te,Dt}from"./chunk-m4zx92xc.js";import{a,cn,hi,it,yi,t,un,st,Et,xt,De,He,R,ot,Te,dn,fn,vi,Si,Ti,At,Je,mn,lt,oe,V,hn,Ei,ar,xi,yn,gn,_n,or,Pi,bn,vn,lr,Pt,Xe,le,Ee,xe,ki,ce,Ne}from"./chunk-wgjqjgj9.js";import{ut}from"./chunk-jcjcz9ae.js";import{$i}from"./chunk-yd4jjshe.js";import{r,m,s,Qt,o}from"./chunk-n5c20498.js";if(!process.stdout.isTTY&&!process.env.FORCE_COLOR&&process.env.NO_COLOR==null)process.env.NO_COLOR="1";var Nt=["MOI_AGENT","CLAUDECODE","CODEX_SANDBOX","CURSOR_TRACE_ID"];function eo(e=process.env){return Nt.some((n)=>!!e[n])}import{resolve as zt}from"path";var q={type:"string",description:'Limit to "widgets", "views", "widgets/<id>", or "views/<id>"'};function F(e){if(e===void 0)return;if(it(e))return e;console.error(`
4
4
  `+t.red("\u2717")+` Invalid --only value "${e}" \u2014 use "widgets", "views", "widgets/<id>", or "views/<id>".
5
- `),process.exit(1)}import{basename as jt}from"path";import{resolve as Le}from"path";async function B(e=process.cwd()){let n=await dr(Le(e)),i=await O(n);return i.remote?{path:n,...i.remote}:void 0}async function eo(e,n){if(n=K(n),!(await $r()).some((d)=>d.id===n.workspace_id&&d.owner.id===n.user_id))throw Error("This workspace is not shared with this account");let l=Le(e),c=(await D()).find((d)=>d.remote?.user_id===n.user_id&&d.remote.workspace_id===n.workspace_id&&Le(d.path)!==l);if(c)throw Error(`This workspace is already initialized at ${c.path} \u2014 remove that registration in Moi first`);let f=await un(l,n);return{path:l,id:f.id,...n}}var{views:Lt,config:Mt,icon:_t,scratchpadOps:Ut}=M,Ht={views:Lt,config:Mt,icon:_t,scratchpadOps:Ut};async function oo(e,n){if(!["config","scratch","tabs"].includes(String(n.type)))return;let i=n.op;if(n.type==="scratch"&&i?.kind==="view")return;let l=await B(e);if(!l)return;let c={remote:l},f=(u,g)=>Ke(Ht[u].path(l),g);if(n.type==="tabs"){let{views:u}=await(await f("views")).json();return{tabs:st(u)}}if(n.type==="config"){if(typeof n.iconPath==="string"){let g=Bun.file(n.iconPath);if(!await g.exists())throw Error("Local icon file not found");return{ok:!0,...await(await f("icon",{method:"PUT",body:g})).json()}}if(n.clearIcon)return await f("icon",{method:"DELETE"}),{ok:!0,clearedIcon:!0};if(n.name!==void 0||n.clearName)return{...await(await f("config",{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({name:n.clearName?null:n.name})})).json(),ok:!0,clearedName:n.clearName===!0};let u=await(await f("config")).json();return{...u,hasIcon:!!u.icon}}if(!i)throw Error("Missing scratch operation");if(i.kind==="read")return{shapes:await xt(c)};if(i.kind==="read-image")return Et(c,i.name);let d=new FormData;if(i.kind.startsWith("add-")&&"name"in i&&!i.name)i.name=`s_${crypto.randomUUID().slice(0,8)}`;if(i.kind==="add-image"){let u=Bun.file(i.path);if(!await u.exists())throw Error("Local image file not found");d.set("image",u),d.set("op",JSON.stringify({...i,path:jt(i.path)}))}else d.set("op",JSON.stringify(i));return{ok:!0,result:await(await f("scratchpadOps",{method:"POST",body:d})).json()}}import{accessSync as qt,constants as Me}from"fs";async function P(){return(await we()).status==="running"}async function _(){console.error(qe(await we())),process.exit(1)}async function to(e=1e4){let n=Date.now()+e;while(Date.now()<n){if(await P())return!0;await Bun.sleep(200)}return!1}async function ee(e){try{qt(e,Me.R_OK|Me.W_OK|Me.X_OK)}catch{console.error(`
5
+ `),process.exit(1)}import{basename as jt}from"path";import{resolve as Me}from"path";async function B(e=process.cwd()){let n=await dr(Me(e)),i=await O(n);return i.remote?{path:n,...i.remote}:void 0}async function oo(e,n){if(n=K(n),!(await $r()).some((d)=>d.id===n.workspace_id&&d.owner.id===n.user_id))throw Error("This workspace is not shared with this account");let l=Me(e),c=(await D()).find((d)=>d.remote?.user_id===n.user_id&&d.remote.workspace_id===n.workspace_id&&Me(d.path)!==l);if(c)throw Error(`This workspace is already initialized at ${c.path} \u2014 remove that registration in Moi first`);let f=await un(l,n);return{path:l,id:f.id,...n}}var{views:Lt,config:Mt,icon:_t,scratchpadOps:Ut}=M,Ht={views:Lt,config:Mt,icon:_t,scratchpadOps:Ut};async function to(e,n){if(!["config","scratch","tabs"].includes(String(n.type)))return;let i=n.op;if(n.type==="scratch"&&i?.kind==="view")return;let l=await B(e);if(!l)return;let c={remote:l},f=(u,g)=>Ge(Ht[u].path(l),g);if(n.type==="tabs"){let{views:u}=await(await f("views")).json();return{tabs:st(u)}}if(n.type==="config"){if(typeof n.iconPath==="string"){let g=Bun.file(n.iconPath);if(!await g.exists())throw Error("Local icon file not found");return{ok:!0,...await(await f("icon",{method:"PUT",body:g})).json()}}if(n.clearIcon)return await f("icon",{method:"DELETE"}),{ok:!0,clearedIcon:!0};if(n.name!==void 0||n.clearName)return{...await(await f("config",{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({name:n.clearName?null:n.name})})).json(),ok:!0,clearedName:n.clearName===!0};let u=await(await f("config")).json();return{...u,hasIcon:!!u.icon}}if(!i)throw Error("Missing scratch operation");if(i.kind==="read")return{shapes:await xt(c)};if(i.kind==="read-image")return Et(c,i.name);let d=new FormData;if(i.kind.startsWith("add-")&&"name"in i&&!i.name)i.name=`s_${crypto.randomUUID().slice(0,8)}`;if(i.kind==="add-image"){let u=Bun.file(i.path);if(!await u.exists())throw Error("Local image file not found");d.set("image",u),d.set("op",JSON.stringify({...i,path:jt(i.path)}))}else d.set("op",JSON.stringify(i));return{ok:!0,result:await(await f("scratchpadOps",{method:"POST",body:d})).json()}}import{accessSync as qt,constants as Ue}from"fs";async function P(){return(await De()).status==="running"}async function _(){console.error(He(await De())),process.exit(1)}async function no(e=1e4){let n=Date.now()+e;while(Date.now()<n){if(await P())return!0;await Bun.sleep(200)}return!1}async function ee(e){try{qt(e,Ue.R_OK|Ue.W_OK|Ue.X_OK)}catch{console.error(`
6
6
  `+t.red("\u2717")+` Can't open ${e} for reading and writing
7
- `),process.exit(1)}return new Promise((n,i)=>{let l=new WebSocket(N);l.onopen=()=>l.send(JSON.stringify({type:"workspace:register",path:e})),l.onmessage=(c)=>{let f=JSON.parse(String(c.data));if(f.id)l.close(),n(f.id)},l.onerror=()=>void we().then((c)=>i(Error(qe(c))))})}function no(e,n=3000){return new Promise((i)=>{let l=new WebSocket(N),c=()=>{clearTimeout(f),l.close(),i()},f=setTimeout(c,n);l.onopen=()=>l.send(JSON.stringify(e)),l.onmessage=c,l.onerror=c})}async function j(e,n,i){try{let d=await oo(e,n);if(d){if(d.error)throw Error(String(d.error));await i(d);let u=await te(e);if(u)console.error(`
7
+ `),process.exit(1)}return new Promise((n,i)=>{let l=new WebSocket(N);l.onopen=()=>l.send(JSON.stringify({type:"workspace:register",path:e})),l.onmessage=(c)=>{let f=JSON.parse(String(c.data));if(f.id)l.close(),n(f.id)},l.onerror=()=>void De().then((c)=>i(Error(He(c))))})}function ro(e,n=3000){return new Promise((i)=>{let l=new WebSocket(N),c=()=>{clearTimeout(f),l.close(),i()},f=setTimeout(c,n);l.onopen=()=>l.send(JSON.stringify(e)),l.onmessage=c,l.onerror=c})}async function j(e,n,i){try{let d=await to(e,n);if(d){if(d.error)throw Error(String(d.error));await i(d);let u=await te(e);if(u)console.error(`
8
8
  `+t.yellow(u)+`
9
9
  `);return}}catch(d){console.error(d instanceof Error?d.message:"Remote command failed"),process.exitCode=1;return}let l=new WebSocket(N),c=!1,f=!1;l.onopen=()=>{c=!0,l.send(JSON.stringify(n))},l.onmessage=async(d)=>{f=!0;let u=JSON.parse(String(d.data));if(u.error)console.error(`
10
10
  `+t.red("\u2717")+" "+u.error+`
11
11
  `),l.close(),process.exit(1);await i(u);let g=await te(e);if(g)console.error(`
12
12
  `+t.yellow(g)+`
13
- `);l.close(),process.exit(0)},l.onclose=()=>{if(c&&!f)console.error("The server disconnected before acknowledging the command. Check the browser before retrying."),process.exit(1)},l.onerror=()=>void _()}function Ft(e){if(e==="built")return t.green(e);if(e==="failed")return t.red(e);return t.dim(e)}var ro=a({meta:{name:"bundle",description:"Rebuild changed widgets and views"},args:{dir:{type:"positional",default:".",description:"Workspace directory (default: current)"},force:{type:"boolean",description:"Rebuild the selected applets, ignoring file modification times",default:!1},only:q},async run({args:e}){let n=F(e.only),i=zt(e.dir),l=await te(i),c=new WebSocket(N);c.onopen=()=>c.send(JSON.stringify({type:"bundle",path:i,force:e.force,only:n})),c.onmessage=(f)=>{let d=JSON.parse(String(f.data));if(d.error)console.error(`
13
+ `);l.close(),process.exit(0)},l.onclose=()=>{if(c&&!f)console.error("The server disconnected before acknowledging the command. Check the browser before retrying."),process.exit(1)},l.onerror=()=>void _()}function Ft(e){if(e==="built")return t.green(e);if(e==="failed")return t.red(e);return t.dim(e)}var io=a({meta:{name:"bundle",description:"Rebuild changed widgets and views"},args:{dir:{type:"positional",default:".",description:"Workspace directory (default: current)"},force:{type:"boolean",description:"Rebuild the selected applets, ignoring file modification times",default:!1},only:q},async run({args:e}){let n=F(e.only),i=zt(e.dir),l=await te(i),c=new WebSocket(N);c.onopen=()=>c.send(JSON.stringify({type:"bundle",path:i,force:e.force,only:n})),c.onmessage=(f)=>{let d=JSON.parse(String(f.data));if(d.error)console.error(`
14
14
  `+t.red(t.bold("Error:"))+" "+d.error+`
15
15
  `),c.close(),process.exit(1);let u=Array.isArray(d.results)?d.results:[],g=typeof d.workspacePath==="string"?d.workspacePath:i;if(u.length===0){if(console.log(`
16
16
  `+t.bold("moi bundle")+t.dim(" \u2014 nothing to build")+`
@@ -22,9 +22,9 @@ import{vt,Ls,p,H,C,tr,rr,nt,he}from"./chunk-kjp60rqs.js";import{w,W,ue,N,K,pt,ge
22
22
  `),console.log(R(["kind","name","status"].map((k)=>t.dim(k)),u.map((k)=>[t.dim(k.kind??""),k.name,Ft(k.status)])));let b=u.filter((k)=>k.status==="failed");console.log();for(let k of b)console.log(t.red(t.bold(k.name+":"))),console.log(" "+k.error+`
23
23
  `);let x=typeof d.logCount==="number"?d.logCount:0;if(x>0)console.log(t.yellow(`\u2139 ${x} applet runtime error(s) on record \u2014 run \`moi debug logs\`.`)+`
24
24
  `);if(l)console.log(t.yellow(l)+`
25
- `);c.close(),process.exit(b.length>0?1:0)},c.onerror=()=>void _()}});import{resolve as Jt}from"path";var S={type:"string",default:".",description:"Workspace directory (default: current)"};var io=a({meta:{name:"call-server-fn",description:"Invoke an applet .server.ts function in an isolated one-shot worker (smoke test)"},args:{fn:{type:"positional",required:!0,description:"Function path: <module>/<fn>, e.g. widgets/hello/getGreeting"},args:{type:"positional",required:!1,description:`Arguments as one JSON array, e.g. '["ann", 10]' (default [])`},dir:S},run({args:e}){let n=Jt(e.dir);j(n,{type:"call-server-fn",path:n,fn:e.fn,args:e.args??"[]"},(i)=>{let l=ut(String(i.result));console.log(Bun.inspect(l,{depth:8,colors:process.stdout.isTTY})),console.error(t.dim(`\u21A9 ${i.ms}ms`))})}});import{existsSync as Bt}from"fs";import{join as Vt,resolve as Kt}from"path";var so=a({meta:{name:"check",description:"Run applet checks"},args:{dir:{type:"positional",default:".",description:"Workspace directory (default: current)"},only:q},async run({args:e}){let n=F(e.only),{root:i}=await Ne(Kt(e.dir));if(!Bt(Vt(i,".moi")))console.error(`
25
+ `);c.close(),process.exit(b.length>0?1:0)},c.onerror=()=>void _()}});import{resolve as Jt}from"path";var S={type:"string",default:".",description:"Workspace directory (default: current)"};var so=a({meta:{name:"call-server-fn",description:"Invoke an applet .server.ts function in an isolated one-shot worker (smoke test)"},args:{fn:{type:"positional",required:!0,description:"Function path: <module>/<fn>, e.g. widgets/hello/getGreeting"},args:{type:"positional",required:!1,description:`Arguments as one JSON array, e.g. '["ann", 10]' (default [])`},dir:S},run({args:e}){let n=Jt(e.dir);j(n,{type:"call-server-fn",path:n,fn:e.fn,args:e.args??"[]"},(i)=>{let l=ut(String(i.result));console.log(Bun.inspect(l,{depth:8,colors:process.stdout.isTTY})),console.error(t.dim(`\u21A9 ${i.ms}ms`))})}});import{existsSync as Bt}from"fs";import{join as Vt,resolve as Kt}from"path";var ao=a({meta:{name:"check",description:"Run applet checks"},args:{dir:{type:"positional",default:".",description:"Workspace directory (default: current)"},only:q},async run({args:e}){let n=F(e.only),{root:i}=await Oe(Kt(e.dir));if(!Bt(Vt(i,".moi")))console.error(`
26
26
  `+t.red("\u2717")+` No Moi workspace found at ${i}
27
- `),process.exit(1);let{formatAppletTypecheckDiagnostics:l,typecheckApplets:c}=await import("./chunk-h2bwhk81.js"),f=await c(i,n);if(n?.includes("/")&&f.files.length===0)console.error(`
27
+ `),process.exit(1);let{formatAppletTypecheckDiagnostics:l,typecheckApplets:c}=await import("./chunk-q7xvhh2t.js"),f=await c(i,n);if(n?.includes("/")&&f.files.length===0)console.error(`
28
28
  `+t.red("\u2717")+` Applet "${n}" not found.
29
29
  `),process.exit(1);if(f.diagnostics.length>0)console.error(`
30
30
  `+t.red("\u2717")+` Applet check failed: TypeScript
@@ -32,8 +32,8 @@ import{vt,Ls,p,H,C,tr,rr,nt,he}from"./chunk-kjp60rqs.js";import{w,W,ue,N,K,pt,ge
32
32
  `+t.green("\u2713")+` No applet source files found in ${u}
33
33
  `);return}let d=n?` (${n})`:"";console.log(`
34
34
  `+t.green("\u2713")+` Applet checks passed: TypeScript \xB7 ${f.files.length} file${f.files.length===1?"":"s"}${d}
35
- `)}});import{resolve as ao}from"path";async function de(e){await j(e.path,{type:"config",...e},(n)=>{if(console.log(),n.ok){if(n.clearedName)console.log(t.green("\u2713")+" Name reset to "+t.dim("(folder name)"));else if(n.name)console.log(t.green("\u2713")+" Name set to "+t.bold(String(n.name)));if(n.clearedIcon)console.log(t.green("\u2713")+" Icon reset to "+t.dim("default (provider)"));else if(n.icon)console.log(t.green("\u2713")+" Icon updated "+t.dim("(128\xD7128 webp)"))}else console.log(t.bold("moi config")+` \u2014 workspace identity
36
- `),console.log(" "+t.dim("name")+" "+(n.name?t.bold(String(n.name)):t.dim("(folder name)"))),console.log(" "+t.dim("icon")+" "+(n.hasIcon?t.green("custom"):t.dim("default (provider)")));console.log()})}function Ue(){let e=(n,i)=>" "+t.cyan(n.padEnd(34))+t.dim(i);console.log(),console.log(t.bold("moi config")+t.dim(" \u2014 workspace name & icon")),console.log(),console.log(e("moi config","Show current name & icon")),console.log(e('moi config name "My WS"',"Set the display name")),console.log(e("moi config name --clear","Reset name to folder default")),console.log(e("moi config icon ./logo.png","Set icon (png/jpg/gif/webp \u2192 128\xD7128 webp)")),console.log(e("moi config icon --clear","Reset icon to provider default")),console.log(e(" --dir <path>","Target workspace (default: current dir)")),console.log()}var lo=a({meta:{name:"config",description:"Show or set the workspace name and icon (moi config [name|icon] <value>)"},args:{field:{type:"positional",required:!1,description:'"name" or "icon" \u2014 omit to show the current config'},value:{type:"positional",required:!1,description:"The new name, or a path to an image file (png/jpg/gif/webp)"},clear:{type:"boolean",description:"Reset the field to its default (folder name / provider icon)"},dir:{type:"string",default:".",description:"Workspace directory (default: current)"}},run({args:e}){let n=ao(e.dir);if(e.field==="help"){Ue();return}if(!e.field){de({path:n});return}if(e.field==="name"){if(e.clear){de({path:n,clearName:!0});return}if(!e.value)console.error(t.red("Usage:")+' moi config name "<workspace name>"'),process.exit(1);de({path:n,name:e.value})}else if(e.field==="icon"){if(e.clear){de({path:n,clearIcon:!0});return}if(!e.value)console.error(t.red("Usage:")+" moi config icon <path-to-image>"),process.exit(1);de({path:n,iconPath:ao(e.value)})}else console.error(t.red(`Unknown field "${e.field}".`)+" Use "+t.bold("name")+" or "+t.bold("icon")+"."),process.exit(1)}});import{resolve as Yt}from"path";function Gt(e){let n=Math.max(0,Math.round((Date.now()-e)/1000));if(n<60)return"just now";if(n<3600)return`${Math.round(n/60)}m ago`;if(n<86400)return`${Math.round(n/3600)}h ago`;return`${Math.round(n/86400)}d ago`}function Xt(e){if(e.module)return`${e.module}/${e.fn??"?"}`;if(e.name)return`${e.kind??"applet"} ${e.name}`;return"unattributed"}var ze=12,Zt=a({meta:{name:"logs",description:"Applet runtime errors on record (load / render / rpc / build failures)"},args:{dir:S,only:q,json:{type:"boolean",default:!1,description:"Machine-readable output, includes stacks and epoch timestamps"},clear:{type:"boolean",default:!1,description:"Wipe the journal"}},run({args:e}){let n=F(e.only),i=Yt(e.dir);if(e.clear){if(n)console.error(`
35
+ `)}});import{resolve as lo}from"path";async function de(e){await j(e.path,{type:"config",...e},(n)=>{if(console.log(),n.ok){if(n.clearedName)console.log(t.green("\u2713")+" Name reset to "+t.dim("(folder name)"));else if(n.name)console.log(t.green("\u2713")+" Name set to "+t.bold(String(n.name)));if(n.clearedIcon)console.log(t.green("\u2713")+" Icon reset to "+t.dim("default (provider)"));else if(n.icon)console.log(t.green("\u2713")+" Icon updated "+t.dim("(128\xD7128 webp)"))}else console.log(t.bold("moi config")+` \u2014 workspace identity
36
+ `),console.log(" "+t.dim("name")+" "+(n.name?t.bold(String(n.name)):t.dim("(folder name)"))),console.log(" "+t.dim("icon")+" "+(n.hasIcon?t.green("custom"):t.dim("default (provider)")));console.log()})}function qe(){let e=(n,i)=>" "+t.cyan(n.padEnd(34))+t.dim(i);console.log(),console.log(t.bold("moi config")+t.dim(" \u2014 workspace name & icon")),console.log(),console.log(e("moi config","Show current name & icon")),console.log(e('moi config name "My WS"',"Set the display name")),console.log(e("moi config name --clear","Reset name to folder default")),console.log(e("moi config icon ./logo.png","Set icon (png/jpg/gif/webp \u2192 128\xD7128 webp)")),console.log(e("moi config icon --clear","Reset icon to provider default")),console.log(e(" --dir <path>","Target workspace (default: current dir)")),console.log()}var co=a({meta:{name:"config",description:"Show or set the workspace name and icon (moi config [name|icon] <value>)"},args:{field:{type:"positional",required:!1,description:'"name" or "icon" \u2014 omit to show the current config'},value:{type:"positional",required:!1,description:"The new name, or a path to an image file (png/jpg/gif/webp)"},clear:{type:"boolean",description:"Reset the field to its default (folder name / provider icon)"},dir:{type:"string",default:".",description:"Workspace directory (default: current)"}},run({args:e}){let n=lo(e.dir);if(e.field==="help"){qe();return}if(!e.field){de({path:n});return}if(e.field==="name"){if(e.clear){de({path:n,clearName:!0});return}if(!e.value)console.error(t.red("Usage:")+' moi config name "<workspace name>"'),process.exit(1);de({path:n,name:e.value})}else if(e.field==="icon"){if(e.clear){de({path:n,clearIcon:!0});return}if(!e.value)console.error(t.red("Usage:")+" moi config icon <path-to-image>"),process.exit(1);de({path:n,iconPath:lo(e.value)})}else console.error(t.red(`Unknown field "${e.field}".`)+" Use "+t.bold("name")+" or "+t.bold("icon")+"."),process.exit(1)}});import{resolve as Yt}from"path";function Gt(e){let n=Math.max(0,Math.round((Date.now()-e)/1000));if(n<60)return"just now";if(n<3600)return`${Math.round(n/60)}m ago`;if(n<86400)return`${Math.round(n/3600)}h ago`;return`${Math.round(n/86400)}d ago`}function Xt(e){if(e.module)return`${e.module}/${e.fn??"?"}`;if(e.name)return`${e.kind??"applet"} ${e.name}`;return"unattributed"}var ze=12,Zt=a({meta:{name:"logs",description:"Applet runtime errors on record (load / render / rpc / build failures)"},args:{dir:S,only:q,json:{type:"boolean",default:!1,description:"Machine-readable output, includes stacks and epoch timestamps"},clear:{type:"boolean",default:!1,description:"Wipe the journal"}},run({args:e}){let n=F(e.only),i=Yt(e.dir);if(e.clear){if(n)console.error(`
37
37
  `+t.red("\u2717")+` Cannot combine --only with --clear.
38
38
  `),process.exit(1);j(i,{type:"debug:logs",path:i,clear:!0},(l)=>{console.log(`
39
39
  `+t.green("\u2713")+` cleared ${l.cleared??0} entries
@@ -43,11 +43,11 @@ import{vt,Ls,p,H,C,tr,rr,nt,he}from"./chunk-kjp60rqs.js";import{w,W,ue,N,K,pt,ge
43
43
  `+t.bold("moi debug logs")+t.dim(` \u2014 ${c.length} error(s) on record${f}`)+`
44
44
  `);for(let d of c){let u=d.count>1?t.dim(` \xD7${d.count}`):"";console.log(` ${t.dim(Gt(d.ts).padEnd(10))} ${d.source.padEnd(7)} ${t.bold(Xt(d))}${u}`);let g=d.message.split(`
45
45
  `);for(let h of g.slice(0,ze))console.log(" "+h);if(g.length>ze)console.log(t.dim(` \u2026 ${g.length-ze} more lines (--json)`));console.log()}console.log(t.dim(" Entries clear when their applet next builds successfully, or via --clear.")+`
46
- `)})}}),co=a({meta:{name:"debug",description:"Debug the workspace (experimental) \u2014 `moi debug logs` for applet errors"},subCommands:{logs:Zt}});function me(e){console.error(`
46
+ `)})}}),mo=a({meta:{name:"debug",description:"Debug the workspace (experimental) \u2014 `moi debug logs` for applet errors"},subCommands:{logs:Zt}});function me(e){console.error(`
47
47
  `+t.red("\u2717")+" "+e+`
48
48
  `),process.exit(1)}var en=a({meta:{name:"set",description:"Set custom secrets: `moi env set KEY=value [KEY=value...]`, or `moi env set KEY` to read one value from stdin"},args:{key:{type:"positional",required:!0,description:"KEY=value pair(s), or a single bare KEY to read the value from stdin"}},async run({args:e}){let n=await Te(),i=e._,l={};if(i.length===1&&!i[0].includes("=")){let f=i[0];if(!Wt(f))me(`Invalid env key: ${f}`);let d;try{d=await Si(f)}catch{process.exit(1)}if(d==="")me(`Empty value for ${f} \u2014 pipe a non-empty value or pass ${f}=value`);l[f]=d}else for(let f of i){let d=f.indexOf("=");if(d===-1)me(`Missing value for ${f} \u2014 use KEY=value (bare KEY reads stdin only when set alone)`);let u=f.slice(0,d),g=f.slice(d+1);if(!Wt(u))me(`Invalid env key: ${u}`);if(g==="")me(`Empty value for ${u} \u2014 use \`moi env unset ${u}\` to remove a key`);l[u]=g}let c=await fn(n.path,{set:l});for(let f of Object.keys(l))console.log(t.green("\u2713")+` Set ${t.bold(f)} ${t.dim("(custom)")}`);if(c==="file")console.log(t.dim(" Stored in a 0600 file \u2014 OS keychain unavailable."));process.exit(0)}}),on=a({meta:{name:"unset",description:"Remove custom secrets: `moi env unset KEY [KEY...]`"},args:{key:{type:"positional",required:!0,description:"Key(s) to remove"}},async run({args:e}){let n=await Te(),i=await dn(n.path),l=new Map(i.vars.map((d)=>[d.key,d])),c=[],f=!1;for(let d of e._){let u=l.get(d);if(!u){console.warn(t.yellow("!")+` ${d} is not set \u2014 skipping`);continue}if(u.source==="dotenv"){console.error(t.red("\u2717")+` ${d} comes from ${(u.files??[]).join(", ")} \u2014 edit that file instead`+t.dim(" (moi env unset only removes custom secrets)")),f=!0;continue}c.push(d)}if(c.length>0){await fn(n.path,{remove:c});for(let d of c){let u=l.get(d),g=u?.source==="both"?t.dim(` (falls back to ${(u.files??[]).join(", ")})`):"";console.log(t.green("\u2713")+` Removed ${t.bold(d)}${g}`)}}process.exit(f?1:0)}}),tn=a({meta:{name:"exec",description:"Run a command with the workspace env: `moi env exec -- <cmd> [args...]`"},async run({rawArgs:e}){let n=e.indexOf("--"),i=n===-1?[]:e.slice(n+1);if(i.length===0)console.error(`
49
49
  `+t.red("\u2717")+` Usage: moi env exec -- <cmd> [args...]
50
- `),process.exit(1);let l=await Te();process.exit(await Ti(l.path,i))}}),mo={set:en,unset:on,exec:tn},po=a({meta:{name:"env",description:"Show the workspace env (key names only \u2014 never values)"},subCommands:mo,async run({rawArgs:e}){let n=e.find((c)=>!c.startsWith("-"));if(n&&Object.hasOwn(mo,n))return;let i=await Te(),l=await dn(i.path);console.log(`
50
+ `),process.exit(1);let l=await Te();process.exit(await Ti(l.path,i))}}),po={set:en,unset:on,exec:tn},fo=a({meta:{name:"env",description:"Show the workspace env (key names only \u2014 never values)"},subCommands:po,async run({rawArgs:e}){let n=e.find((c)=>!c.startsWith("-"));if(n&&Object.hasOwn(po,n))return;let i=await Te(),l=await dn(i.path);console.log(`
51
51
  `+vi(i,l)+`
52
52
  `),process.exit(0)}});function $e(e,n){console.log(`
53
53
  `+t.bold(" Commands")),console.log(ot([[t.bold(`moi ${e} init`)+" "+t.dim(n),"Install Moi skills and register the workspace"]]," "))}function Re(e,n,i){return n===1?`moi ${e} init`:`moi ${e} init <${i}>`}function Fe(e){console.log(R(["","profile","model","workspace"].map((n)=>t.dim(n)),e.map((n)=>[n.isDefault?t.green("\u25CF"):" ",n.isDefault?t.bold(n.agentId):n.agentId,n.model??t.dim("\u2014"),t.dim(n.path)])))}var nn=a({meta:{name:"init",description:"Install Moi skills into a Hermes profile workspace. Run without args to list discovered profiles."},args:{profile:{type:"positional",required:!1,description:"Profile id or description (omit to list profiles)"}},async run({args:e}){let n=await ve();if(n.length===0)console.error(`
@@ -65,35 +65,35 @@ import{vt,Ls,p,H,C,tr,rr,nt,he}from"./chunk-kjp60rqs.js";import{w,W,ue,N,K,pt,ge
65
65
  `+t.green("\u2713")+" Installed skills to "+t.bold(c)),console.log(t.dim(" Profile: ")+t.bold(i.agentId)+(i.model?t.dim(" ("+i.model+")"):""));let u=process.stdout.isTTY;if(await P()){let h=`http://localhost:${w}/workspace/${d.id}`;if(await ee(i.path),u)console.log(" Opening "+t.bold(h)+`
66
66
  `),await _e(h);else console.log(" Ready at "+t.bold(h)+`
67
67
  `)}else console.log(" Run "+t.bold("moi start")+` to open in the browser
68
- `);process.exit(0)}}),fo=a({meta:{name:"hermes",description:"Hermes Agent integration commands"},async run({rawArgs:e}){if(e.some((i)=>!i.startsWith("-")))return;console.log(`
68
+ `);process.exit(0)}}),uo=a({meta:{name:"hermes",description:"Hermes Agent integration commands"},async run({rawArgs:e}){if(e.some((i)=>!i.startsWith("-")))return;console.log(`
69
69
  `+t.bold("Hermes")),$e("hermes","[profile]");let n=await ve().catch(()=>[]);if(n.length===0){console.log(`
70
70
  `+t.dim("No profiles discovered \u2014 install Hermes and run ")+t.dim("hermes setup")+`
71
71
  `);return}console.log(`
72
72
  `+t.bold(" Profiles")),Fe(n),console.log(t.dim(`
73
73
  Run `)+t.bold(Re("hermes",n.length,"profile"))+`
74
- `)},subCommands:{init:nn}});import{existsSync as xn}from"fs";import{join as xo,resolve as Cn}from"path";import{existsSync as rn}from"fs";import{join as sn,resolve as uo}from"path";var pe=["claude-code","codex","hermes","openclaw"],re={"claude-code":"Claude Code",codex:"Codex",hermes:"Hermes",openclaw:"OpenClaw"};function go(e){return pe.includes(e)}var ho={hermesProfiles:ve,openclawAgents:Ie,codexWorkspaces:async()=>(await Xr(new Set)).map((e)=>e.path),claudeCodeWorkspaces:async()=>{let{claudeCodeHarness:e}=await import("./chunk-jb63ns1z.js");return(await e.discoverWorkspaces?.(new Set)??[]).map((i)=>i.path)},hasClaudeConfigDir:(e)=>rn(sn(e,".claude"))};async function ne(e,n){try{return await e()}catch{return n}}function wo(e){return{harness:"hermes",agent:{agentId:e.agentId,...e.name?{name:e.name}:{},isDefault:e.isDefault},reason:`a Hermes profile workspace (${e.agentId})`}}function yo(e){return{harness:"openclaw",agent:{agentId:e.agentId,...e.name?{name:e.name}:{},isDefault:e.isDefault,...e.lastRunAt?{lastRunAt:e.lastRunAt}:{}},reason:`an OpenClaw agent workspace (${e.agentId}${e.name?", "+e.name:""})`}}async function vo(e,n={}){let i={...ho,...n},l=uo(e),c=(await ne(i.hermesProfiles,[])).find((d)=>d.path===l);if(c)return wo(c);let f=(await ne(i.openclawAgents,[])).find((d)=>d.path===l);if(f)return yo(f);if((await ne(i.codexWorkspaces,[])).includes(l))return{harness:"codex",reason:"Codex session history here"};if((await ne(i.claudeCodeWorkspaces,[])).includes(l))return{harness:"claude-code",reason:"Claude Code session history here"};if(i.hasClaudeConfigDir(l))return{harness:"claude-code",reason:"a .claude/ directory here"};return null}async function bo(e,n,i={}){let l={...ho,...i},c=uo(n);if(e==="hermes"){let f=(await ne(l.hermesProfiles,[])).find((d)=>d.path===c);return f?wo(f).agent??null:null}if(e==="openclaw"){let f=(await ne(l.openclawAgents,[])).find((d)=>d.path===c);return f?yo(f).agent??null:null}return null}import{existsSync as an}from"fs";import{homedir as ln,tmpdir as pn}from"os";import{join as wn}from"path";function Oe(e,n){if(n||!an(wn(e,"dist","index.html")))return e;return ln()||pn()||e}import{join as kn}from"path";function ko(e=Bun.version){if(nt)throw Error("Development mode requires a Moi source checkout");let n=$i.slice(4);if(!Bun.semver.satisfies(e,`>=${n}`))throw Error(`Moi development requires Bun ${n} or newer (running ${e}). Run \`bun upgrade --version ${n}\`, then restart \`bun run dev\`.`)}function Y(e,n=process.env,i=[]){let l=[process.execPath,he("cli.ts"),"start",...i];return Bun.spawn(l,{stdin:"inherit",stdout:"inherit",stderr:"inherit",cwd:e,env:{...n,MOI_SERVER:"1"}})}async function So(e,n){let{watch:i}=await import("fs"),l=Y(e,n),c=!1,f;async function d(u){if(c)return;c=!0,console.log(t.dim(`
75
- \u21BB ${u} \u2014 restarting server\u2026`));try{l.kill("SIGTERM")}catch{}let g=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}},3000);await l.exited,clearTimeout(g),c=!1,l=Y(e,n)}for(let u of["server","lib"])i(kn(e,u),{recursive:!0},(g,h)=>{if(!h||!h.endsWith(".ts"))return;clearTimeout(f),f=setTimeout(()=>d(`${h} changed`),100)});for(let u of["SIGINT","SIGTERM"])process.on(u,()=>{try{l.kill("SIGTERM")}catch{}process.exit(0)});await new Promise(()=>{})}async function $n(e,n){if(n!==void 0){let c=n.trim();if(!go(c))console.error(`
74
+ `)},subCommands:{init:nn}});import{existsSync as xn}from"fs";import{join as Co,resolve as Cn}from"path";import{existsSync as rn}from"fs";import{join as sn,resolve as go}from"path";var pe=["claude-code","codex","hermes","openclaw"],re={"claude-code":"Claude Code",codex:"Codex",hermes:"Hermes",openclaw:"OpenClaw"};function ho(e){return pe.includes(e)}var wo={hermesProfiles:ve,openclawAgents:Ie,codexWorkspaces:async()=>(await Xr(new Set)).map((e)=>e.path),claudeCodeWorkspaces:async()=>{let{claudeCodeHarness:e}=await import("./chunk-8ktr8n5m.js");return(await e.discoverWorkspaces?.(new Set)??[]).map((i)=>i.path)},hasClaudeConfigDir:(e)=>rn(sn(e,".claude"))};async function ne(e,n){try{return await e()}catch{return n}}function yo(e){return{harness:"hermes",agent:{agentId:e.agentId,...e.name?{name:e.name}:{},isDefault:e.isDefault},reason:`a Hermes profile workspace (${e.agentId})`}}function vo(e){return{harness:"openclaw",agent:{agentId:e.agentId,...e.name?{name:e.name}:{},isDefault:e.isDefault,...e.lastRunAt?{lastRunAt:e.lastRunAt}:{}},reason:`an OpenClaw agent workspace (${e.agentId}${e.name?", "+e.name:""})`}}async function bo(e,n={}){let i={...wo,...n},l=go(e),c=(await ne(i.hermesProfiles,[])).find((d)=>d.path===l);if(c)return yo(c);let f=(await ne(i.openclawAgents,[])).find((d)=>d.path===l);if(f)return vo(f);if((await ne(i.codexWorkspaces,[])).includes(l))return{harness:"codex",reason:"Codex session history here"};if((await ne(i.claudeCodeWorkspaces,[])).includes(l))return{harness:"claude-code",reason:"Claude Code session history here"};if(i.hasClaudeConfigDir(l))return{harness:"claude-code",reason:"a .claude/ directory here"};return null}async function ko(e,n,i={}){let l={...wo,...i},c=go(n);if(e==="hermes"){let f=(await ne(l.hermesProfiles,[])).find((d)=>d.path===c);return f?yo(f).agent??null:null}if(e==="openclaw"){let f=(await ne(l.openclawAgents,[])).find((d)=>d.path===c);return f?vo(f).agent??null:null}return null}import{existsSync as an}from"fs";import{homedir as ln,tmpdir as pn}from"os";import{join as wn}from"path";function Ae(e,n){if(n||!an(wn(e,"dist","index.html")))return e;return ln()||pn()||e}import{join as kn}from"path";function So(e=Bun.version){if(we)throw Error("Development mode requires a Moi source checkout");let n=$i.slice(4);if(!Bun.semver.satisfies(e,`>=${n}`))throw Error(`Moi development requires Bun ${n} or newer (running ${e}). Run \`bun upgrade --version ${n}\`, then restart \`bun run dev\`.`)}function Y(e,n=process.env,i=[]){let l=[process.execPath,he("cli.ts"),"start",...i];return Bun.spawn(l,{stdin:"inherit",stdout:"inherit",stderr:"inherit",cwd:e,env:{...n,MOI_SERVER:"1"}})}async function xo(e,n){let{watch:i}=await import("fs"),l=Y(e,n),c=!1,f;async function d(u){if(c)return;c=!0,console.log(t.dim(`
75
+ \u21BB ${u} \u2014 restarting server\u2026`));try{l.kill("SIGTERM")}catch{}let g=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}},3000);await l.exited,clearTimeout(g),c=!1,l=Y(e,n)}for(let u of["server","lib"])i(kn(e,u),{recursive:!0},(g,h)=>{if(!h||!h.endsWith(".ts"))return;clearTimeout(f),f=setTimeout(()=>d(`${h} changed`),100)});for(let u of["SIGINT","SIGTERM"])process.on(u,()=>{try{l.kill("SIGTERM")}catch{}process.exit(0)});await new Promise(()=>{})}async function $n(e,n){if(n!==void 0){let c=n.trim();if(!ho(c))console.error(`
76
76
  `+t.red("\u2717")+" Unknown harness: "+t.bold(n)),console.error(t.dim(" Valid values: "+pe.join(", "))+`
77
- `),process.exit(1);let f=await bo(c,e);if(!f&&(c==="openclaw"||c==="hermes")){let d=c==="hermes"?"profile":"agent";console.log(`
77
+ `),process.exit(1);let f=await ko(c,e);if(!f&&(c==="openclaw"||c==="hermes")){let d=c==="hermes"?"profile":"agent";console.log(`
78
78
  `+t.yellow("\u26A0")+" No "+re[c]+" "+d+` found at this path \u2014 registering without one.
79
79
  `+t.dim(" Run ")+t.bold("moi "+c+" init")+t.dim(" to bind it once "+re[c]+" can see the workspace."))}return{harness:c,agent:f}}let i=(await D()).find((c)=>c.path===e);if(i){let c=i.harness??"claude-code";return console.log(`
80
- `+t.dim(" Already registered \u2014 initializing for ")+t.bold(re[c])),{harness:c,agent:i.agentId?{agentId:i.agentId,...i.name?{name:i.name}:{},isDefault:i.isDefault??!1,...i.lastRunAt?{lastRunAt:i.lastRunAt}:{}}:null}}let l=await vo(e);if(l)return console.log(`
80
+ `+t.dim(" Already registered \u2014 initializing for ")+t.bold(re[c])),{harness:c,agent:i.agentId?{agentId:i.agentId,...i.name?{name:i.name}:{},isDefault:i.isDefault??!1,...i.lastRunAt?{lastRunAt:i.lastRunAt}:{}}:null}}let l=await bo(e);if(l)return console.log(`
81
81
  `+t.yellow("\u25C6")+" Detected "+l.reason+" \u2014 initializing for "+t.bold(re[l.harness])+"."),{harness:l.harness,agent:l.agent??null};console.error(`
82
82
  `+t.red("\u2717")+" No agent harness detected in "+t.bold(e)),console.error(t.dim(` Looked for a Hermes profile, an OpenClaw agent, and Codex or Claude Code history.
83
83
  `)),console.error(` Pick one:
84
- `),console.error(ot(pe.map((c)=>[t.bold("moi init --harness="+c),re[c]])," ")),console.error(),process.exit(1)}var Co=a({meta:{name:"init",description:"Initialize a local or remote workspace and install its skill"},args:{remote:{type:"string",description:"Remote workspace address: ownerId:workspaceId"},json:{type:"boolean",description:"Print remote initialization as JSON"},dir:{type:"positional",default:".",description:"Target directory (default: current)"},harness:{type:"string",description:"Agent harness: "+pe.join(", ")+" (default: auto-detect)"},web:{type:"boolean",default:!1,description:"Start the web server if not already running"},id:{type:"string",description:"Register under this id instead of a generated one \u2014 fails if the workspace is already registered"}},async run({args:e}){if(e.remote!==void 0&&(e.harness||e.id)||e.json&&(e.remote===void 0||e.web)){console.error("--remote cannot be combined with --harness or --id; --json requires --remote without --web"),process.exitCode=1;return}let n=Cn(e.dir),i=bt(n);if(i!==n&&!e.json)console.log(`
85
- `+t.yellow("\u25C6")+" Ran inside "+t.bold(".moi")+" \u2014 using the workspace root "+t.bold(i)+" instead (no nested .moi created).");let l=xo(i,".moi",".moi");if(xn(l)&&!e.json)console.log(`
84
+ `),console.error(ot(pe.map((c)=>[t.bold("moi init --harness="+c),re[c]])," ")),console.error(),process.exit(1)}var $o=a({meta:{name:"init",description:"Initialize a local or remote workspace and install its skill"},args:{remote:{type:"string",description:"Remote workspace address: ownerId:workspaceId"},json:{type:"boolean",description:"Print remote initialization as JSON"},dir:{type:"positional",default:".",description:"Target directory (default: current)"},harness:{type:"string",description:"Agent harness: "+pe.join(", ")+" (default: auto-detect)"},web:{type:"boolean",default:!1,description:"Start the web server if not already running"},id:{type:"string",description:"Register under this id instead of a generated one \u2014 fails if the workspace is already registered"}},async run({args:e}){if(e.remote!==void 0&&(e.harness||e.id)||e.json&&(e.remote===void 0||e.web)){console.error("--remote cannot be combined with --harness or --id; --json requires --remote without --web"),process.exitCode=1;return}let n=Cn(e.dir),i=bt(n);if(i!==n&&!e.json)console.log(`
85
+ `+t.yellow("\u25C6")+" Ran inside "+t.bold(".moi")+" \u2014 using the workspace root "+t.bold(i)+" instead (no nested .moi created).");let l=Co(i,".moi",".moi");if(xn(l)&&!e.json)console.log(`
86
86
  `+t.yellow("\u26A0")+" Found a stray nested "+t.bold(".moi/.moi")+` (from an older bug). Safe to remove:
87
87
  `+t.dim(" rm -rf "+l));if(e.id)try{await ti(i,e.id)}catch(g){console.error(`
88
88
  `+t.red("\u2717")+" "+g.message+`
89
- `),process.exit(1)}let c=H,f=process.stdout.isTTY,d;if(e.remote!==void 0)try{let g=await eo(i,pt(e.remote));if(e.json){console.log(JSON.stringify(g));return}if(d=g,console.log(t.green("\u2713")+" Linked "+t.bold(g.path)+" to "+e.remote),console.log(`
90
- Next:`),console.log(" 1. Read "+xo(ye(g.path),"moi-workspace","SKILL.md")),console.log(" 2. Run commands from "+g.path),console.log(" 3. Run `moi remote` for available commands\n"),!e.web)return}catch(g){console.error(g instanceof Error?g.message:"Remote initialization failed"),process.exitCode=1;return}else{let g=await O(i);if(g.remote){console.error(`This is a remote workspace \u2014 use moi init --remote ${g.remote.user_id}:${g.remote.workspace_id}`),process.exitCode=1;return}let{harness:h,agent:v}=await $n(i,e.harness);console.log();let{scaffold:b,skillsDir:x,installLogPath:k}=await J(i,h);if(b!=="exists"&&b!=="skipped")if(b==="installing")console.log(t.dim(" Widget dependencies still installing in .moi/ (background)")),console.log(t.dim(" Install log: "+k));else if(b===0)console.log(t.dim(" Installed widget dependencies in .moi/"));else console.warn(t.yellow(` bun install failed (exit ${b}) \u2014 run it manually in .moi/`)),console.warn(t.dim(" Install log: "+k));d=await z(i,{...e.id?{id:e.id}:{},harness:h,...v?{name:v.name,agentId:v.agentId,isDefault:v.isDefault,lastRunAt:v.lastRunAt}:{}}),console.log(t.green("\u2713")+" Initialized "+t.bold(i)+t.dim(" ("+h+")")),console.log(" Skills installed to "+t.dim(x)+" \u2014 ask "+(h==="claude-code"?"Claude":"your agent")+` to build a widget or a view to get started
91
- `)}let u=await P();if(!u&&e.web){console.log(t.dim(" Starting server\u2026"));let g=Oe(c,!1),h=Y(g);if(u=await to(),!u)console.error(t.red(` Server failed to start
89
+ `),process.exit(1)}let c=H,f=process.stdout.isTTY,d;if(e.remote!==void 0)try{let g=await oo(i,pt(e.remote));if(e.json){console.log(JSON.stringify(g));return}if(d=g,console.log(t.green("\u2713")+" Linked "+t.bold(g.path)+" to "+e.remote),console.log(`
90
+ Next:`),console.log(" 1. Read "+Co(ye(g.path),"moi-workspace","SKILL.md")),console.log(" 2. Run commands from "+g.path),console.log(" 3. Run `moi remote` for available commands\n"),!e.web)return}catch(g){console.error(g instanceof Error?g.message:"Remote initialization failed"),process.exitCode=1;return}else{let g=await O(i);if(g.remote){console.error(`This is a remote workspace \u2014 use moi init --remote ${g.remote.user_id}:${g.remote.workspace_id}`),process.exitCode=1;return}let{harness:h,agent:v}=await $n(i,e.harness);console.log();let{scaffold:b,skillsDir:x,installLogPath:k}=await J(i,h);if(b!=="exists"&&b!=="skipped")if(b==="installing")console.log(t.dim(" Widget dependencies still installing in .moi/ (background)")),console.log(t.dim(" Install log: "+k));else if(b===0)console.log(t.dim(" Installed widget dependencies in .moi/"));else console.warn(t.yellow(` bun install failed (exit ${b}) \u2014 run it manually in .moi/`)),console.warn(t.dim(" Install log: "+k));d=await z(i,{...e.id?{id:e.id}:{},harness:h,...v?{name:v.name,agentId:v.agentId,isDefault:v.isDefault,lastRunAt:v.lastRunAt}:{}}),console.log(t.green("\u2713")+" Initialized "+t.bold(i)+t.dim(" ("+h+")")),console.log(" Skills installed to "+t.dim(x)+" \u2014 ask "+(h==="claude-code"?"Claude":"your agent")+` to build a widget or a view to get started
91
+ `)}let u=await P();if(!u&&e.web){console.log(t.dim(" Starting server\u2026"));let g=Ae(c,!1),h=Y(g);if(u=await no(),!u)console.error(t.red(` Server failed to start
92
92
  `)),await h.exited,process.exit(1);let v=`http://localhost:${w}/workspace/${d.id}`;if(console.log(t.green("\u2713")+" Server started on http://localhost:"+w),f)console.log(" Opening "+t.bold(v));if(console.log(t.dim(` Press Ctrl+C to stop
93
93
  `)),f)await _e(v);process.exit(await lr(h,()=>Y(g)))}if(u){await ee(i);let g=`http://localhost:${w}/workspace/${d.id}`;if(f)console.log(" Opening "+t.bold(g)+`
94
94
  `),await _e(g);else console.log(" Ready at "+t.bold(g)+`
95
95
  `);process.exit(0)}console.log(" Run "+t.bold("moi start")+` to open in the browser
96
- `)}});import{resolve as Rn}from"path";var $o=a({meta:{name:"navigate",description:"Navigate the last active browser showing this workspace"},args:{href:{type:"positional",required:!0,description:"Workspace address, e.g. moi:/views/events?eventId=123"},dir:S},run({args:e}){try{let i=Pt(e.href);if(!i.startsWith("moi:/")||i.startsWith("moi:/files/"))throw Error("Navigation needs a workspace page address")}catch(i){console.error(i instanceof Error?i.message:"Invalid workspace address"),process.exit(1)}let n=Rn(e.dir);j(n,{type:"navigate",path:n,href:e.href},(i)=>{console.log(`
96
+ `)}});import{resolve as Rn}from"path";var Ro=a({meta:{name:"navigate",description:"Navigate the last active browser showing this workspace"},args:{href:{type:"positional",required:!0,description:"Workspace address, e.g. moi:/views/events?eventId=123"},dir:S},run({args:e}){try{let i=Pt(e.href);if(!i.startsWith("moi:/")||i.startsWith("moi:/files/"))throw Error("Navigation needs a workspace page address")}catch(i){console.error(i instanceof Error?i.message:"Invalid workspace address"),process.exit(1)}let n=Rn(e.dir);j(n,{type:"navigate",path:n,href:e.href},(i)=>{console.log(`
97
97
  `+t.green("\u2713")+" Navigated to "+t.bold(String(i.href))+`
98
98
  `)})}});function On(e,n){let i=e.find((c)=>c.agentId===n);if(i)return i;let l=n.toLowerCase();return e.find((c)=>c.name?.toLowerCase()===l)??null}function Be(e){console.log(R(["","agentId","name","workspace"].map((n)=>t.dim(n)),e.map((n)=>[n.isDefault?t.green("\u25CF"):" ",n.isDefault?t.bold(n.agentId):n.agentId,n.name??t.dim("\u2014"),t.dim(n.path)])))}var An=a({meta:{name:"init",description:"Install Moi skills into an OpenClaw agent workspace. Run without args to list discovered agents."},args:{agent:{type:"positional",required:!1,description:"Agent id or name (omit to list agents)"}},async run({args:e}){let n=await Ie();if(n.length===0)console.error(`
99
99
  `+t.red("\u2717")+` No OpenClaw agents discovered.
@@ -110,21 +110,21 @@ Next:`),console.log(" 1. Read "+xo(ye(g.path),"moi-workspace","SKILL.md")),cons
110
110
  `+t.green("\u2713")+" Installed skills to "+t.bold(c)),console.log(t.dim(" Agent: ")+t.bold(i.agentId)+(i.name?t.dim(" ("+i.name+")"):""));let u=process.stdout.isTTY;if(await P()){let h=`http://localhost:${w}/workspace/${d.id}`;if(await ee(i.path),u)console.log(" Opening "+t.bold(h)+`
111
111
  `),await _e(h);else console.log(" Ready at "+t.bold(h)+`
112
112
  `)}else console.log(" Run "+t.bold("moi start")+` to open in the browser
113
- `);process.exit(0)}}),Ro=a({meta:{name:"openclaw",description:"OpenClaw integration commands"},async run({rawArgs:e}){if(e.some((i)=>!i.startsWith("-")))return;console.log(`
113
+ `);process.exit(0)}}),Oo=a({meta:{name:"openclaw",description:"OpenClaw integration commands"},async run({rawArgs:e}){if(e.some((i)=>!i.startsWith("-")))return;console.log(`
114
114
  `+t.bold("OpenClaw")),$e("openclaw","[agent]");let n=await Ie().catch(()=>[]);if(n.length===0){console.log(`
115
115
  `+t.dim("No agents discovered \u2014 start the OpenClaw gateway and check ")+t.dim("~/.openclaw/openclaw.json")+`
116
116
  `);return}console.log(`
117
117
  `+t.bold(" Agents")),Be(n),console.log(t.dim(`
118
118
  Run `)+t.bold(Re("openclaw",n.length,"agentId"))+`
119
- `)},subCommands:{init:An}});var Oo=a({meta:{name:"refresh",description:"Refresh widget and view data in your tabs for the current workspace."},args:{only:q},async run({args:e}){let n=F(e.only),i=await te(process.cwd()),l=new WebSocket(N);l.onopen=()=>l.send(JSON.stringify({type:"applets:refresh",only:n,path:process.cwd()})),l.onmessage=(c)=>{let f=JSON.parse(String(c.data));if(f.error)console.error(`
119
+ `)},subCommands:{init:An}});var Ao=a({meta:{name:"refresh",description:"Refresh widget and view data in your tabs for the current workspace."},args:{only:q},async run({args:e}){let n=F(e.only),i=await te(process.cwd()),l=new WebSocket(N);l.onopen=()=>l.send(JSON.stringify({type:"applets:refresh",only:n,path:process.cwd()})),l.onmessage=(c)=>{let f=JSON.parse(String(c.data));if(f.error)console.error(`
120
120
  `+t.red("\u2717")+" "+f.error+`
121
121
  `),l.close(),process.exit(1);if(console.log(`
122
122
  `+t.green("\u2713")+" Refresh signal sent"+(n?` (${n})`:"")+`
123
123
  `),i)console.log(t.yellow(i)+`
124
- `);l.close(),process.exit(0)},l.onerror=()=>void _()}});import{mkdir as Tn,rename as In,rm as En}from"fs/promises";import{basename as Nn,dirname as Pn,resolve as Ve}from"path";var be={type:"boolean",description:"Print JSON result"},Wn=s({exitCode:m().int(),stdout:r(),stderr:r()});async function jn(e,n=!1){let i=Wn.parse(await e.json());if(n)console.log(JSON.stringify(i));else process.stdout.write(i.stdout),process.stderr.write(i.stderr);process.exitCode=i.exitCode<0?1:i.exitCode}async function To(e,n,i){let l=await B(i);if(!l)return!1;let c=await gt(M.commands.path(l),{method:"POST",body:JSON.stringify({command:e,args:n}),contentType:"application/json"});return await jn(c),!0}var Dn=Qt("type",[s({type:o("stdout"),data:r()}),s({type:o("stderr"),data:r()}),s({type:o("exit"),code:m().int()})]);async function ie(){let e=await B();if(!e){let n=await dr(process.cwd()),i=await O(n),l="This folder is not linked to a remote workspace";if(!i.remote&&await Bun.file(ge(n)).exists()){let c=Bun.stripANSI(i.name||Nn(n)).replace(/[\u0000-\u001f\u007f-\u009f]/g,"");l+=`
125
- It is an existing local workspace: ${c}`}throw Error(l)}return{file:(n,i)=>gt(M.files.path(e,n),i),exec:(n)=>gt(M.exec.path(e),n)}}async function Ao(){if(process.stdin.isTTY)throw Error("Supply content or pipe it on stdin");return Bun.stdin.text()}function Io(e){let n=a({meta:{name:"read",description:"Read a remote workspace file to stdout"},args:{file:{type:"positional",required:!0}},run:({args:u})=>e(async()=>{let g=await(await ie()).file(u.file);if(g.body)for await(let h of g.body)await Bun.write(Bun.stdout,h)})}),i=a({meta:{name:"write",description:"Write a remote file; content argument or stdin"},args:{file:{type:"positional",required:!0},content:{type:"positional",required:!1},json:be},run:({args:u})=>e(async()=>{let g=await(await ie()).file(u.file,{method:"PUT",body:u.content??await Ao(),contentType:"application/octet-stream"});console.log(u.json?JSON.stringify(await g.json()):`Wrote ${u.file}`)})}),l=a({meta:{name:"patch",description:"Apply a unified diff to a remote file (stdin or --patch-file)"},args:{file:{type:"positional",required:!0},"patch-file":{type:"string"},json:be},run:({args:u})=>e(async()=>{let g=u["patch-file"]?await Bun.file(Ve(u["patch-file"])).text():await Ao(),h=await(await ie()).file(u.file,{method:"PATCH",body:JSON.stringify({patch:g}),contentType:"application/json"});console.log(u.json?JSON.stringify(await h.json()):`Patched ${u.file}`)})}),c=a({meta:{name:"file-upload",description:"Upload a local file to a remote workspace path"},args:{source:{type:"positional",required:!0},destination:{type:"positional",required:!0},json:be},run:({args:u})=>e(async()=>{let g=Bun.file(Ve(u.source));if(!await g.exists())throw Error("Local source file not found");let h=await(await ie()).file(u.destination,{method:"PUT",body:g,contentType:"application/octet-stream"});console.log(u.json?JSON.stringify(await h.json()):`Uploaded ${u.destination}`)})}),f=a({meta:{name:"file-download",description:"Download a remote workspace file to a local path"},args:{source:{type:"positional",required:!0},destination:{type:"positional",required:!0},json:be},run:({args:u})=>e(async()=>{let g=await(await ie()).file(u.source),h=Ve(u.destination),v=`${h}.${crypto.randomUUID()}.tmp`;await Tn(Pn(h),{recursive:!0});try{await Bun.write(v,g),await In(v,h)}finally{await En(v,{force:!0})}console.log(u.json?JSON.stringify({ok:!0,path:h}):`Downloaded ${u.destination}`)})}),d=a({meta:{name:"exec",description:"Run a shell command on the remote host, in this workspace"},args:{command:{type:"positional",required:!0},json:be},run:({args:u})=>e(async()=>{let g=new AbortController,h=await ie(),v=crypto.randomUUID(),b,x=()=>{b??=h.exec({method:"POST",body:JSON.stringify({cancel:v}),contentType:"application/json",signal:AbortSignal.timeout(1e4)}).then(async(k)=>{await k.body?.cancel()}).catch(()=>{console.error("Could not confirm the remote command stopped")}).finally(()=>g.abort())};process.once("SIGINT",x);try{let k=await h.exec({method:"POST",body:JSON.stringify({command:u.command,id:v}),contentType:"application/json",signal:g.signal});if(!k.body)throw Error("Remote execution returned no stream");let y="",A,E=new TextDecoder;for await(let Ot of k.body){y+=E.decode(Ot,{stream:!0});let je;while((je=y.indexOf(`
126
- `))!==-1){let Tt=y.slice(0,je);y=y.slice(je+1);let ae=Dn.parse(JSON.parse(Tt));if(u.json)console.log(JSON.stringify(ae));if(ae.type==="exit")A=ae.code;else if(!u.json)(ae.type==="stdout"?process.stdout:process.stderr).write(ae.data)}}if(A===void 0||y)throw Error("Remote execution disconnected before the exit code; command may still have run");process.exitCode=A<0?1:A}catch(k){if(!b)throw k}finally{if(process.removeListener("SIGINT",x),await b,b)process.exitCode=130}})});return{read:n,write:i,patch:l,exec:d,"file-upload":c,"file-download":f}}import{clearLine as Ln,cursorTo as Eo}from"readline";var T=(e)=>Bun.stripANSI(e).replace(/[\u0000-\u001f\u007f-\u009f]/g,"");async function No(){try{let{root:e,harness:n}=await Ne(process.cwd());if(!n&&!await Bun.file(ge(e)).exists())return;let i=await te(e);if(i)console.error(`
127
- `+t.yellow(i))}catch{}}async function U(e){try{await e()}catch(n){if(n instanceof fe||n instanceof Error&&n.message==="Not signed in \u2014 run moi remote login")console.error(`${t.dim("\u203A")} Signed out`),console.error(t.dim("\u203A Run ")+t.cyan("moi remote login")+t.dim(" to connect to Moi Cloud"));else console.error(n instanceof Error?n.message:"Cloud request failed");process.exitCode=1}}function Mn(){if(!process.stderr.isTTY)return console.error("Waiting for authentication\u2026"),()=>{};let n=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],i=0,l=()=>{Eo(process.stderr,0),process.stderr.write(t.dim(`${n[i++%n.length]} ${"Waiting for authentication\u2026"}`))};l();let c=setInterval(l,80),f=()=>{clearInterval(c),Ln(process.stderr,0),Eo(process.stderr,0),process.removeListener("SIGINT",d)},d=()=>{f(),process.exit(130)};return process.once("SIGINT",d),f}var Un=a({meta:{name:"login",description:"Sign in to Moi Cloud in your browser (for humans only)"},args:{browser:{type:"boolean",default:!0,description:"Open the login page (use --no-browser to print its URL only)"}},async run({args:e}){await U(async()=>{let n=()=>{};try{await bs(async(c,f)=>{if(console.log(`
124
+ `);l.close(),process.exit(0)},l.onerror=()=>void _()}});import{mkdir as Tn,rename as In,rm as En}from"fs/promises";import{basename as Nn,dirname as Pn,resolve as Ve}from"path";var be={type:"boolean",description:"Print JSON result"},Wn=s({exitCode:m().int(),stdout:r(),stderr:r()});async function jn(e,n=!1){let i=Wn.parse(await e.json());if(n)console.log(JSON.stringify(i));else process.stdout.write(i.stdout),process.stderr.write(i.stderr);process.exitCode=i.exitCode<0?1:i.exitCode}async function Io(e,n,i){let l=await B(i);if(!l)return!1;let c=await gt(M.commands.path(l),{method:"POST",body:JSON.stringify({command:e,args:n}),contentType:"application/json"});return await jn(c),!0}var Dn=Qt("type",[s({type:o("stdout"),data:r()}),s({type:o("stderr"),data:r()}),s({type:o("exit"),code:m().int()})]);async function ie(){let e=await B();if(!e){let n=await dr(process.cwd()),i=await O(n),l="This folder is not linked to a remote workspace";if(!i.remote&&await Bun.file(ge(n)).exists()){let c=Bun.stripANSI(i.name||Nn(n)).replace(/[\u0000-\u001f\u007f-\u009f]/g,"");l+=`
125
+ It is an existing local workspace: ${c}`}throw Error(l)}return{file:(n,i)=>gt(M.files.path(e,n),i),exec:(n)=>gt(M.exec.path(e),n)}}async function To(){if(process.stdin.isTTY)throw Error("Supply content or pipe it on stdin");return Bun.stdin.text()}function Eo(e){let n=a({meta:{name:"read",description:"Read a remote workspace file to stdout"},args:{file:{type:"positional",required:!0}},run:({args:u})=>e(async()=>{let g=await(await ie()).file(u.file);if(g.body)for await(let h of g.body)await Bun.write(Bun.stdout,h)})}),i=a({meta:{name:"write",description:"Write a remote file; content argument or stdin"},args:{file:{type:"positional",required:!0},content:{type:"positional",required:!1},json:be},run:({args:u})=>e(async()=>{let g=await(await ie()).file(u.file,{method:"PUT",body:u.content??await To(),contentType:"application/octet-stream"});console.log(u.json?JSON.stringify(await g.json()):`Wrote ${u.file}`)})}),l=a({meta:{name:"patch",description:"Apply a unified diff to a remote file (stdin or --patch-file)"},args:{file:{type:"positional",required:!0},"patch-file":{type:"string"},json:be},run:({args:u})=>e(async()=>{let g=u["patch-file"]?await Bun.file(Ve(u["patch-file"])).text():await To(),h=await(await ie()).file(u.file,{method:"PATCH",body:JSON.stringify({patch:g}),contentType:"application/json"});console.log(u.json?JSON.stringify(await h.json()):`Patched ${u.file}`)})}),c=a({meta:{name:"file-upload",description:"Upload a local file to a remote workspace path"},args:{source:{type:"positional",required:!0},destination:{type:"positional",required:!0},json:be},run:({args:u})=>e(async()=>{let g=Bun.file(Ve(u.source));if(!await g.exists())throw Error("Local source file not found");let h=await(await ie()).file(u.destination,{method:"PUT",body:g,contentType:"application/octet-stream"});console.log(u.json?JSON.stringify(await h.json()):`Uploaded ${u.destination}`)})}),f=a({meta:{name:"file-download",description:"Download a remote workspace file to a local path"},args:{source:{type:"positional",required:!0},destination:{type:"positional",required:!0},json:be},run:({args:u})=>e(async()=>{let g=await(await ie()).file(u.source),h=Ve(u.destination),v=`${h}.${crypto.randomUUID()}.tmp`;await Tn(Pn(h),{recursive:!0});try{await Bun.write(v,g),await In(v,h)}finally{await En(v,{force:!0})}console.log(u.json?JSON.stringify({ok:!0,path:h}):`Downloaded ${u.destination}`)})}),d=a({meta:{name:"exec",description:"Run a shell command on the remote host, in this workspace"},args:{command:{type:"positional",required:!0},json:be},run:({args:u})=>e(async()=>{let g=new AbortController,h=await ie(),v=crypto.randomUUID(),b,x=()=>{b??=h.exec({method:"POST",body:JSON.stringify({cancel:v}),contentType:"application/json",signal:AbortSignal.timeout(1e4)}).then(async(k)=>{await k.body?.cancel()}).catch(()=>{console.error("Could not confirm the remote command stopped")}).finally(()=>g.abort())};process.once("SIGINT",x);try{let k=await h.exec({method:"POST",body:JSON.stringify({command:u.command,id:v}),contentType:"application/json",signal:g.signal});if(!k.body)throw Error("Remote execution returned no stream");let y="",A,E=new TextDecoder;for await(let Ot of k.body){y+=E.decode(Ot,{stream:!0});let Le;while((Le=y.indexOf(`
126
+ `))!==-1){let Tt=y.slice(0,Le);y=y.slice(Le+1);let ae=Dn.parse(JSON.parse(Tt));if(u.json)console.log(JSON.stringify(ae));if(ae.type==="exit")A=ae.code;else if(!u.json)(ae.type==="stdout"?process.stdout:process.stderr).write(ae.data)}}if(A===void 0||y)throw Error("Remote execution disconnected before the exit code; command may still have run");process.exitCode=A<0?1:A}catch(k){if(!b)throw k}finally{if(process.removeListener("SIGINT",x),await b,b)process.exitCode=130}})});return{read:n,write:i,patch:l,exec:d,"file-upload":c,"file-download":f}}import{clearLine as Ln,cursorTo as No}from"readline";var T=(e)=>Bun.stripANSI(e).replace(/[\u0000-\u001f\u007f-\u009f]/g,"");async function Po(){try{let{root:e,harness:n}=await Oe(process.cwd());if(!n&&!await Bun.file(ge(e)).exists())return;let i=await te(e);if(i)console.error(`
127
+ `+t.yellow(i))}catch{}}async function U(e){try{await e()}catch(n){if(n instanceof fe||n instanceof Error&&n.message==="Not signed in \u2014 run moi remote login")console.error(`${t.dim("\u203A")} Signed out`),console.error(t.dim("\u203A Run ")+t.cyan("moi remote login")+t.dim(" to connect to Moi Cloud"));else console.error(n instanceof Error?n.message:"Cloud request failed");process.exitCode=1}}function Mn(){if(!process.stderr.isTTY)return console.error("Waiting for authentication\u2026"),()=>{};let n=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],i=0,l=()=>{No(process.stderr,0),process.stderr.write(t.dim(`${n[i++%n.length]} ${"Waiting for authentication\u2026"}`))};l();let c=setInterval(l,80),f=()=>{clearInterval(c),Ln(process.stderr,0),No(process.stderr,0),process.removeListener("SIGINT",d)},d=()=>{f(),process.exit(130)};return process.once("SIGINT",d),f}var Un=a({meta:{name:"login",description:"Sign in to Moi Cloud in your browser (for humans only)"},args:{browser:{type:"boolean",default:!0,description:"Open the login page (use --no-browser to print its URL only)"}},async run({args:e}){await U(async()=>{let n=()=>{};try{await bs(async(c,f)=>{if(console.log(`
128
128
  Visit ${t.bold(c)}
129
129
  Code: ${T(f)}
130
130
  `),e.browser)await Pr(c).catch(()=>{});n=Mn()})}finally{n()}let{me:i}=await Jn(),l="email"in i?i.email:i.name;console.log(`${t.green("\u2713")} Signed in as ${T(l)}
@@ -139,16 +139,16 @@ Help and full command list: `+t.cyan("moi remote workspaces --help")+`
139
139
  `)})}}),Bn=a({meta:{name:"accept",description:"Accept a workspace invitation as a human or agent"},args:{invite:{type:"positional",required:!0},name:{type:"string",description:"Your agent display name, shown to workspace members"},client:{type:"string",description:"The app you run in, as a lowercase id such as dot or grok-bot"},json:se},async run({args:e}){await U(async()=>{let n=await Ss(e.invite,e.name,e.client);console.log(e.json?JSON.stringify(n):`Invitation accepted
140
140
 
141
141
  Create a local linked folder (choose an unused folder name):
142
- moi init ./workspace-folder --remote ${n.remote.user_id}:${n.remote.workspace_id}`)})}}),Vn=a({meta:{name:"leave",description:"Leave a shared workspace; keep local files"},args:{workspace:{type:"positional",required:!1,description:"ownerId:workspaceId (defaults to current folder)"},json:se},async run({args:e}){await U(async()=>{let n=e.workspace!==void 0?pt(e.workspace):await B();if(!n)throw Error("No remote workspace here \u2014 run from a linked workspace folder or provide ownerId:workspaceId");let i=await Es(n.user_id,n.workspace_id);console.log(e.json?JSON.stringify(i):"Left the workspace; local files kept")})}}),Po={...Io(U),login:Un,logout:Hn,"rename-agent":qn,workspaces:Fn,invitations:zn,accept:Bn,leave:Vn},Wo=a({meta:{name:"remote",description:"Show your identity and linked workspace commands"},args:{json:se},subCommands:Po,setup({rawArgs:e}){let n=e.indexOf("--");if((n<0?e:e.slice(0,n)).some((l)=>l==="--path"||l.startsWith("--path=")))throw Error("Unknown option --path \u2014 run this command from the workspace folder")},async run({args:e,rawArgs:n}){let i=n.find((l)=>!l.startsWith("-"));if(i&&Object.hasOwn(Po,i))return;await U(async()=>{let l={...await Jn(),currentWorkspace:await B()};if(e.json){console.log(JSON.stringify(l,null,2)),await No();return}let c="email"in l.me?l.me.email:l.me.client;console.log(`
142
+ moi init ./workspace-folder --remote ${n.remote.user_id}:${n.remote.workspace_id}`)})}}),Vn=a({meta:{name:"leave",description:"Leave a shared workspace; keep local files"},args:{workspace:{type:"positional",required:!1,description:"ownerId:workspaceId (defaults to current folder)"},json:se},async run({args:e}){await U(async()=>{let n=e.workspace!==void 0?pt(e.workspace):await B();if(!n)throw Error("No remote workspace here \u2014 run from a linked workspace folder or provide ownerId:workspaceId");let i=await Es(n.user_id,n.workspace_id);console.log(e.json?JSON.stringify(i):"Left the workspace; local files kept")})}}),Wo={...Eo(U),login:Un,logout:Hn,"rename-agent":qn,workspaces:Fn,invitations:zn,accept:Bn,leave:Vn},jo=a({meta:{name:"remote",description:"Show your identity and linked workspace commands"},args:{json:se},subCommands:Wo,setup({rawArgs:e}){let n=e.indexOf("--");if((n<0?e:e.slice(0,n)).some((l)=>l==="--path"||l.startsWith("--path=")))throw Error("Unknown option --path \u2014 run this command from the workspace folder")},async run({args:e,rawArgs:n}){let i=n.find((l)=>!l.startsWith("-"));if(i&&Object.hasOwn(Wo,i))return;await U(async()=>{let l={...await Jn(),currentWorkspace:await B()};if(e.json){console.log(JSON.stringify(l,null,2)),await Po();return}let c="email"in l.me?l.me.email:l.me.client;console.log(`
143
143
  Signed in as `+t.bold(T(l.me.name||c))+t.dim(` <${T(c)}>`));let f=l.currentWorkspace;if(f){let d=l.workspaces.find((u)=>u.id===f.workspace_id&&u.owner.id===f.user_id);console.log(`
144
144
  Current workspace is linked to: `+t.bold(T(f.workspace_id))+(d?" by "+T(d.owner.email):"")),console.log("Remote ID: "+T(`${f.user_id}:${f.workspace_id}`)),console.log(`
145
145
  `+ot([[t.cyan("moi remote read <remote-path>"),"Read a file"],[t.cyan('moi remote write <remote-path> "content"'),"Write a file"],[t.cyan("moi remote patch <remote-path>"),"Apply a diff from stdin"],[t.cyan('moi remote exec "command"'),"Run a command remotely"],[t.cyan("moi remote file-upload <local-path> <remote-path>"),"Upload a local file"],[t.cyan("moi remote file-download <remote-path> <local-path>"),"Download a remote file"]])),console.log(`
146
146
  `+t.cyan("moi check|bundle|theme|config|tabs|ui-components|call-server-fn|debug|scratch")+`
147
147
  `+t.dim("These regular commands work on the remote workspace"))}else console.log(`
148
148
  This folder is not linked to a remote workspace`);if(console.log(`
149
- `+t.dim("Help and full command list: ")+t.cyan("moi remote --help")),f)console.log(t.dim("Command help: ")+t.cyan("moi remote <command> --help"));console.log(),await No()})}});import{tmpdir as Lo}from"os";import{join as Mo,resolve as I}from"path";function Q(e){let n=e.split(",").map((i)=>Number(i.trim()));if(n.length!==2||!n.every((i)=>Number.isFinite(i)))throw Error(`Expected "x,y", got "${e}"`);return{x:n[0],y:n[1]}}function jo(e){if(/^-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?$/.test(e))return Q(e);return{name:e}}var _o={black:"#1d1d1d",red:"#e03131",yellow:"#f1ac4b",green:"#099268",blue:"#4465e9",grey:"#9fa8b2"},Ae=Object.keys(_o),Uo={small:"m",large:"xl"},Ho=Object.keys(Uo),qo={regular:"m",big:"xl"},zo=Object.keys(qo),Fo={none:"none",semi:"solid",pattern:"pattern",solid:"fill"},Jo=Object.keys(Fo);function Do(e){let n=e.trim().replace(/^#/,"");if(n.length===3)n=n.replace(/(.)/g,"$1$1");if(!/^[0-9a-fA-F]{6}$/.test(n))return null;return[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)]}function Kn(e){let n=e.trim().toLowerCase();if(Ae.includes(n))return n;let i=Do(e);if(!i)throw Error(`Unknown color "${e}". Use a hex like "#4465e9" or one of: ${Ae.join(", ")}.`);let l="black",c=1/0;for(let f of Ae){let[d,u,g]=Do(_o[f]),h=(d-i[0])**2+(u-i[1])**2+(g-i[2])**2;if(h<c)c=h,l=f}return l}function Yn(e){let n=Uo[e.trim().toLowerCase()];if(!n)throw Error(`Unknown stroke "${e}". Use one of: ${Ho.join(", ")}.`);return n}function Gn(e){let n=qo[e.trim().toLowerCase()];if(!n)throw Error(`Unknown font size "${e}". Use one of: ${zo.join(", ")}.`);return n}function Zn(e){let n=Fo[e.trim().toLowerCase()];if(!n)throw Error(`Unknown fill "${e}". Use one of: ${Jo.join(", ")}.`);return n}function Qn(e){if(!e)return"lo";let n=e.trim().toLowerCase();if(n==="lo"||n==="hi")return n;throw Error(`Unknown quality "${e}". Use "lo" or "hi".`)}var Pe={type:"string",description:`Color: ${Ae.join(", ")}, or any hex (snapped to nearest)`},er={type:"string",description:`Stroke weight: ${Ho.join(", ")}`},Ye={type:"string",description:`Font size: ${zo.join(", ")}`},nr={type:"string",default:"semi",description:`Fill: ${Jo.join(", ")} (default: semi)`};function We(e){return{...e.color?{color:Kn(e.color)}:{},...e.stroke?{size:Yn(e.stroke)}:{},...e.fontSize?{size:Gn(e.fontSize)}:{},...e.fill?{fill:Zn(e.fill)}:{}}}function L(e,n,i){j(e,{type:"scratch",path:e,op:n},i)}function ke(e){let n=e.result;console.log(`
149
+ `+t.dim("Help and full command list: ")+t.cyan("moi remote --help")),f)console.log(t.dim("Command help: ")+t.cyan("moi remote <command> --help"));console.log(),await Po()})}});import{tmpdir as Mo}from"os";import{join as _o,resolve as I}from"path";function Q(e){let n=e.split(",").map((i)=>Number(i.trim()));if(n.length!==2||!n.every((i)=>Number.isFinite(i)))throw Error(`Expected "x,y", got "${e}"`);return{x:n[0],y:n[1]}}function Do(e){if(/^-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?$/.test(e))return Q(e);return{name:e}}var Uo={black:"#1d1d1d",red:"#e03131",yellow:"#f1ac4b",green:"#099268",blue:"#4465e9",grey:"#9fa8b2"},Pe=Object.keys(Uo),Ho={small:"m",large:"xl"},qo=Object.keys(Ho),zo={regular:"m",big:"xl"},Fo=Object.keys(zo),Jo={none:"none",semi:"solid",pattern:"pattern",solid:"fill"},Bo=Object.keys(Jo);function Lo(e){let n=e.trim().replace(/^#/,"");if(n.length===3)n=n.replace(/(.)/g,"$1$1");if(!/^[0-9a-fA-F]{6}$/.test(n))return null;return[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)]}function Kn(e){let n=e.trim().toLowerCase();if(Pe.includes(n))return n;let i=Lo(e);if(!i)throw Error(`Unknown color "${e}". Use a hex like "#4465e9" or one of: ${Pe.join(", ")}.`);let l="black",c=1/0;for(let f of Pe){let[d,u,g]=Lo(Uo[f]),h=(d-i[0])**2+(u-i[1])**2+(g-i[2])**2;if(h<c)c=h,l=f}return l}function Yn(e){let n=Ho[e.trim().toLowerCase()];if(!n)throw Error(`Unknown stroke "${e}". Use one of: ${qo.join(", ")}.`);return n}function Gn(e){let n=zo[e.trim().toLowerCase()];if(!n)throw Error(`Unknown font size "${e}". Use one of: ${Fo.join(", ")}.`);return n}function Zn(e){let n=Jo[e.trim().toLowerCase()];if(!n)throw Error(`Unknown fill "${e}". Use one of: ${Bo.join(", ")}.`);return n}function Qn(e){if(!e)return"lo";let n=e.trim().toLowerCase();if(n==="lo"||n==="hi")return n;throw Error(`Unknown quality "${e}". Use "lo" or "hi".`)}var We={type:"string",description:`Color: ${Pe.join(", ")}, or any hex (snapped to nearest)`},er={type:"string",description:`Stroke weight: ${qo.join(", ")}`},Ke={type:"string",description:`Font size: ${Fo.join(", ")}`},nr={type:"string",default:"semi",description:`Fill: ${Bo.join(", ")} (default: semi)`};function je(e){return{...e.color?{color:Kn(e.color)}:{},...e.stroke?{size:Yn(e.stroke)}:{},...e.fontSize?{size:Gn(e.fontSize)}:{},...e.fill?{fill:Zn(e.fill)}:{}}}function L(e,n,i){j(e,{type:"scratch",path:e,op:n},i)}function ke(e){let n=e.result;console.log(`
150
150
  `+t.green("\u2713")+" added "+t.bold(n?.name??"(shape)")+`
151
- `)}var ir=a({meta:{name:"read",description:"Print the canvas shapes as JSON (served off disk)"},args:{dir:S},run({args:e}){L(I(e.dir),{kind:"read"},(n)=>{console.log(JSON.stringify(n.shapes??[],null,2))})}}),sr=a({meta:{name:"view",description:"Render the canvas to a PNG (needs an open Scratchpad tab)"},args:{dir:S,out:{type:"string",description:"Output PNG path (default: a temp file)"}},async run({args:e}){L(I(e.dir),{kind:"view"},async(n)=>{let i=n.result;if(!i?.image)console.error(t.red("No image returned")),process.exit(1);let l=i.image.replace(/^data:image\/png;base64,/,""),c=e.out?I(e.out):Mo(Lo(),`moi-scratch-${Date.now()}.png`);await Bun.write(c,Buffer.from(l,"base64")),console.log(c)})}}),cr={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg","image/avif":"avif","image/apng":"apng","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov"},mr=a({meta:{name:"read-image",description:"Save an image shape to a file by id (served off disk)"},args:{id:{type:"positional",required:!0,description:"Image shape id (from `scratch read`)"},out:{type:"string",description:"Output file path (default: a temp file)"},dir:S},async run({args:e}){L(I(e.dir),{kind:"read-image",name:e.id},async(n)=>{let i=n.src;if(!i)console.error(t.red("No image data")),process.exit(1);if(/^https?:\/\//.test(i)){console.log(i);return}let l=i.match(/^data:([^;,]+)(;base64)?,(.*)$/s);if(!l)console.error(t.red("Unrecognized image source")),process.exit(1);let[,c,f,d]=l,u=f?Buffer.from(d,"base64"):Buffer.from(decodeURIComponent(d),"utf8"),g=cr[c]??"bin",h=e.id.replace(/[^a-zA-Z0-9_-]/g,"_"),v=e.out?I(e.out):Mo(Lo(),`moi-scratch-${h}-${Date.now()}.${g}`);await Bun.write(v,u),console.log(v)})}}),pr=a({meta:{name:"text",description:"Add a text shape"},args:{at:{type:"string",required:!0,description:'Position "x,y"'},text:{type:"string",required:!0,description:"Text content"},id:{type:"string",description:"Stable name to address this shape later"},color:Pe,fontSize:Ye,dir:S},run({args:e}){let{x:n,y:i}=Q(e.at);L(I(e.dir),{kind:"add-text",name:e.id??"",x:n,y:i,text:e.text,...We({color:e.color,fontSize:e.fontSize})},ke)}}),fr=a({meta:{name:"rect",description:"Add a rectangle"},args:{at:{type:"string",required:!0,description:'Top-left position "x,y"'},size:{type:"string",required:!0,description:'Size "w,h"'},text:{type:"string",description:"Optional label"},id:{type:"string",description:"Stable name to address this shape later"},color:Pe,fill:nr,fontSize:Ye,dir:S},run({args:e}){let{x:n,y:i}=Q(e.at),{x:l,y:c}=Q(e.size);L(I(e.dir),{kind:"add-rect",name:e.id??"",x:n,y:i,w:l,h:c,...e.text?{text:e.text}:{},...We({color:e.color,fill:e.fill,fontSize:e.fontSize})},ke)}}),ur=a({meta:{name:"note",description:"Add a sticky note"},args:{at:{type:"string",required:!0,description:'Position "x,y"'},text:{type:"string",required:!0,description:"Note content"},id:{type:"string",description:"Stable name to address this shape later"},color:Pe,fontSize:Ye,dir:S},run({args:e}){let{x:n,y:i}=Q(e.at);L(I(e.dir),{kind:"add-note",name:e.id??"",x:n,y:i,text:e.text,...We({color:e.color,fontSize:e.fontSize})},ke)}}),gr=a({meta:{name:"arrow",description:"Add an arrow connecting shapes or points"},args:{from:{type:"string",required:!0,description:'Start: a shape name or "x,y"'},to:{type:"string",required:!0,description:'End: a shape name or "x,y"'},id:{type:"string",description:"Stable name to address this shape later"},elbow:{type:"boolean",description:"Right-angle (squared) routing for diagrams; default is a curved arc"},color:Pe,stroke:er,dir:S},run({args:e}){L(I(e.dir),{kind:"add-arrow",name:e.id??"",from:jo(e.from),to:jo(e.to),...e.elbow?{elbow:!0}:{},...We({color:e.color,stroke:e.stroke})},ke)}}),hr=a({meta:{name:"image",description:"Add an image from a file (resized to fit the canvas)"},args:{path:{type:"positional",required:!0,description:"Path to an image file (png/jpg/webp/gif)"},at:{type:"string",description:'Top-left position "x,y" (default: 0,0)'},id:{type:"string",description:"Stable name to address this shape later"},quality:{type:"string",description:"Resize: lo (default, smaller) or hi (sharper)"},dir:S},run({args:e}){let{x:n,y:i}=e.at?Q(e.at):{x:0,y:0};L(I(e.dir),{kind:"add-image",name:e.id??"",x:n,y:i,path:I(e.path),quality:Qn(e.quality)},ke)}}),wr=a({meta:{name:"add",description:"Add a shape: text, rect, note, arrow, or image"},subCommands:{text:pr,rect:fr,note:ur,arrow:gr,image:hr}}),yr=a({meta:{name:"move",description:"Move a shape to a new position"},args:{id:{type:"positional",required:!0,description:"Shape name"},to:{type:"string",required:!0,description:'New position "x,y"'},dir:S},run({args:e}){let{x:n,y:i}=Q(e.to);L(I(e.dir),{kind:"move",name:e.id,x:n,y:i},()=>console.log(`
151
+ `)}var ir=a({meta:{name:"read",description:"Print the canvas shapes as JSON (served off disk)"},args:{dir:S},run({args:e}){L(I(e.dir),{kind:"read"},(n)=>{console.log(JSON.stringify(n.shapes??[],null,2))})}}),sr=a({meta:{name:"view",description:"Render the canvas to a PNG (needs an open Scratchpad tab)"},args:{dir:S,out:{type:"string",description:"Output PNG path (default: a temp file)"}},async run({args:e}){L(I(e.dir),{kind:"view"},async(n)=>{let i=n.result;if(!i?.image)console.error(t.red("No image returned")),process.exit(1);let l=i.image.replace(/^data:image\/png;base64,/,""),c=e.out?I(e.out):_o(Mo(),`moi-scratch-${Date.now()}.png`);await Bun.write(c,Buffer.from(l,"base64")),console.log(c)})}}),cr={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg","image/avif":"avif","image/apng":"apng","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov"},mr=a({meta:{name:"read-image",description:"Save an image shape to a file by id (served off disk)"},args:{id:{type:"positional",required:!0,description:"Image shape id (from `scratch read`)"},out:{type:"string",description:"Output file path (default: a temp file)"},dir:S},async run({args:e}){L(I(e.dir),{kind:"read-image",name:e.id},async(n)=>{let i=n.src;if(!i)console.error(t.red("No image data")),process.exit(1);if(/^https?:\/\//.test(i)){console.log(i);return}let l=i.match(/^data:([^;,]+)(;base64)?,(.*)$/s);if(!l)console.error(t.red("Unrecognized image source")),process.exit(1);let[,c,f,d]=l,u=f?Buffer.from(d,"base64"):Buffer.from(decodeURIComponent(d),"utf8"),g=cr[c]??"bin",h=e.id.replace(/[^a-zA-Z0-9_-]/g,"_"),v=e.out?I(e.out):_o(Mo(),`moi-scratch-${h}-${Date.now()}.${g}`);await Bun.write(v,u),console.log(v)})}}),pr=a({meta:{name:"text",description:"Add a text shape"},args:{at:{type:"string",required:!0,description:'Position "x,y"'},text:{type:"string",required:!0,description:"Text content"},id:{type:"string",description:"Stable name to address this shape later"},color:We,fontSize:Ke,dir:S},run({args:e}){let{x:n,y:i}=Q(e.at);L(I(e.dir),{kind:"add-text",name:e.id??"",x:n,y:i,text:e.text,...je({color:e.color,fontSize:e.fontSize})},ke)}}),fr=a({meta:{name:"rect",description:"Add a rectangle"},args:{at:{type:"string",required:!0,description:'Top-left position "x,y"'},size:{type:"string",required:!0,description:'Size "w,h"'},text:{type:"string",description:"Optional label"},id:{type:"string",description:"Stable name to address this shape later"},color:We,fill:nr,fontSize:Ke,dir:S},run({args:e}){let{x:n,y:i}=Q(e.at),{x:l,y:c}=Q(e.size);L(I(e.dir),{kind:"add-rect",name:e.id??"",x:n,y:i,w:l,h:c,...e.text?{text:e.text}:{},...je({color:e.color,fill:e.fill,fontSize:e.fontSize})},ke)}}),ur=a({meta:{name:"note",description:"Add a sticky note"},args:{at:{type:"string",required:!0,description:'Position "x,y"'},text:{type:"string",required:!0,description:"Note content"},id:{type:"string",description:"Stable name to address this shape later"},color:We,fontSize:Ke,dir:S},run({args:e}){let{x:n,y:i}=Q(e.at);L(I(e.dir),{kind:"add-note",name:e.id??"",x:n,y:i,text:e.text,...je({color:e.color,fontSize:e.fontSize})},ke)}}),gr=a({meta:{name:"arrow",description:"Add an arrow connecting shapes or points"},args:{from:{type:"string",required:!0,description:'Start: a shape name or "x,y"'},to:{type:"string",required:!0,description:'End: a shape name or "x,y"'},id:{type:"string",description:"Stable name to address this shape later"},elbow:{type:"boolean",description:"Right-angle (squared) routing for diagrams; default is a curved arc"},color:We,stroke:er,dir:S},run({args:e}){L(I(e.dir),{kind:"add-arrow",name:e.id??"",from:Do(e.from),to:Do(e.to),...e.elbow?{elbow:!0}:{},...je({color:e.color,stroke:e.stroke})},ke)}}),hr=a({meta:{name:"image",description:"Add an image from a file (resized to fit the canvas)"},args:{path:{type:"positional",required:!0,description:"Path to an image file (png/jpg/webp/gif)"},at:{type:"string",description:'Top-left position "x,y" (default: 0,0)'},id:{type:"string",description:"Stable name to address this shape later"},quality:{type:"string",description:"Resize: lo (default, smaller) or hi (sharper)"},dir:S},run({args:e}){let{x:n,y:i}=e.at?Q(e.at):{x:0,y:0};L(I(e.dir),{kind:"add-image",name:e.id??"",x:n,y:i,path:I(e.path),quality:Qn(e.quality)},ke)}}),wr=a({meta:{name:"add",description:"Add a shape: text, rect, note, arrow, or image"},subCommands:{text:pr,rect:fr,note:ur,arrow:gr,image:hr}}),yr=a({meta:{name:"move",description:"Move a shape to a new position"},args:{id:{type:"positional",required:!0,description:"Shape name"},to:{type:"string",required:!0,description:'New position "x,y"'},dir:S},run({args:e}){let{x:n,y:i}=Q(e.to);L(I(e.dir),{kind:"move",name:e.id,x:n,y:i},()=>console.log(`
152
152
  `+t.green("\u2713")+" moved "+t.bold(e.id)+`
153
153
  `))}}),vr=a({meta:{name:"set",description:"Relabel / edit a shape's text"},args:{id:{type:"positional",required:!0,description:"Shape name"},text:{type:"string",required:!0,description:"New text"},dir:S},run({args:e}){L(I(e.dir),{kind:"set",name:e.id,text:e.text},()=>console.log(`
154
154
  `+t.green("\u2713")+" updated "+t.bold(e.id)+`
@@ -156,64 +156,64 @@ This folder is not linked to a remote workspace`);if(console.log(`
156
156
  `+t.green("\u2713")+" deleted "+t.bold(e.id)+`
157
157
  `))}}),kr=a({meta:{name:"clear",description:"Delete every shape \u2014 wipe the whole canvas"},args:{dir:S},run({args:e}){L(I(e.dir),{kind:"clear"},()=>console.log(`
158
158
  `+t.green("\u2713")+` cleared the canvas
159
- `))}}),Bo=a({meta:{name:"scratch",description:"Read and draw on the workspace Scratchpad canvas"},subCommands:{read:ir,"read-image":mr,view:sr,add:wr,move:yr,set:vr,delete:br,clear:kr}});import{existsSync as Sr}from"fs";import{dirname as xr}from"path";function Se(e){if(e===C)return null;return t.yellow("\u26A0")+` Server is running v${e}, this CLI is v${C}.
159
+ `))}}),Vo=a({meta:{name:"scratch",description:"Read and draw on the workspace Scratchpad canvas"},subCommands:{read:ir,"read-image":mr,view:sr,add:wr,move:yr,set:vr,delete:br,clear:kr}});import{existsSync as Sr}from"fs";import{dirname as xr}from"path";function Se(e){if(e===C)return null;return t.yellow("\u26A0")+` Server is running v${e}, this CLI is v${C}.
160
160
  `+t.dim(" Restart to match: `moi service restart` (service) or Ctrl-C + `moi start`.")}function G(e){let n=e instanceof V?e.message:String(e);console.error(`
161
161
  `+t.red("\u2717")+" "+n+`
162
- `),process.exit(1)}function Ko(e){if(e){console.log(" server "+t.bold(`v${e.version}`)+` running on ${lt(e)}`+t.dim(` (pid ${e.pid})`));let n=Se(e.version);if(n)console.log(`
163
- `+n)}else console.log(" "+t.yellow("server did not come up \u2014 check `moi service logs`")+t.dim(" (it may still be starting)"))}var Cr=a({meta:{name:"install",description:"Install and start the user service (launchd on macOS, systemd on Linux)"},args:{port:{type:"string",description:"HTTP port for the service server (default: 13337)"},env:{type:"string",description:"Extra env var names to capture from this shell, comma-separated (e.g. --env MY_TOKEN,OTHER)"}},async run({args:e}){if(He().kind!=="global")try{await hn()}catch(h){G(h)}let i=e.port?Number(e.port):void 0;if(i!==void 0&&(!Number.isInteger(i)||i<1||i>65535))G(new V(`Invalid --port value "${e.port}" \u2014 use a port number.`));let c=((Array.isArray(e.env)?e.env.join(","):e.env)??"").split(",").map((h)=>h.trim()).filter(Boolean),f=mn(process.env,xr(process.execPath),c),d=c.filter((h)=>!(h in f));if(d.length>0)G(new V(`--env ${d.join(", ")}: not set in this shell (or the value is not capturable).`));let u=await oe();if(await P()&&!u?.service)G(new V("A foreground server is running"+(u?.pid?` (pid ${u.pid})`:"")+".\n Stop it (Ctrl-C in its terminal), then rerun `moi service install`."));try{let h=await hn({port:i,extraEnv:c});if(console.log(`
164
- `+t.green("\u2713")+" Service installed "+t.dim(`(${process.platform==="darwin"?"launchd":"systemd user unit"})`)),console.log(" unit "+t.dim(X(h.unitPath))),h.logPath)console.log(" logs "+t.dim(X(h.logPath)));Ko(h.info),console.log(t.dim(`
162
+ `),process.exit(1)}function Yo(e){if(e){console.log(" server "+t.bold(`v${e.version}`)+` running on ${lt(e)}`+t.dim(` (pid ${e.pid})`));let n=Se(e.version);if(n)console.log(`
163
+ `+n)}else console.log(" "+t.yellow("server did not come up \u2014 check `moi service logs`")+t.dim(" (it may still be starting)"))}var Cr=a({meta:{name:"install",description:"Install and start the user service (launchd on macOS, systemd on Linux)"},args:{port:{type:"string",description:"HTTP port for the service server (default: 13337)"},env:{type:"string",description:"Extra env var names to capture from this shell, comma-separated (e.g. --env MY_TOKEN,OTHER)"}},async run({args:e}){if(Je().kind!=="global")try{await hn()}catch(h){G(h)}let i=e.port?Number(e.port):void 0;if(i!==void 0&&(!Number.isInteger(i)||i<1||i>65535))G(new V(`Invalid --port value "${e.port}" \u2014 use a port number.`));let c=((Array.isArray(e.env)?e.env.join(","):e.env)??"").split(",").map((h)=>h.trim()).filter(Boolean),f=mn(process.env,xr(process.execPath),c),d=c.filter((h)=>!(h in f));if(d.length>0)G(new V(`--env ${d.join(", ")}: not set in this shell (or the value is not capturable).`));let u=await oe();if(await P()&&!u?.service)G(new V("A foreground server is running"+(u?.pid?` (pid ${u.pid})`:"")+".\n Stop it (Ctrl-C in its terminal), then rerun `moi service install`."));try{let h=await hn({port:i,extraEnv:c});if(console.log(`
164
+ `+t.green("\u2713")+" Service installed "+t.dim(`(${process.platform==="darwin"?"launchd":"systemd user unit"})`)),console.log(" unit "+t.dim(X(h.unitPath))),h.logPath)console.log(" logs "+t.dim(X(h.logPath)));Yo(h.info),console.log(t.dim(`
165
165
  Starts on login, restarts on crash, survives reboots.`));for(let v of h.notes)console.log(t.yellow(" "+v));console.log()}catch(h){G(h)}}}),Rr=a({meta:{name:"uninstall",description:"Stop the service and remove its unit"},async run(){try{let{unitPath:e,existed:n}=await Ei();if(!n){console.log(`
166
166
  `+t.dim("\u25CB")+" Service is not installed "+t.dim(`(${X(e)})`)+`
167
167
  `);return}console.log(`
168
168
  `+t.green("\u2713")+" Service removed "+t.dim(`(${X(e)})`)+`
169
169
  `)}catch(e){G(e)}}}),Or=a({meta:{name:"restart",description:"Restart the service server"},async run(){try{let e=await ar();console.log(`
170
- `+t.green("\u2713")+" Service restarted"),Ko(e),console.log()}catch(e){G(e)}}}),Ar=a({meta:{name:"logs",description:"Show server logs (journalctl on Linux, log file on macOS)"},args:{lines:{type:"string",default:"80",description:"How many trailing lines to show"},follow:{type:"boolean",alias:"f",default:!1,description:"Keep following new output"}},async run({args:e}){let n=Math.max(1,Number(e.lines)||80);if(process.platform==="linux"){let c=["journalctl","--user","-u","moi.service","-n",String(n),"--no-pager"];if(e.follow)c.push("-f");let f=Bun.spawn(c,{stdin:"inherit",stdout:"inherit",stderr:"inherit"});process.exit(await f.exited)}let i=At();if(!Sr(i))console.log(`
170
+ `+t.green("\u2713")+" Service restarted"),Yo(e),console.log()}catch(e){G(e)}}}),Ar=a({meta:{name:"logs",description:"Show server logs (journalctl on Linux, log file on macOS)"},args:{lines:{type:"string",default:"80",description:"How many trailing lines to show"},follow:{type:"boolean",alias:"f",default:!1,description:"Keep following new output"}},async run({args:e}){let n=Math.max(1,Number(e.lines)||80);if(process.platform==="linux"){let c=["journalctl","--user","-u","moi.service","-n",String(n),"--no-pager"];if(e.follow)c.push("-f");let f=Bun.spawn(c,{stdin:"inherit",stdout:"inherit",stderr:"inherit"});process.exit(await f.exited)}let i=At();if(!Sr(i))console.log(`
171
171
  `+t.dim("\u25CB")+" No logs yet "+t.dim(`(${X(i)})`)+`
172
172
  `),process.exit(0);console.error(t.dim(X(i)));let l=Bun.spawn(["tail","-n",String(n),...e.follow?["-F"]:[],i],{stdin:"inherit",stdout:"inherit",stderr:"inherit"});process.exit(await l.exited)}});function X(e){let n=process.env.HOME;return n&&e.startsWith(n)?"~"+e.slice(n.length):e}async function Tr(){try{let e=await xi(),n=e.platform==="darwin"?"launchd user agent":"systemd user unit";if(console.log(`
173
173
  `+t.bold("moi service")+t.dim(` \u2014 ${n}`)),console.log(),!e.installed)console.log(" "+t.dim("\u25CB")+" Not installed"),console.log(t.dim(" Run `moi service install` to start Moi on login and keep it running.")),console.log(),process.exit(0);let i=e.runtime,l=i===null?t.dim("unknown"):i.state==="running"?t.green("\u25CF running")+(i.pid?t.dim(` (pid ${i.pid})`):""):i.state==="failed"?t.red("\u2717 failed")+t.dim(i.detail?` (${i.detail})`:""):i.state==="unavailable"?t.yellow("? unavailable")+t.dim(i.detail?` \u2014 ${i.detail}`:""):t.dim("\u25CB "+i.state);if(console.log(" state "+l),console.log(" unit "+t.dim(X(e.unitPath))),e.logPath)console.log(" logs "+t.dim(X(e.logPath))+t.dim(" (`moi service logs`)"));else console.log(" logs "+t.dim("journalctl --user -u moi.service (`moi service logs`)"));let c=await oe();if(c){if(console.log(" server "+t.bold(`v${c.version}`)+t.dim(` on ${lt(c)} (pid ${c.pid})`)),!c.service)console.log(t.yellow(" \u26A0 The running server is a foreground `moi start`, not the service."))}else if(i?.state==="running")console.log(" server "+t.yellow("unreachable on the control port"));if(console.log(),e.binMissing&&e.bin)console.log(t.yellow(` \u26A0 The service execs ${e.bin}, which no longer exists`)+t.dim(" (Moi moved or was reinstalled elsewhere).")+`
174
174
  `+t.dim(" Rerun `moi service install` to re-capture paths."));if(e.bunMissing)console.log(t.yellow(" \u26A0 No bun on the service PATH \u2014 the server cannot start.")+`
175
175
  `+t.dim(" Reinstall bun, then rerun `moi service install`."));if(e.linger==="disabled")console.log(t.yellow(" \u26A0 Lingering is off \u2014 the service stops when your last session ends.")+`
176
176
  `+t.dim(" Enable: loginctl enable-linger"));let f=c?Se(c.version):null;if(f)console.log(f.replace(/^/gm," ").replace(/^ {2}\u26A0/," \u26A0")+`
177
- `);process.exit(0)}catch(e){G(e)}}var Vo={install:Cr,uninstall:Rr,restart:Or,logs:Ar},Yo=a({meta:{name:"service",description:"Run Moi as a user service: `moi service install|uninstall|restart|logs`"},subCommands:Vo,async run({rawArgs:e}){let n=e.find((i)=>!i.startsWith("-"));if(n&&Object.hasOwn(Vo,n))return;await Tr()}});import{resolve as Zo}from"path";async function Ir(e){let{root:n,harness:i}=await Ne(e),l=await Dt(n,i),{changedSkills:c,updatedAppletTypes:f}=l,d=c.length>0?"Skills updated in ":"Skills unchanged in ";console.log(`
177
+ `);process.exit(0)}catch(e){G(e)}}var Ko={install:Cr,uninstall:Rr,restart:Or,logs:Ar},Go=a({meta:{name:"service",description:"Run Moi as a user service: `moi service install|uninstall|restart|logs`"},subCommands:Ko,async run({rawArgs:e}){let n=e.find((i)=>!i.startsWith("-"));if(n&&Object.hasOwn(Ko,n))return;await Tr()}});import{resolve as Qo}from"path";async function Ir(e){let{root:n,harness:i}=await Oe(e),l=await Dt(n,i),{changedSkills:c,updatedAppletTypes:f}=l,d=c.length>0?"Skills updated in ":"Skills unchanged in ";console.log(`
178
178
  `+t.green("\u2713")+" "+d+t.bold(n)+`
179
179
  `),Er(n,l);for(let u of f)console.log(t.dim(" Applet types regenerated: ")+t.bold(`.moi/${u}
180
180
  `))}function Er(e,{before:n,status:i,changedSkills:l,changedSkillPaths:c}){let f=new Set(c);console.log(R(["skill","path","from","to"].map((u)=>t.dim(u)),i.skills.map((u)=>{let g=n.find((b)=>b.name===u.name&&b.path===u.path)?.installed??null,h=g!==u.installed,v=f.has(u.path);return[u.name,It(e,u.path),g??t.dim("none"),h?t.green(u.installed??"?"):v?t.green((u.installed??"?")+" (files changed)"):t.dim((u.installed??"?")+" (no change)")]})));let d=l.length>0?` Reload changed skills before using them again: ${l.join(", ")}.`:" No skill files changed. Keep using the copies already in context.";console.log(`
181
181
  `+t.dim(d)+`
182
- `)}function Nr(e){if(Sn(e.installed,e.bundled))return t.yellow("update available");if(Ct(e.installed,e.bundled))return t.dim("patch behind");return t.green("up to date")}var Go=(e,n)=>a({meta:{name:e,description:n},args:{dir:S},async run({args:i}){await Ir(Zo(i.dir))}}),Xo={update:Go("update","Update this workspace\u2019s skills to the version shipped with the CLI"),install:Go("install","Alias for `moi skill update`")},Qo=a({meta:{name:"skill",description:"Show or update the workspace skills shipped with Moi"},subCommands:Xo,args:{dir:S},async run({args:e,rawArgs:n}){let i=n.find((d)=>!d.startsWith("-"));if(i&&i in Xo)return;let{root:l,harness:c}=await Ne(Zo(e.dir)),f=await ct(l,c);if(console.log(`
182
+ `)}function Nr(e){if(Sn(e.installed,e.bundled))return t.yellow("update available");if(Ct(e.installed,e.bundled))return t.dim("patch behind");return t.green("up to date")}var Xo=(e,n)=>a({meta:{name:e,description:n},args:{dir:S},async run({args:i}){await Ir(Qo(i.dir))}}),Zo={update:Xo("update","Update this workspace\u2019s skills to the version shipped with the CLI"),install:Xo("install","Alias for `moi skill update`")},et=a({meta:{name:"skill",description:"Show or update the workspace skills shipped with Moi"},subCommands:Zo,args:{dir:S},async run({args:e,rawArgs:n}){let i=n.find((d)=>!d.startsWith("-"));if(i&&i in Zo)return;let{root:l,harness:c}=await Oe(Qo(e.dir)),f=await ct(l,c);if(console.log(`
183
183
  `+t.bold("moi skill")+t.dim(" \u2014 workspace skills")+`
184
184
  `),console.log(R(["skill","path","installed","bundled","status"].map((d)=>t.dim(d)),f.map((d)=>[d.name,It(l,d.path),d.installed??t.dim("\u2014"),d.bundled??t.dim("\u2014"),Nr(d)]))),f.some((d)=>Ct(d.installed,d.bundled)))console.log(`
185
- `+t.dim(" Run ")+t.bold("moi skill update")+t.dim(" to refresh."));console.log()}});var et=a({meta:{name:"start",description:"Start the Moi web server"},args:{port:{type:"string",description:"HTTP port to listen on (default: 13337)"}},async run({args:e}){let n=H,i=process.argv.includes("--dev");if(i)ko();let l=process.argv.includes("--debug");if(!process.env.MOI_SERVER){if(await P()){let g=await oe();if(g?.service)console.log(`
185
+ `+t.dim(" Run ")+t.bold("moi skill update")+t.dim(" to refresh."));console.log()}});var tt=a({meta:{name:"start",description:"Start the Moi web server"},args:{port:{type:"string",description:"HTTP port to listen on (default: 13337)"}},async run({args:e}){let n=H,i=process.argv.includes("--dev");if(i)So();let l=process.argv.includes("--debug");if(!process.env.MOI_SERVER){if(await P()){let g=await oe();if(g?.service)console.log(`
186
186
  `+t.yellow("\u25C6")+" The Moi service is already running on "+lt(g)+t.dim(` (v${g.version})`)+`
187
187
  `+t.dim(" Manage it with `moi service` \u2014 restart, logs, uninstall.")+`
188
188
  `);else console.log(`
189
189
  `+t.yellow("\u25C6")+" Server is already running on "+lt(g)+`
190
- `);process.exit(0)}let f={...process.env,PUBLIC_TLDRAW_LICENSE_KEY:process.env.PUBLIC_TLDRAW_LICENSE_KEY??"",...e.port?{PORT:e.port}:{},...i?{MOI_DEV:"1"}:{},...l?{MOI_DEBUG:"1"}:{}};if(i){await So(n,f);return}let d=Oe(n,i),u=Y(d,f);process.exit(await lr(u,()=>Y(d,f)))}Ls();try{await import("./chunk-00rk365r.js")}catch(f){if(f?.code==="EADDRINUSE")console.error(`
190
+ `);process.exit(0)}let f={...process.env,PUBLIC_TLDRAW_LICENSE_KEY:process.env.PUBLIC_TLDRAW_LICENSE_KEY??"",...e.port?{PORT:e.port}:{},...i?{MOI_DEV:"1"}:{},...l?{MOI_DEBUG:"1"}:{}};if(i){await xo(n,f);return}let d=Ae(n,i),u=Y(d,f);process.exit(await lr(u,()=>Y(d,f)))}Ls();try{await import("./chunk-1ttazyr4.js")}catch(f){if(f?.code==="EADDRINUSE")console.error(`
191
191
  ${t.red("\u2717")} Port already in use (http :${w} / control :${W}) \u2014 `+"is another Moi server running?");else console.error(`
192
192
  ${t.red("\u2717")} Server failed to start: ${String(f)}`);if(process.env.MOI_SERVICE)console.error(t.dim(" The service stays idle \u2014 fix this, then `moi service restart`.\n")),process.exit(0);process.exit(1)}let{unixSocket:c}=p();console.log(`
193
193
  ${t.green("\u2713")} Server started on ${c??`http://localhost:${w}`}`),console.log(t.dim(` Press Ctrl+C to stop
194
- `))}});var tt=a({meta:{name:"status",description:"Show server status and registered workspaces"},async run(){let e=await we(),n=await te(process.cwd());if(e.status==="not-running")console.log(`
194
+ `))}});var nt=a({meta:{name:"status",description:"Show server status and registered workspaces"},async run(){let e=await De(),n=await te(process.cwd());if(e.status==="not-running")console.log(`
195
195
  `+t.dim("\u25CB")+" Server is "+t.bold("not running")),console.log(t.dim(` cli version ${C}`)+`
196
196
  `),process.exit(0);if(e.status==="unreachable")console.log(`
197
197
  `+t.yellow("\u25C6")+" Server is "+t.bold("unreachable")),console.log(t.dim(` control port ${ue}:${W} \u2014 ${e.reason}`)),console.log(t.dim(` cli version ${C}`)+`
198
198
  `),process.exit(1);let i=await oe();if(console.log(`
199
199
  `+t.green("\u25CF")+" Server is "+t.bold("running")+t.dim((i?.unixSocket?` (web socket: ${i.unixSocket}`:` (http port: ${i?.port||w}`)+`, control port: ${W}`+(i?.pid?`, pid: ${i.pid}`:"")+")")),i)console.log(t.dim(` server version ${i.version}`)+(i.service?t.dim(" \xB7 service-managed (`moi service`)"):""));console.log(t.dim(` cli version ${C}`));let l=i?Se(i.version):null;if(l)console.log(`
200
200
  `+l);if(await new Promise((c,f)=>{let d=new WebSocket(N);d.onopen=()=>d.send(JSON.stringify({type:"workspace:list"})),d.onmessage=(u)=>{let v=(JSON.parse(String(u.data)).workspaces??[]).length;console.log(t.dim(` ${v} workspace${v===1?"":"s"} registered
201
- `)),d.close(),c()},d.onerror=()=>void we().then((u)=>f(Error(qe(u))))}),n)console.log(t.yellow(n)+`
201
+ `)),d.close(),c()},d.onerror=()=>void De().then((u)=>f(Error(He(u))))}),n)console.log(t.yellow(n)+`
202
202
  `);process.exit(0)}});import{resolve as Wr}from"path";function jr(e){let n=Wr(e);j(n,{type:"tabs",path:n},(i)=>{let l=Array.isArray(i.tabs)?i.tabs:[];console.log(`
203
203
  `+t.bold("moi tabs")+t.dim(" \u2014 workspace tabs")+`
204
204
  `),console.log(R(["title","address"].map((c)=>t.dim(c)),l.map((c)=>[c.title,c.href]))),console.log(`
205
205
  `+t.dim(" Open one: moi navigate <address>")+`
206
- `)})}var rt=a({meta:{name:"tabs",description:"List workspace tabs and their navigation addresses"},args:{dir:S},run({args:e}){if(e._.length)console.error("moi tabs only lists tabs. Use moi navigate <address> to navigate."),process.exit(1);jr(e.dir)}});var Dr=(e,n)=>Math.round(e*(n=Math.pow(10,n)))/n,Lr=(e=4)=>(n)=>typeof n==="number"?Dr(n,e):n,at=Lr;var bc=at(2),Mr=(e)=>Math.max(0,Math.min(1,e||0)),Ge=(e)=>Math.round(Mr(e)*255),_r=Je("rgb"),kc=Je("hsl"),Ur=(e)=>{if(e===void 0)return;let n=Ge(e.r),i=Ge(e.g),l=Ge(e.b);return"#"+(16777216|n<<16|i<<8|l).toString(16).slice(1)};var Xe=(e)=>Ur(_r(e));import{resolve as Hr}from"path";function dt(e){let n=Number.parseInt(e.slice(1),16);return[n>>16&255,n>>8&255,n&255]}function mt(e,n){if(!process.stdout.isTTY||!e)return" ";let[i,l,c]=dt(e),[f,d,u]=dt(n??"#000000");return`\x1B[48;2;${i};${l};${c}m\x1B[38;2;${f};${d};${u}m Aa \x1B[0m`}function ft(e){if(!e)return mt();let n=ki(e);return mt(Xe(n.primary),Xe(n.primaryForeground))}var ht=a({meta:{name:"theme",description:"Show or set the workspace appearance"},args:{dir:{type:"positional",default:".",description:"Workspace directory (default: current)"},font:{type:"string",description:"Font theme key to apply"},color:{type:"string",description:"Color preset key to apply"},radius:{type:"string",description:"Radius preset key to apply"},agent:{type:"string",description:"Agent preset key to apply"}},async run({args:e}){let n=Hr(e.dir),i=await te(n),l=new WebSocket(N);l.onopen=()=>l.send(JSON.stringify({type:"theme",path:n,font:e.font??null,color:e.color??null,radius:e.radius??null,agent:e.agent??null})),l.onmessage=(c)=>{let f=JSON.parse(String(c.data));if(f.error)console.error(`
206
+ `)})}var rt=a({meta:{name:"tabs",description:"List workspace tabs and their navigation addresses"},args:{dir:S},run({args:e}){if(e._.length)console.error("moi tabs only lists tabs. Use moi navigate <address> to navigate."),process.exit(1);jr(e.dir)}});var Dr=(e,n)=>Math.round(e*(n=Math.pow(10,n)))/n,Lr=(e=4)=>(n)=>typeof n==="number"?Dr(n,e):n,at=Lr;var bc=at(2),Mr=(e)=>Math.max(0,Math.min(1,e||0)),Ye=(e)=>Math.round(Mr(e)*255),_r=Xe("rgb"),kc=Xe("hsl"),Ur=(e)=>{if(e===void 0)return;let n=Ye(e.r),i=Ye(e.g),l=Ye(e.b);return"#"+(16777216|n<<16|i<<8|l).toString(16).slice(1)};var Ze=(e)=>Ur(_r(e));import{resolve as Hr}from"path";function dt(e){let n=Number.parseInt(e.slice(1),16);return[n>>16&255,n>>8&255,n&255]}function mt(e,n){if(!process.stdout.isTTY||!e)return" ";let[i,l,c]=dt(e),[f,d,u]=dt(n??"#000000");return`\x1B[48;2;${i};${l};${c}m\x1B[38;2;${f};${d};${u}m Aa \x1B[0m`}function ft(e){if(!e)return mt();let n=ki(e);return mt(Ze(n.primary),Ze(n.primaryForeground))}var ht=a({meta:{name:"theme",description:"Show or set the workspace appearance"},args:{dir:{type:"positional",default:".",description:"Workspace directory (default: current)"},font:{type:"string",description:"Font theme key to apply"},color:{type:"string",description:"Color preset key to apply"},radius:{type:"string",description:"Radius preset key to apply"},agent:{type:"string",description:"Agent preset key to apply"}},async run({args:e}){let n=Hr(e.dir),i=await te(n),l=new WebSocket(N);l.onopen=()=>l.send(JSON.stringify({type:"theme",path:n,font:e.font??null,color:e.color??null,radius:e.radius??null,agent:e.agent??null})),l.onmessage=(c)=>{let f=JSON.parse(String(c.data));if(f.error)console.error(`
207
207
  `+t.red(t.bold("Error:"))+" "+f.error+`
208
208
  `),l.close(),process.exit(1);if(f.ok){if(console.log(),f.font){let y=le[f.font];console.log(t.green("\u2713")+" Font set to "+t.bold(y.label)+t.dim(` (${y.sans} / ${y.mono})`))}if(f.color){let y=ce[f.color],A=ft(y.primary);console.log(t.green("\u2713")+" Color set to "+t.bold(y.label)+" "+A)}if(f.radius){let y=Ee[f.radius];console.log(t.green("\u2713")+" Radius set to "+t.bold(y.label))}if(f.agent){let y=xe[f.agent];console.log(t.green("\u2713")+" Agent set to "+t.bold(y.label))}if(console.log(),i)console.log(t.yellow(i)+`
209
- `);l.close(),process.exit(0)}let d=f.currentFont??De.font,u=f.currentColor??De.color,g=f.currentRadius??De.radius,h=f.currentAgent??De.agent;console.log(`
209
+ `);l.close(),process.exit(0)}let d=f.currentFont??Ne.font,u=f.currentColor??Ne.color,g=f.currentRadius??Ne.radius,h=f.currentAgent??Ne.agent;console.log(`
210
210
  `+t.bold("moi theme")+" \u2014 workspace appearance"),console.log(t.dim(" Usage: moi theme --font=<key> --color=<key> --radius=<key> --agent=<key>")+`
211
211
  `);let v=Object.keys(le).map((y)=>{let A=le[y],E=y===d;return[E?t.green("\u2192"):" ",E?t.bold(y):y,A.label,t.dim(A.sans),t.dim(A.mono)]});console.log(t.dim(" Fonts")),console.log(R(["","key","label","sans","mono"].map((y)=>t.dim(y)),v)+`
212
212
  `);let b=Object.keys(ce).map((y)=>{let A=ce[y],E=y===u;return[E?t.green("\u2192"):" ",E?t.bold(y):y,A.label,ft(A.primary)]});console.log(t.dim(" Colors")),console.log(R(["","key","label","swatch"].map((y)=>t.dim(y)),b)+`
213
213
  `);let x=Object.keys(Ee).map((y)=>{let A=Ee[y],E=y===g;return[E?t.green("\u2192"):" ",E?t.bold(y):y,A.label,t.dim(A.radius)]});console.log(t.dim(" Radius")),console.log(R(["","key","label","value"].map((y)=>t.dim(y)),x)+`
214
214
  `);let k=Object.keys(xe).map((y)=>{let A=xe[y],E=y===h;return[E?t.green("\u2192"):" ",E?t.bold(y):y,A.label]});if(console.log(t.dim(" Agent")),console.log(R(["","key","label"].map((y)=>t.dim(y)),k)+`
215
215
  `),i)console.log(t.yellow(i)+`
216
- `);l.close(),process.exit(0)},l.onerror=()=>void _()}});var wt=a({meta:{name:"ui-components",description:"UI components for applets"},subCommands:()=>import("./chunk-gbkjshyt.js").then((e)=>e.uiComponentsSubCommands),async run({rawArgs:e}){let{runUiComponentsCatalog:n}=await import("./chunk-gbkjshyt.js");await n(e)}});var kt=a({meta:{name:"update",description:"Update Moi to the latest published version"},args:{check:{type:"boolean",default:!1,description:"Only check the registry, change nothing. Exit 0: up to date (or nothing to update), 1: update available, 2: check failed."}},async run({args:e}){let n=He();if(n.kind==="checkout")console.log(`
216
+ `);l.close(),process.exit(0)},l.onerror=()=>void _()}});var wt=a({meta:{name:"ui-components",description:"UI components for applets"},subCommands:()=>import("./chunk-yr67rvnq.js").then((e)=>e.uiComponentsSubCommands),async run({rawArgs:e}){let{runUiComponentsCatalog:n}=await import("./chunk-yr67rvnq.js");await n(e)}});var kt=a({meta:{name:"update",description:"Update Moi to the latest published version"},args:{check:{type:"boolean",default:!1,description:"Only check the registry, change nothing. Exit 0: up to date (or nothing to update), 1: update available, 2: check failed."}},async run({args:e}){let n=Je();if(n.kind==="checkout")console.log(`
217
217
  `+t.yellow("\u25C6")+` This Moi runs from a source tree (${n.reason}) \u2014 update it with git instead.
218
218
  `),process.exit(0);if(console.log(`
219
219
  `+t.bold("moi update")+t.dim(` \u2014 installed v${C}`)),tr(C))console.log(`
@@ -238,9 +238,9 @@ ${t.green("\u2713")} Server started on ${c??`http://localhost:${w}`}`),console.l
238
238
  `+t.red(t.bold("Error:"))+" "+c.error+`
239
239
  `),i.close(),process.exit(1);console.log(`
240
240
  `+t.green("\u2713")+" View updated "+t.bold(String(c.viewId??e.id))+`
241
- `),i.close(),process.exit(0)},i.onerror=()=>void _()}}),zr=a({meta:{name:"create",description:"Create a view, optionally forking a source chat to build it"},args:{dir:{type:"positional",default:".",description:"Workspace directory"},"from-session":{type:"string",description:"Session id to fork into a new view chat"},requirements:{type:"string",required:!0,description:"Complete view requirements"}},run({args:e}){let n=new WebSocket(N);n.onopen=()=>n.send(JSON.stringify({type:"view:create",path:$t(e.dir),fromSessionId:e["from-session"],requirements:e.requirements})),n.onmessage=(i)=>{let l=JSON.parse(String(i.data));if(console.log(JSON.stringify(l,null,2)),l.warning)console.error(l.warning);n.close(),process.exit(l.error?1:0)},n.onerror=()=>void _()}}),Rt=a({meta:{name:"views",description:"Create views and set their build details"},subCommands:{create:zr,set:qr}});import{resolve as Fr}from"path";function Z(e,n,i=[]){let l=n.run;return{...n,...n.subCommands?{subCommands:async()=>{let c=typeof n.subCommands==="function"?await n.subCommands():await n.subCommands,f={};for(let[d,u]of Object.entries(c??{})){let g=typeof u==="function"?await u():await u;f[d]=Z(e,g,[...i,d])}return f}}:{},async run(c){if(n.subCommands&&c.args._.length)return l?.(c);let f=c.args,d=Fr(typeof f.dir==="string"?f.dir:process.cwd()),u=typeof n.args==="function"?await n.args():await n.args,g=Object.entries(u??{}).filter(([,b])=>b.type==="positional").findIndex(([b])=>b==="dir"),h=0,v=[];for(let b=0;b<c.rawArgs.length;b++){let x=c.rawArgs[b];if(x==="--dir"){b++;continue}if(x.startsWith("--dir="))continue;if(x.startsWith("-")&&x!=="-"){v.push(x);let k=x.replace(/^--?/,"").split("=")[0];if(!x.includes("=")&&u?.[k]?.type==="string"&&c.rawArgs[b+1]!==void 0)v.push(c.rawArgs[++b])}else if(h++!==g)v.push(x)}try{if(await To(e,[...i,...v],d)){if(e==="bundle"&&!process.exitCode)await no({type:"views:reconcile",path:d});return}}catch(b){console.error(b instanceof Error?b.message:"Remote command failed"),process.exitCode=1;return}return l?.(c)}}}var Ze={bundle:Z("bundle",ro),check:Z("check",so),refresh:Oo,views:Rt,"call-server-fn":Z("call-server-fn",io),debug:Z("debug",co),theme:Z("theme",ht),config:lo,env:po,scratch:Bo,skill:Qo,tabs:rt,navigate:$o,remote:Wo,"ui-components":Z("ui-components",wt)},Ce={init:Co,start:et,status:tt,service:Yo,update:kt,openclaw:Ro,hermes:fo,version:St},Jr=a({meta:()=>({name:"moi",description:"Moi \u2014 local AI workspace",version:rr()}),subCommands:{...Ze,...Ce}});function Br(){let e=process.argv[2];if(!e||e==="version"||e==="start")return;if(!(e in Ce))return;if(!vt())return;let n=p();if(!n.demo)return;console.log(`
241
+ `),i.close(),process.exit(0)},i.onerror=()=>void _()}}),zr=a({meta:{name:"create",description:"Create a view, optionally forking a source chat to build it"},args:{dir:{type:"positional",default:".",description:"Workspace directory"},"from-session":{type:"string",description:"Session id to fork into a new view chat"},requirements:{type:"string",required:!0,description:"Complete view requirements"}},run({args:e}){let n=new WebSocket(N);n.onopen=()=>n.send(JSON.stringify({type:"view:create",path:$t(e.dir),fromSessionId:e["from-session"],requirements:e.requirements})),n.onmessage=(i)=>{let l=JSON.parse(String(i.data));if(console.log(JSON.stringify(l,null,2)),l.warning)console.error(l.warning);n.close(),process.exit(l.error?1:0)},n.onerror=()=>void _()}}),Rt=a({meta:{name:"views",description:"Create views and set their build details"},subCommands:{create:zr,set:qr}});import{resolve as Fr}from"path";function Z(e,n,i=[]){let l=n.run;return{...n,...n.subCommands?{subCommands:async()=>{let c=typeof n.subCommands==="function"?await n.subCommands():await n.subCommands,f={};for(let[d,u]of Object.entries(c??{})){let g=typeof u==="function"?await u():await u;f[d]=Z(e,g,[...i,d])}return f}}:{},async run(c){if(n.subCommands&&c.args._.length)return l?.(c);let f=c.args,d=Fr(typeof f.dir==="string"?f.dir:process.cwd()),u=typeof n.args==="function"?await n.args():await n.args,g=Object.entries(u??{}).filter(([,b])=>b.type==="positional").findIndex(([b])=>b==="dir"),h=0,v=[];for(let b=0;b<c.rawArgs.length;b++){let x=c.rawArgs[b];if(x==="--dir"){b++;continue}if(x.startsWith("--dir="))continue;if(x.startsWith("-")&&x!=="-"){v.push(x);let k=x.replace(/^--?/,"").split("=")[0];if(!x.includes("=")&&u?.[k]?.type==="string"&&c.rawArgs[b+1]!==void 0)v.push(c.rawArgs[++b])}else if(h++!==g)v.push(x)}try{if(await Io(e,[...i,...v],d)){if(e==="bundle"&&!process.exitCode)await ro({type:"views:reconcile",path:d});return}}catch(b){console.error(b instanceof Error?b.message:"Remote command failed"),process.exitCode=1;return}return l?.(c)}}}var Qe={bundle:Z("bundle",io),check:Z("check",ao),refresh:Ao,views:Rt,"call-server-fn":Z("call-server-fn",so),debug:Z("debug",mo),theme:Z("theme",ht),config:co,env:fo,scratch:Vo,skill:et,tabs:rt,navigate:Ro,remote:jo,"ui-components":Z("ui-components",wt)},Ce={init:$o,start:tt,status:nt,service:Go,update:kt,openclaw:Oo,hermes:uo,version:St},Jr=a({meta:()=>({name:"moi",description:"Moi \u2014 local AI workspace",version:rr()}),subCommands:{...Qe,...Ce}});function Br(){let e=process.argv[2];if(!e||e==="version"||e==="start")return;if(!(e in Ce))return;if(!vt())return;let n=p();if(!n.demo)return;console.log(`
242
242
  `+t.yellow("\u25C6")+` moi ${e} is not available in the demo.
243
243
  `+t.dim(" Get Moi on your computer: ")+t.bold(n.demoInstallUrl)+`
244
244
  `),process.exit(1)}function Vr(){let e=process.argv[2];if(!e||e==="version"||e==="status")return;if(!(e in Ce))return;if(vt())return;console.log(`
245
245
  `+t.yellow("\u25C6")+` moi ${e} is only available to the user that runs moi.
246
- `),process.exit(1)}Vr();Br();async function Kr(e){return(typeof e.meta==="function"?await e.meta():await e.meta)?.description??""}async function Yr(){let e=Math.max(...Object.keys({...Ze,...Ce}).map((i)=>i.length))+4,n=async(i,l)=>" "+t.cyan(i.padEnd(e))+t.dim(await Kr(l));console.log(),console.log(t.bold("Moi")+t.dim(" \u2014 local AI workspace ")+t.dim(`v${rr()}`)),console.log(),console.log(t.dim("USAGE ")+"moi <command> [options]"),console.log(),console.log(t.bold("Workspace commands:")+t.dim(" for agents and humans alike")),console.log();for(let[i,l]of Object.entries(Ze))console.log(await n(i,l));if(console.log(),!Qe()){console.log(t.bold("System commands:")+t.dim(" manage Moi itself (server, service, updates)")),console.log(t.yellow(" AGENTS: do not run these unless explicitly asked!")),console.log();for(let[i,l]of Object.entries(Ce))console.log(await n(i,l));console.log()}console.log(t.dim("Use moi <command> --help for more information about a command.")),console.log()}hi(Jr,{async showUsage(e,n){let i=typeof e.meta==="function"?await e.meta():await e.meta;if(i?.name==="moi"){await Yr();return}if(i?.name==="config"){Ue();return}await cn(e,n)}});
246
+ `),process.exit(1)}Vr();Br();async function Kr(e){return(typeof e.meta==="function"?await e.meta():await e.meta)?.description??""}async function Yr(){let e=Math.max(...Object.keys({...Qe,...Ce}).map((i)=>i.length))+4,n=async(i,l)=>" "+t.cyan(i.padEnd(e))+t.dim(await Kr(l));console.log(),console.log(t.bold("Moi")+t.dim(" \u2014 local AI workspace ")+t.dim(`v${rr()}`)),console.log(),console.log(t.dim("USAGE ")+"moi <command> [options]"),console.log(),console.log(t.bold("Workspace commands:")+t.dim(" for agents and humans alike")),console.log();for(let[i,l]of Object.entries(Qe))console.log(await n(i,l));if(console.log(),!eo()){console.log(t.bold("System commands:")+t.dim(" manage Moi itself (server, service, updates)")),console.log(t.yellow(" AGENTS: do not run these unless explicitly asked!")),console.log();for(let[i,l]of Object.entries(Ce))console.log(await n(i,l));console.log()}console.log(t.dim("Use moi <command> --help for more information about a command.")),console.log()}hi(Jr,{async showUsage(e,n){let i=typeof e.meta==="function"?await e.meta():await e.meta;if(i?.name==="moi"){await Yr();return}if(i?.name==="config"){qe();return}await cn(e,n)}});
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Nt}from"./chunk-k049dtaq.js";import{ut}from"./chunk-4wj1jzhr.js";import{join as u,resolve as d,sep as m}from"path";var l=process.env.MEI_FUNCTIONS_DIR??u(import.meta.dir,"..","..","test-workspace",".moi");if(process.env.MEI_WORKSPACE_ROOT)try{process.chdir(process.env.MEI_WORKSPACE_ROOT)}catch{}var n=new Map;function r(e){try{process.send(e)}catch{}}async function y(e){let s=n.get(e);if(s)return s;let o=u(l,`${e}.server.ts`);if(!d(o).startsWith(d(l)+m))throw Error(`Server module "${e}" not found`);let t=Bun.file(o);if(!await t.exists())throw Error(`Server module "${e}" not found`);let i=await import(o+`?t=${t.lastModified}`);return n.set(e,i),r({type:"loaded",module:e}),i}async function p(e){let s=n.get(e);if(!s)return;if(typeof s.dispose==="function")try{await s.dispose()}catch(o){console.error(`[mei] dispose error in ${e}.server.ts:`,o)}n.delete(e)}process.on("message",async(e)=>{if(e.type==="reload"){for(let s of e.modules)await p(s);return}if(e.type==="shutdown"){for(let s of[...n.keys()])await p(s);process.exit(0)}if(e.type==="call"){let{id:s,module:o,name:t,args:i}=e;if(!s||!o||!t){r({id:s,type:"error",message:"Malformed call message"});return}try{let a=(await y(o))[t];if(typeof a!=="function")throw Error(`"${t}" in ${o}.server.ts is not a function`);let f=ut(i),g=await a(...f);r({id:s,type:"result",data:Nt(g)})}catch(c){let a=c instanceof Error?c.message:"Unknown error";r({id:s,type:"error",message:a})}}});r({type:"ready"});
2
+ import{Nt}from"./chunk-jrkbyrmq.js";import{ut}from"./chunk-jcjcz9ae.js";import{join as u,resolve as d,sep as m}from"path";var l=process.env.MEI_FUNCTIONS_DIR??u(import.meta.dir,"..","..","test-workspace",".moi");if(process.env.MEI_WORKSPACE_ROOT)try{process.chdir(process.env.MEI_WORKSPACE_ROOT)}catch{}var n=new Map;function r(e){try{process.send(e)}catch{}}async function y(e){let s=n.get(e);if(s)return s;let o=u(l,`${e}.server.ts`);if(!d(o).startsWith(d(l)+m))throw Error(`Server module "${e}" not found`);let t=Bun.file(o);if(!await t.exists())throw Error(`Server module "${e}" not found`);let i=await import(o+`?t=${t.lastModified}`);return n.set(e,i),r({type:"loaded",module:e}),i}async function p(e){let s=n.get(e);if(!s)return;if(typeof s.dispose==="function")try{await s.dispose()}catch(o){console.error(`[mei] dispose error in ${e}.server.ts:`,o)}n.delete(e)}process.on("message",async(e)=>{if(e.type==="reload"){for(let s of e.modules)await p(s);return}if(e.type==="shutdown"){for(let s of[...n.keys()])await p(s);process.exit(0)}if(e.type==="call"){let{id:s,module:o,name:t,args:i}=e;if(!s||!o||!t){r({id:s,type:"error",message:"Malformed call message"});return}try{let a=(await y(o))[t];if(typeof a!=="function")throw Error(`"${t}" in ${o}.server.ts is not a function`);let f=ut(i),g=await a(...f);r({id:s,type:"result",data:Nt(g)})}catch(c){let a=c instanceof Error?c.message:"Unknown error";r({id:s,type:"error",message:a})}}});r({type:"ready"});