@fugood/buttress-server 2.26.0-beta.22 → 2.26.0-beta.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1162,9 +1162,11 @@ decision_assistance = true # opt-in tool prefilter (default false)
1162
1162
  - `devices_scan`: the same UDP + HTTP LAN discovery as `bricks devtools scan`,
1163
1163
  including project previews found relative to the Buttress config directory.
1164
1164
  - `devtools`: one action-based tool for screenshots (inline images), brick tree/query,
1165
- tap/key/text input, console capture, JavaScript evaluation, storage overview, and
1166
- raw CDP requests for other supported operations. Reuses the CLI CDP transport and
1167
- shared DevTools operations; no CLI subprocess or separate tool per device/action.
1165
+ tap/key/text input, a press by brick id, the open app modals and one operation on the topmost
1166
+ one (app version >= 2.26; a generator confirm dialog is only dismissed), console capture,
1167
+ JavaScript evaluation, storage overview, and raw CDP requests for other supported operations.
1168
+ Reuses the CLI CDP transport and shared DevTools operations; no CLI subprocess or separate tool
1169
+ per device/action.
1168
1170
 
1169
1171
  For example, scan with `{}` then call `devtools` with
1170
1172
  `{ "action": "tree", "address": "192.168.1.42", "port": 19851 }`.
@@ -102,7 +102,7 @@ SOURCE: /[\s\S]+/
102
102
  `),Ne=e=>typeof e==`string`?e:JSON.stringify(e)??String(e);function Pe(e,t){if(!e)return structuredClone(t);for(let n of[`input`,`output`,`cacheRead`,`cacheWrite`,`totalTokens`])e[n]=(e[n]??0)+(t[n]??0);if(t.cost){e.cost??={};for(let[n,r]of Object.entries(t.cost))e.cost[n]=(e.cost[n]??0)+(r??0)}return e}function Fe(e){return e.length===0?`No tool calls were made.`:`Tool calls made before the failure (they are not undone): ${e.map(e=>`${e.name} (${e.status})`).join(`, `)}`}function Ie(e,t){return`${e.kind===`script`?e.stack??`${e.name??`Error`}: ${e.message}`:e.kind===`timeout`?`Script timed out: ${e.message}`:e.kind===`aborted`?`Script aborted: ${e.message}`:`Script sandbox failed: ${e.message}`}\n\n${Fe(t)}`}function Le(e,t){let n=Math.floor(t/2),r=t-n,i=e.length-n-r;return`${e.slice(0,n)}…${Math.ceil(i/4)} tokens truncated…${r>0?e.slice(-r):``}`}function Re(e,t){let n=Array.from({length:e.length}),r=e.map((e,t)=>({length:e,index:t})).sort((e,t)=>e.length-t.length),i=t;return r.forEach(({length:e,index:t},a)=>{n[t]=Math.min(e,Math.floor(i/(r.length-a))),i-=n[t]}),n}async function ze(e,t,n){let r=e.filter(e=>e.type===`text`).map(e=>e.text),i=r.join(`
103
103
  `),a=t*4;if(r.length===0||i.length<=a)return{items:e};let o=Re(r.map(e=>e.length),a),s=r.every((e,t)=>e.length<=o[t]||o[t]>=400)?r.map((e,t)=>e.length>o[t]?Le(e,o[t]):e).join(`
104
104
  `):Le(i,a),c=`Warning: truncated output (original token count: ${Math.ceil(i.length/4)})\nTotal output lines: ${i.split(`
105
- `).length}\n\n${s}`,l;if(n)try{l=await n(i),l&&(c+=`\n\n[Full output: ${l} (read with offset/limit)]`)}catch(e){c+=`\n\n[Could not save the full output: ${e?.message||e}]`}return{items:[{type:`text`,text:c},...e.filter(e=>e.type===`image`)],...l?{fullOutputPath:l}:{}}}function Be(e,t){let{result:n}=t;if(e.outputSchema&&n.structuredContent!==void 0)return n.structuredContent;let r=Me(n);if(t.isError)throw Error(r||`Tool "${e.name}" failed`);return r}function Ve(e,t){let n=a(e),r=a(t),i=e=>e.includes(`__`)?e.slice(e.lastIndexOf(`__`)+2):void 0;return e===t||n===r||i(e)===t||i(n)===r}function He(e,t,n){let r=he(e,{getNamespace:n}),i=e=>({name:a(e.name),description:t.get(e.name)??``}),o=t=>e.map(n).find(e=>e&&Ve(e.name,t));return[{name:`searchTools`,spread:!0,execute:([e,t])=>{if(typeof e!=`string`)throw Error(`searchTools() expects a query string`);let n=t?.limit??8;if(typeof n!=`number`||!Number.isInteger(n)||n<=0)throw Error(`searchTools() limit must be a positive integer`);let a=t?.namespace;if(a!=null&&typeof a!=`string`)throw Error(`searchTools() namespace must be a string`);let s=a?o(a):void 0;return a&&!s?[]:_e(r,e,n,{namespace:s?.name,maxLimit:Math.max(n,8)}).map(i)}},{name:`describeTool`,spread:!0,execute:([n])=>{if(typeof n!=`string`)throw Error(`describeTool() expects a tool name`);let r=e.find(e=>e.name===n||a(e.name)===n);return r?t.get(r.name):void 0}},{name:`describeNamespace`,spread:!0,execute:([t])=>{if(typeof t!=`string`)throw Error(`describeNamespace() expects a namespace name`);let r=o(t);if(r)return{name:r.name,...r.description?{description:r.description}:{},...r.instructions?{instructions:r.instructions}:{},tools:e.filter(e=>n(e)?.name===r.name).map(e=>a(e.name))}}}]}async function Ue({toolCallId:e,code:t,signal:n,onUpdate:r,tools:i,executeTool:a,store:o={},models:s,getNamespace:l=()=>void 0,sandbox:u={},spillOutput:d}){let f=performance.now(),p;try{p=de(t)}catch(e){if(!(e instanceof P))throw e;return{content:[{type:`text`,text:`Script failed\nScript error:\n${e.message}`}],details:{calls:[]},isError:!0}}let{code:m,options:h}=p,g=[],_=0,v,y=0,b=()=>g.slice(-200).map(e=>({...e})),x=()=>r?.({content:[],details:{calls:b()}}),S=e=>(g.push(e),e),C=new Map(i.map(e=>[e.name,c(ee(e))])),w=i.map(t=>({name:t.name,description:C.get(t.name),execute:async(n,{signal:r})=>{let i=S({id:`${e}/${++_}`,name:t.name,args:je(n),status:`running`});x();let o=performance.now(),s=await a(t,n,{id:i.id,parentToolCallId:e,signal:r});return i.durationMs=performance.now()-o,s.isError?(i.status=r.aborted?`cancelled`:`error`,i.error=Ae(Me(s.result)||`Tool "${t.name}" failed`,500)):i.status=`ok`,x(),Be(t,s)}})),T=Math.min(h.timeoutMs??u.defaultTimeoutMs??1/0,u.maxTimeoutMs??1/0),E=new oe({tools:w,globals:[...He(i,C,l),...s?Ee(s,{toolCallId:e,track:S,publish:x,addUsage:e=>{v=Pe(v,e)},addGeneratedImages:e=>{y+=e}}):[]],timeoutMs:T,memoryLimitBytes:u.memoryLimitBytes??268435456,...u.wasmPath?{wasm:te(u.wasmPath)}:{},...u.workerUrl?{workerUrl:u.workerUrl}:{}}),ne=u.limit??(e=>e()),D;try{D=await ne(()=>E.execute(m,{signal:n,store:o}))}finally{await E.close()}for(let e of g)e.status===`running`&&(e.status=`cancelled`);let O=D.output.map(e=>e.type===`text`?{type:`text`,text:e.text}:e);D.ok?D.value!==void 0&&O.push({type:`text`,text:Ne(D.value)}):O.push({type:`text`,text:`Script error:\n${Ie(D.error,g)}`}),y>0&&!O.some(e=>e.type===`image`)&&O.push({type:`text`,text:`Note: models.generateImages() returned ${y} image${y===1?``:`s`} that the script did not show. Show each image block of result.output with image(block).`});let k=await ze(O,h.maxOutputTokens??1e4,d),A=((performance.now()-f)/1e3).toFixed(1),j=`${D.ok?`Script completed`:`Script failed`}\nWall time ${A} seconds\nOutput:\n`,M=D.ok?D.storeWrites:null,re=M&&(Object.keys(M.set).length>0||M.delete.length>0);return{content:[{type:`text`,text:j},...k.items],details:{calls:b(),...g.length>200?{omittedCalls:g.length-200}:{},...re?{storeWrites:M}:{},...k.fullOutputPath?{fullOutputPath:k.fullOutputPath}:{}},...v?{usage:v}:{},...D.ok?{}:{isError:!0}}}const H=`codemode`,U=`codemodeStore`,W=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function We(e,t){if(!(!W(t)||!W(t.set)||!Array.isArray(t.delete))){for(let n of t.delete)delete e[n];Object.assign(e,t.set)}}function Ge(e){let t=Object.create(null);for(let n of Array.isArray(e)?e:[]){if(W(n?.codemodeStore)){for(let e of Object.keys(t))delete t[e];Object.assign(t,n[U])}n?.role===`toolResult`&&n.toolName===`codemode`&&We(t,n.details?.storeWrites)}return t}function Ke(e,t){let n=Ge(t);Object.keys(n).length>0&&(e[U]=n)}var qe=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function G(e){}function Je(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=G,onError:n=G,onRetry:r=G,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Ye(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1;f(n,e.slice(t+r),e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
105
+ `).length}\n\n${s}`,l;if(n)try{l=await n(i),l&&(c+=`\n\n[Full output: ${l} (read with offset/limit)]`)}catch(e){c+=`\n\n[Could not save the full output: ${e?.message||e}]`}return{items:[{type:`text`,text:c},...e.filter(e=>e.type===`image`)],...l?{fullOutputPath:l}:{}}}function Be(e,t){let{result:n}=t;if(e.outputSchema&&n.structuredContent!==void 0)return n.structuredContent;let r=Me(n);if(t.isError)throw Error(r||`Tool "${e.name}" failed`);return r}function Ve(e,t){let n=a(e),r=a(t),i=e=>e.includes(`__`)?e.slice(e.lastIndexOf(`__`)+2):void 0;return e===t||n===r||i(e)===t||i(n)===r}function He(e,t,n){let r=he(e,{getNamespace:n}),i=e=>({name:a(e.name),description:t.get(e.name)??``}),o=t=>e.map(n).find(e=>e&&Ve(e.name,t));return[{name:`searchTools`,spread:!0,execute:([e,t])=>{if(typeof e!=`string`)throw Error(`searchTools() expects a query string`);let n=t?.limit??8;if(typeof n!=`number`||!Number.isInteger(n)||n<=0)throw Error(`searchTools() limit must be a positive integer`);let a=t?.namespace;if(a!=null&&typeof a!=`string`)throw Error(`searchTools() namespace must be a string`);let s=a?o(a):void 0;return a&&!s?[]:_e(r,e,n,{namespace:s?.name,maxLimit:Math.max(n,8)}).map(i)}},{name:`describeTool`,spread:!0,execute:([n])=>{if(typeof n!=`string`)throw Error(`describeTool() expects a tool name`);let r=e.find(e=>e.name===n||a(e.name)===n);return r?t.get(r.name):void 0}},{name:`describeNamespace`,spread:!0,execute:([t])=>{if(typeof t!=`string`)throw Error(`describeNamespace() expects a namespace name`);let r=o(t);if(r)return{name:r.name,...r.description?{description:r.description}:{},...r.instructions?{instructions:r.instructions}:{},tools:e.filter(e=>n(e)?.name===r.name).map(e=>a(e.name))}}}]}async function Ue({toolCallId:e,code:t,signal:n,onUpdate:r,tools:i,executeTool:a,store:o={},models:s,getNamespace:l=()=>void 0,sandbox:u={},spillOutput:d}){let f=performance.now(),p;try{p=de(t)}catch(e){if(!(e instanceof P))throw e;return{content:[{type:`text`,text:`Script failed\nScript error:\n${e.message}`}],details:{calls:[]},isError:!0}}let{code:m,options:h}=p,g=[],_=0,v,y=0,b=()=>g.slice(-200).map(e=>({...e})),x=()=>r?.({content:[],details:{calls:b()}}),S=e=>(g.push(e),e),C=new Map(i.map(e=>[e.name,c(ee(e))])),w=i.map(t=>({name:t.name,description:C.get(t.name),execute:async(n={},{signal:r})=>{let i=S({id:`${e}/${++_}`,name:t.name,args:je(n),status:`running`});x();let o=performance.now(),s=await a(t,n,{id:i.id,parentToolCallId:e,signal:r});return i.durationMs=performance.now()-o,s.isError?(i.status=r.aborted?`cancelled`:`error`,i.error=Ae(Me(s.result)||`Tool "${t.name}" failed`,500)):i.status=`ok`,x(),Be(t,s)}})),T=Math.min(h.timeoutMs??u.defaultTimeoutMs??1/0,u.maxTimeoutMs??1/0),E=new oe({tools:w,globals:[...He(i,C,l),...s?Ee(s,{toolCallId:e,track:S,publish:x,addUsage:e=>{v=Pe(v,e)},addGeneratedImages:e=>{y+=e}}):[]],timeoutMs:T,memoryLimitBytes:u.memoryLimitBytes??268435456,...u.wasmPath?{wasm:te(u.wasmPath)}:{},...u.workerUrl?{workerUrl:u.workerUrl}:{}}),ne=u.limit??(e=>e()),D;try{D=await ne(()=>E.execute(m,{signal:n,store:o}))}finally{await E.close()}for(let e of g)e.status===`running`&&(e.status=`cancelled`);let O=D.output.map(e=>e.type===`text`?{type:`text`,text:e.text}:e);D.ok?D.value!==void 0&&O.push({type:`text`,text:Ne(D.value)}):O.push({type:`text`,text:`Script error:\n${Ie(D.error,g)}`}),y>0&&!O.some(e=>e.type===`image`)&&O.push({type:`text`,text:`Note: models.generateImages() returned ${y} image${y===1?``:`s`} that the script did not show. Show each image block of result.output with image(block).`});let k=await ze(O,h.maxOutputTokens??1e4,d),A=((performance.now()-f)/1e3).toFixed(1),j=`${D.ok?`Script completed`:`Script failed`}\nWall time ${A} seconds\nOutput:\n`,M=D.ok?D.storeWrites:null,re=M&&(Object.keys(M.set).length>0||M.delete.length>0);return{content:[{type:`text`,text:j},...k.items],details:{calls:b(),...g.length>200?{omittedCalls:g.length-200}:{},...re?{storeWrites:M}:{},...k.fullOutputPath?{fullOutputPath:k.fullOutputPath}:{}},...v?{usage:v}:{},...D.ok?{}:{isError:!0}}}const H=`codemode`,U=`codemodeStore`,W=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function We(e,t){if(!(!W(t)||!W(t.set)||!Array.isArray(t.delete))){for(let n of t.delete)delete e[n];Object.assign(e,t.set)}}function Ge(e){let t=Object.create(null);for(let n of Array.isArray(e)?e:[]){if(W(n?.codemodeStore)){for(let e of Object.keys(t))delete t[e];Object.assign(t,n[U])}n?.role===`toolResult`&&n.toolName===`codemode`&&We(t,n.details?.storeWrites)}return t}function Ke(e,t){let n=Ge(t);Object.keys(n).length>0&&(e[U]=n)}var qe=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function G(e){}function Je(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=G,onError:n=G,onRetry:r=G,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Ye(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1;f(n,e.slice(t+r),e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
106
106
  `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new qe(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new qe(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
107
107
  `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Ye(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
108
108
  `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as e,i as t,n,o as r,r as i}from"./net-tWFM4EP8.mjs";import{a,c as o,n as s}from"./config-DiYweJ2m.mjs";import{n as c,r as l}from"./client-qqI-HCOj.mjs";import u from"node:fs/promises";import d from"node:path";import f from"node:fs";import{execFile as p,spawn as m}from"node:child_process";import h from"node-machine-id";import g from"@iarna/toml";import{promisify as _}from"node:util";const v=_(p),y=e=>e?.code===`ENOENT`,b=async e=>{try{return await u.stat(e)}catch(e){if(y(e))return null;throw e}},x=e=>{if(!e)return{};try{let{env:t}=g.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}},S=e=>(process.platform===`win32`?/^[\w@%+=:,./\\-]+$/:/^[\w@%+=:,./-]+$/).test(e)?e:process.platform===`win32`?`"${e}"`:`'${e.replaceAll(`'`,`'\\''`)}'`,C=e=>process.platform===`darwin`?[`open`,e]:process.platform===`win32`?[`rundll32`,`url.dll,FileProtocolHandler`,e]:[`xdg-open`,e],w=()=>{if(process.platform===`darwin`)return[{argv:[`pbcopy`]}];if(process.platform===`win32`)return[{argv:[`clip`],encode:e=>Buffer.from(`\ufeff${e}`,`utf16le`)}];let e={argv:[`wl-copy`]},t={argv:[`xclip`,`-selection`,`clipboard`]};return process.env.WAYLAND_DISPLAY?[e,t]:[t,e]},T=(e,t)=>new Promise((n,r)=>{let i=m(e,t,{detached:!0,stdio:`ignore`});i.once(`error`,r),i.once(`spawn`,()=>{i.unref(),n()})}),E=(e,t,n)=>new Promise((r,i)=>{let a=m(e,t,{stdio:[`pipe`,`ignore`,`ignore`]});a.once(`error`,i),a.stdin.once(`error`,i),a.once(`exit`,t=>{t===0?r():i(Error(`${e} exited with code ${t}`))}),a.stdin.end(n)}),D=n=>{let o=new Set,p=()=>{for(let e of[...o])e()};return{configPath:n,serverVersion:e().version,machineId:h.machineIdSync(),async readConfigText(){try{return await u.readFile(n,`utf8`)}catch(e){if(y(e))return null;throw e}},async writeConfigText(e,{backup:t}){let r=await u.realpath(n).catch(()=>n),i=await b(r);await u.mkdir(d.dirname(r),{recursive:!0}),p();let a=d.join(d.dirname(r),`.${d.basename(r)}.${process.pid}-${Date.now()}.tmp`);try{await u.writeFile(a,e,{encoding:`utf8`,flag:`wx`,...i?{mode:i.mode&511}:{}}),i&&await u.chmod(a,i.mode&4095);let o=null;return t&&i&&(o=`${n}.bak`,await u.copyFile(r,o)),await u.rename(a,r),{backupPath:o}}catch(e){throw await u.rm(a,{force:!0}),e}},async statConfig(){let e=await b(n);return e?{mtimeMs:e.mtimeMs}:null},watchConfig(e){let t=d.basename(n),r=null,i=null,a=!1,s=()=>{if(o.delete(s),!a)try{i=f.watch(d.dirname(n),(n,i)=>{i&&i!==t||(r&&clearTimeout(r),r=setTimeout(()=>{r=null,e()},100))}),i.on(`error`,e=>{console.warn(`[ui] Stopped watching ${n}: ${e.message}`),i?.close()})}catch(e){y(e)?o.add(s):console.warn(`[ui] Cannot watch ${n}: ${e.message}`)}};return s(),()=>{a=!0,o.delete(s),r&&clearTimeout(r),i?.close()}},async probeCaps(e){return(await t(e.map(e=>({type:e})))).map(({type:e,score:t,hasGpu:n,usableBytes:r})=>({type:e,score:t??0,hasGpu:n??!1,usableBytes:r??0}))},async getBackendDefaults(e){return r(e)},resolveHfToken(e){let t={...x(e.raw.env),...process.env};return[e.runtime.huggingface_token,t.HUGGINGFACE_TOKEN,t.HF_TOKEN].find(e=>typeof e==`string`&&e.trim()!==``)?.trim()??null},async hostInfo(){return i()},async preferredAppearance(){if(process.platform!==`darwin`)return`light`;try{let{stdout:e}=await v(`defaults`,[`read`,`-g`,`AppleInterfaceStyle`]);return e.trim()===`Dark`?`dark`:`light`}catch{return`light`}},async openExternal(e){let{protocol:t}=new URL(e);if(t!==`http:`&&t!==`https:`)throw Error(`Only http(s) links can be opened: ${e}`);let[n,...r]=C(e);await T(n,r)},async copyToClipboard(e){let t=null;for(let{argv:n,encode:r}of w()){let[i,...a]=n;try{await E(i,a,r?r(e):e);return}catch(e){t=e}}throw t},startCommand:()=>`bricks-buttress --config ${S(n)}`,agentConnection(e){if(!f.existsSync(n))return null;let t;try{t=c(n)}catch{return null}let{config:r,agentsConfig:i}=t;return i?{baseUrl:`http://127.0.0.1:${e?.port??(r.server.port||2080)}`,token:l(i.runtimeTokenFile)}:null},agentsConfigError(e){let t=e;if(t===void 0)try{t=f.readFileSync(n,`utf8`)}catch{return{agents:0,error:null}}let r;try{r=g.parse(t)}catch(e){return{agents:0,error:`invalid TOML: ${O(e)}`}}let i=Array.isArray(r.agents)?r.agents.length:0;if(i===0)return{agents:0,error:null};try{return s(a(r),{configDir:d.dirname(n)}),{agents:i,error:null}}catch(e){return{agents:i,error:O(e)}}}}},O=e=>e instanceof Error?e.message:String(e),k=()=>import(`@fugood/buttress-ui`),A=[`darwin-arm64`,`linux-x64`,`win32-x64`],j=[`chat`,`status`,`settings`],M=e=>j.includes(e),N=e=>{let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`-h`||i===`--help`)return{kind:`help`};if(i===`-c`||i===`--config`){let n=e[r+1];if(n===void 0)return{kind:`error`,message:`${i} needs a config file path`};t.push(n),r+=1}else if(i===`--tab`){let t=e[r+1];if(t===void 0||!M(t)){let e=t===void 0?``:` (got "${t}")`;return{kind:`error`,message:`--tab needs one of ${j.join(`, `)}${e}`}}n=t,r+=1}else if(i.startsWith(`-`))return{kind:`error`,message:`Unknown option: ${i}`};else t.push(i)}return t.length===0?{kind:`error`,message:`bricks-buttress ui needs a config file path`}:t.length>1?{kind:`error`,message:`Give one config file path (got ${t.join(`, `)})`}:t[0].includes(`
2
+ import{a as e,i as t,n,o as r,r as i}from"./net-DHnXAu8o.mjs";import{a,c as o,n as s}from"./config-DiYweJ2m.mjs";import{n as c,r as l}from"./client-qqI-HCOj.mjs";import u from"node:fs/promises";import d from"node:path";import f from"node:fs";import{execFile as p,spawn as m}from"node:child_process";import h from"node-machine-id";import g from"@iarna/toml";import{promisify as _}from"node:util";const v=_(p),y=e=>e?.code===`ENOENT`,b=async e=>{try{return await u.stat(e)}catch(e){if(y(e))return null;throw e}},x=e=>{if(!e)return{};try{let{env:t}=g.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}},S=e=>(process.platform===`win32`?/^[\w@%+=:,./\\-]+$/:/^[\w@%+=:,./-]+$/).test(e)?e:process.platform===`win32`?`"${e}"`:`'${e.replaceAll(`'`,`'\\''`)}'`,C=e=>process.platform===`darwin`?[`open`,e]:process.platform===`win32`?[`rundll32`,`url.dll,FileProtocolHandler`,e]:[`xdg-open`,e],w=()=>{if(process.platform===`darwin`)return[{argv:[`pbcopy`]}];if(process.platform===`win32`)return[{argv:[`clip`],encode:e=>Buffer.from(`\ufeff${e}`,`utf16le`)}];let e={argv:[`wl-copy`]},t={argv:[`xclip`,`-selection`,`clipboard`]};return process.env.WAYLAND_DISPLAY?[e,t]:[t,e]},T=(e,t)=>new Promise((n,r)=>{let i=m(e,t,{detached:!0,stdio:`ignore`});i.once(`error`,r),i.once(`spawn`,()=>{i.unref(),n()})}),E=(e,t,n)=>new Promise((r,i)=>{let a=m(e,t,{stdio:[`pipe`,`ignore`,`ignore`]});a.once(`error`,i),a.stdin.once(`error`,i),a.once(`exit`,t=>{t===0?r():i(Error(`${e} exited with code ${t}`))}),a.stdin.end(n)}),D=n=>{let o=new Set,p=()=>{for(let e of[...o])e()};return{configPath:n,serverVersion:e().version,machineId:h.machineIdSync(),async readConfigText(){try{return await u.readFile(n,`utf8`)}catch(e){if(y(e))return null;throw e}},async writeConfigText(e,{backup:t}){let r=await u.realpath(n).catch(()=>n),i=await b(r);await u.mkdir(d.dirname(r),{recursive:!0}),p();let a=d.join(d.dirname(r),`.${d.basename(r)}.${process.pid}-${Date.now()}.tmp`);try{await u.writeFile(a,e,{encoding:`utf8`,flag:`wx`,...i?{mode:i.mode&511}:{}}),i&&await u.chmod(a,i.mode&4095);let o=null;return t&&i&&(o=`${n}.bak`,await u.copyFile(r,o)),await u.rename(a,r),{backupPath:o}}catch(e){throw await u.rm(a,{force:!0}),e}},async statConfig(){let e=await b(n);return e?{mtimeMs:e.mtimeMs}:null},watchConfig(e){let t=d.basename(n),r=null,i=null,a=!1,s=()=>{if(o.delete(s),!a)try{i=f.watch(d.dirname(n),(n,i)=>{i&&i!==t||(r&&clearTimeout(r),r=setTimeout(()=>{r=null,e()},100))}),i.on(`error`,e=>{console.warn(`[ui] Stopped watching ${n}: ${e.message}`),i?.close()})}catch(e){y(e)?o.add(s):console.warn(`[ui] Cannot watch ${n}: ${e.message}`)}};return s(),()=>{a=!0,o.delete(s),r&&clearTimeout(r),i?.close()}},async probeCaps(e){return(await t(e.map(e=>({type:e})))).map(({type:e,score:t,hasGpu:n,usableBytes:r})=>({type:e,score:t??0,hasGpu:n??!1,usableBytes:r??0}))},async getBackendDefaults(e){return r(e)},resolveHfToken(e){let t={...x(e.raw.env),...process.env};return[e.runtime.huggingface_token,t.HUGGINGFACE_TOKEN,t.HF_TOKEN].find(e=>typeof e==`string`&&e.trim()!==``)?.trim()??null},async hostInfo(){return i()},async preferredAppearance(){if(process.platform!==`darwin`)return`light`;try{let{stdout:e}=await v(`defaults`,[`read`,`-g`,`AppleInterfaceStyle`]);return e.trim()===`Dark`?`dark`:`light`}catch{return`light`}},async openExternal(e){let{protocol:t}=new URL(e);if(t!==`http:`&&t!==`https:`)throw Error(`Only http(s) links can be opened: ${e}`);let[n,...r]=C(e);await T(n,r)},async copyToClipboard(e){let t=null;for(let{argv:n,encode:r}of w()){let[i,...a]=n;try{await E(i,a,r?r(e):e);return}catch(e){t=e}}throw t},startCommand:()=>`bricks-buttress --config ${S(n)}`,agentConnection(e){if(!f.existsSync(n))return null;let t;try{t=c(n)}catch{return null}let{config:r,agentsConfig:i}=t;return i?{baseUrl:`http://127.0.0.1:${e?.port??(r.server.port||2080)}`,token:l(i.runtimeTokenFile)}:null},agentsConfigError(e){let t=e;if(t===void 0)try{t=f.readFileSync(n,`utf8`)}catch{return{agents:0,error:null}}let r;try{r=g.parse(t)}catch(e){return{agents:0,error:`invalid TOML: ${O(e)}`}}let i=Array.isArray(r.agents)?r.agents.length:0;if(i===0)return{agents:0,error:null};try{return s(a(r),{configDir:d.dirname(n)}),{agents:i,error:null}}catch(e){return{agents:i,error:O(e)}}}}},O=e=>e instanceof Error?e.message:String(e),k=()=>import(`@fugood/buttress-ui`),A=[`darwin-arm64`,`linux-x64`,`win32-x64`],j=[`chat`,`status`,`settings`],M=e=>j.includes(e),N=e=>{let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`-h`||i===`--help`)return{kind:`help`};if(i===`-c`||i===`--config`){let n=e[r+1];if(n===void 0)return{kind:`error`,message:`${i} needs a config file path`};t.push(n),r+=1}else if(i===`--tab`){let t=e[r+1];if(t===void 0||!M(t)){let e=t===void 0?``:` (got "${t}")`;return{kind:`error`,message:`--tab needs one of ${j.join(`, `)}${e}`}}n=t,r+=1}else if(i.startsWith(`-`))return{kind:`error`,message:`Unknown option: ${i}`};else t.push(i)}return t.length===0?{kind:`error`,message:`bricks-buttress ui needs a config file path`}:t.length>1?{kind:`error`,message:`Give one config file path (got ${t.join(`, `)})`}:t[0].includes(`
3
3
  `)?{kind:`error`,message:`bricks-buttress ui edits a config file; inline TOML is not supported`}:{kind:`run`,configPath:d.resolve(t[0]),initialTab:n}},P=()=>({isBun:`Bun`in globalThis,platform:process.platform,arch:process.arch}),F=(e,t)=>e.isBun?A.includes(`${e.platform}-${e.arch}`)?null:`bricks-buttress ui runs on darwin-arm64, linux-x64 and win32-x64; on this machine open ${t()} in a browser instead`:`bricks-buttress ui needs Bun; run it with bun or the standalone bricks-buttress binary`,I=e=>{try{let t=g.parse(f.readFileSync(e,`utf8`)).server?.port;return Number.isInteger(t)&&t>0?t:o}catch{return o}},L=e=>`http://${n()??`localhost`}:${I(e)}/status`,R=e=>e instanceof Error?e.message:String(e),z=e=>{let{code:t,specifier:n}=e??{};return t===`ERR_MODULE_NOT_FOUND`&&n===`@fugood/buttress-ui`},B=e=>process.env.BUTTRESS_SERVER_DISTRIBUTION===`1`&&R(e).includes(`@gpuix/native-`),V=async e=>{try{let{launchButtressUi:e}=await k();return e}catch(t){z(t)?console.error(`This bricks-buttress install does not include the settings window (the npm package leaves it out); use the standalone bricks-buttress binary or a source checkout, or open ${L(e)} in a browser instead`):B(t)?console.error(`The window's native module (gpuix) is missing next to bricks-buttress; run \`bricks-buttress update\` to reinstall it, or open ${L(e)} in a browser instead (${R(t)})`):console.error(`bricks-buttress ui failed to load the window: ${R(t)}`),process.exit(1)}},H=async e=>{let t=N(e);t.kind===`help`&&(console.log(`
4
4
  Usage:
5
5
  bricks-buttress ui [-c|--config] <config.toml> [--tab <chat|status|settings>]