@fugood/buttress-server 2.26.0-beta.23 → 2.26.0-beta.25

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
@@ -565,16 +565,38 @@ vocoder_batch_size = 4096
565
565
  ### `ggml-decision` (typed decisions via `@fugood/llama.node`)
566
566
 
567
567
  Loads a typed decision model (System One — Julia-1, Laya, Kev, Jevling, lev,
568
- ...) and answers `choice` / `score` / `noul` questions about a state with
569
- calibrated probabilities: one forward pass per answer, no generated tokens.
570
- Clients reach it through the Typed Decision (GGML) generator; local
571
- functions through `context.buttress.decide`.
568
+ Clef, LiquidAI d1, pplx-decider, ...) and answers `choice` / `score` / `noul`
569
+ questions about a state with calibrated probabilities: one forward pass per
570
+ answer, no generated tokens. Clients reach it through the Typed Decision (GGML)
571
+ generator; local functions through `context.buttress.decide`.
572
572
 
573
573
  The model is checked when its context loads: a GGUF with no decision metadata
574
574
  (`<arch>.decision.type`) and no `system_one` template, or one whose decision
575
575
  type this build cannot serve, fails the load with the reason. Requests on one
576
576
  generator run one at a time.
577
577
 
578
+ **Requests** follow the TypeSafe `/v1/systemone` shape:
579
+ `{ state, questions, images?, files? }`.
580
+
581
+ - `state` is text, or a JSON object/array (given to the model as JSON text).
582
+ - `questions` maps an id to a `choice`, `score` or `noul` question. A `noul`
583
+ question takes `criteria: { true?, false? }`; `lfm2-d1-omni` also takes
584
+ `yes` / `no`.
585
+ - `images` carries the media: images, or audio clips for a model whose prompt
586
+ takes audio (`lfm2-d1-omni`). `files` is an alias; both lists are used. A
587
+ client session sends uploaded file names (resolved like STT audio) or data
588
+ URLs (`data:image/...`, `data:audio/...`); local functions send file paths
589
+ or data URLs; the HTTP endpoints take data URLs only. `lfm2-d1-omni` takes
590
+ images or one audio clip, not both.
591
+ - With media, `state` may be `null` (or empty) to ask about the media only.
592
+ Only `lfm2-d1` and `lfm2-d1-omni` accept that; other models reject it. Without
593
+ media a `state` is required.
594
+
595
+ The OpenAI-compatible `POST /oai-compat/v1/decisions` also takes `input_audio`
596
+ content parts (`{ type: 'input_audio', input_audio: { data, format } }`, base64
597
+ `data`, `format` `wav` or `mp3`). An input with only images or audio gets a
598
+ placeholder state (`The attached image.`), since every model type takes one.
599
+
578
600
  **Sharing a model with `ggml-llm`** — a model that both generates and decides
579
601
  (Jevling, for one) can be configured as both a `ggml-llm` and a
580
602
  `ggml-decision`. By default each loads its own context. Set
@@ -623,7 +645,7 @@ filename = "jevling-0.8b-v1-q8_0-embf16.gguf"
623
645
  | Key | Type | Default | Notes |
624
646
  | ------------------------- | -------- | -------------------------------- | ------------------------------------------------------------------ |
625
647
  | `preferred_quantizations` | string[] | `["q8_0", "q4_k_m", <no-quant>]` | Default fallback chain |
626
- | `mmproj_repo_id` | string | falls back to `repo_id` | Vision projector repo, for models whose prompt takes images |
648
+ | `mmproj_repo_id` | string | falls back to `repo_id` | Projector repo, for models whose prompt takes images or audio |
627
649
  | `mmproj_filename` | string | auto (`*mmproj*`) | Pin a specific projector artifact |
628
650
  | `mmproj_url` | string | — | Direct projector URL (skips manifest lookup) |
629
651
  | `mmproj_revision` | string | falls back to `revision` | |
@@ -633,8 +655,8 @@ filename = "jevling-0.8b-v1-q8_0-embf16.gguf"
633
655
  | `n_gpu_layers` | number | `99` | Forced to `0` when the GPU is unused |
634
656
 
635
657
  Setting any `mmproj_*` key loads a projector; requests can then pass `images`
636
- (file paths or data URLs). The projector is ignored, with a warning, when the
637
- model's prompt has no place for images.
658
+ (images or audio clips, as file paths or data URLs). The projector is ignored,
659
+ with a warning, when the model's prompt has no place for images or audio.
638
660
 
639
661
  **Runtime extras** — under `[runtime]` for ggml-decision:
640
662
 
@@ -895,7 +917,7 @@ export default async function ({ path }: { path: string }, context: ButtressFunc
895
917
  | `buttress.detokenize({ model?, tokens })` | Convert token ids back into text with the same model. |
896
918
  | `buttress.transcribe({ model?, filePath \| audioData, options? })` | Transcribe audio with this server's STT generator. |
897
919
  | `buttress.synthesize({ model?, text, options? })` | Synthesize speech with this server's TTS generator (`onnx-tts` or `ggml-tts`); the WAV lands in `tempDir` → `{ path, sampling_rate, channels }`. |
898
- | `buttress.decide({ model?, state, questions, images? })` | Answer typed `choice` / `score` / `noul` questions about `state` with this server's `ggml-decision` generator → `{ model, answers, usage }`. `answers[id]` is typed from its question. `images` are local paths or data URLs. |
920
+ | `buttress.decide({ model?, state, questions, images?, files? })` | Answer typed `choice` / `score` / `noul` questions about `state` with this server's `ggml-decision` generator → `{ model, answers, usage }`. `answers[id]` is typed from its question. `images` (alias `files`) are images or audio clips, as local paths or data URLs; with media, `state` may be `null` for `lfm2-d1` / `lfm2-d1-omni`. |
899
921
  | `bank.list({ keyword?, meta?, ids? })` / `bank.get(id)` / `bank.update(properties, { dontNotify? })` / `bank.remove(id)` | Read/write the bound workspace's remote **Data Bank** (see below). To listen for changes, use `bank.subscribe` inside a daemon function. |
900
922
  | `daemons.emit(name, event, data?)` / `daemons.list()` | Signal a running **daemon function**'s `onEvent` handlers (see below) / list running daemon names. |
901
923
  | `emit(event, data)` | Progress event; delivered to SSE callers, ignored otherwise. |
@@ -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-u--89HiT.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>]
@@ -10,7 +10,7 @@ export declare const TYPES_FILE_NAME = "buttress-functions.d.ts";
10
10
  export declare const TSCONFIG_FILE_NAME = "tsconfig.json";
11
11
  export declare const EXAMPLE_FILE_NAME = "_example.ts";
12
12
  export declare const EXAMPLE_DAEMON_FILE_NAME = "_example-daemon.ts";
13
- export declare const TYPES_TEMPLATE = "// Generated by @fugood/buttress-server \u2014 do not edit.\n// Rewritten on every server start to match the running version.\n//\n// Local functions are EXPERIMENTAL: this contract may change between\n// releases \u2014 after a server upgrade, re-read this file for the current shape.\n\n/** Result of `context.spawn(...)`. */\ntype ButtressSpawnResult = {\n /** Exit code, or null when the process was killed by a signal. */\n code: number | null\n signal: NodeJS.Signals | null\n stdout: string | Buffer\n stderr: string | Buffer\n /** True when output hit `maxBuffer` and capture stopped early. */\n truncated: boolean\n}\n\ntype ButtressSpawnOptions = {\n cwd?: string\n /** Merged over the server's own environment. */\n env?: Record<string, string | undefined>\n /** Written to stdin, which is then closed. */\n input?: string | Uint8Array\n /** 'utf8' (default) yields strings; 'buffer' yields Buffers. */\n encoding?: 'utf8' | 'buffer'\n /** Per-stream capture cap in bytes (default 8MB). */\n maxBuffer?: number\n onStdout?: (chunk: Buffer) => void\n onStderr?: (chunk: Buffer) => void\n}\n\ntype ButtressCompletionResult = {\n content: string\n reasoning_content?: string\n tool_calls?: any[]\n interrupted?: boolean\n usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number }\n}\n\ntype ButtressEmbeddingResult = {\n /** Plain numbers, ready for JSON or conversion into a sqlite-vec float32 BLOB. */\n embedding: number[]\n}\n\n/** A string, or any JSON object/array (given to the model as JSON text). */\ntype ButtressDecisionContent = string | readonly any[] | { [key: string]: any }\n\ntype ButtressDecisionQuestion =\n | {\n type: 'choice'\n instructions: ButtressDecisionContent\n /**\n * Option key \u2192 description (or null), shown in key order. Whole-number\n * keys ('1', '10') sort first in JavaScript, so prefix them ('n1').\n */\n criteria: { [key: string]: string | null }\n }\n | {\n type: 'score'\n instructions: ButtressDecisionContent\n /** 2 to 10 level descriptions, lowest first. */\n criteria: readonly string[]\n }\n | {\n type: 'noul'\n instructions: ButtressDecisionContent\n criteria?: { true?: string | null; false?: string | null }\n }\n\n/** The answer for one question, narrowed by its type (choice keys included). */\ntype ButtressDecisionAnswer<Q> = Q extends { type: 'choice'; criteria: infer C }\n ? {\n type: 'choice'\n /** The option with the highest probability. */\n choice: keyof C & string\n /** Option \u2192 probability, summing to 1. */\n probabilities: { [K in keyof C & string]: number }\n /** 0 when all options are equally likely, 1 when one has all the mass. */\n confidence: number\n }\n : Q extends { type: 'score' }\n ? {\n type: 'score'\n /** Expected level index, weighted by probability (may fall between levels). */\n score: number\n /** Level index \u2192 description. */\n legend: Record<string, string>\n /** Level index \u2192 probability, summing to 1. */\n probabilities: Record<string, number>\n confidence: number\n }\n : {\n type: 'noul'\n /** Probability that the statement is true. */\n noul: number\n }\n\ntype ButtressDecisionResult<Q extends Record<string, ButtressDecisionQuestion>> = {\n /** `general.name` of the model, or its file name. */\n model: string\n answers: { [id in keyof Q]: ButtressDecisionAnswer<Q[id]> }\n /** `output_tokens` is always 0: no token is generated. */\n usage: { input_tokens: number; output_tokens: number }\n}\n\n/** 'InSubspace' scopes a property to the space; 'Global' is cross-application. */\ntype ButtressBankPropertyMeta = 'InSubspace' | 'Global'\n\ntype ButtressBankProperty = {\n propertyId: string\n meta: ButtressBankPropertyMeta\n definition: Record<string, any> | null\n value: any\n tags: string[] | null\n lastUpdateHash: string | null\n lastUpdateNote: string | null\n lastUpdateKey: string | null\n createAt: string | null\n updateAt: string | null\n}\n\n/**\n * The Bank replaces `value` unconditionally on update \u2014 an omitted `value`\n * clears the stored one. Read-merge first when a partial update is intended.\n */\ntype ButtressBankPropertyInput = {\n propertyId: string\n /** Defaults to 'InSubspace'. */\n meta?: ButtressBankPropertyMeta\n definition?: Record<string, any>\n newDefinitionFallback?: Record<string, any>\n value?: any\n updateNote?: string\n /** Bank defaults upsert to true; pass false to require an existing property. */\n upsert?: boolean\n tags?: string[]\n}\n\ntype ButtressFunctionContext = {\n /**\n * Run a child process. Resolves once it exits \u2014 a non-zero `code` is a\n * normal resolution, so check it yourself. Rejects only when the process\n * cannot be started. Every process a call spawns is killed when the call\n * ends or times out.\n */\n spawn: (\n command: string,\n args?: string[],\n options?: ButtressSpawnOptions,\n ) => Promise<ButtressSpawnResult>\n\n buttress: {\n /**\n * Run a chat completion on this server's LLM generator. `messages` are\n * rendered with the model's own chat template, and thinking is off unless\n * you pass `enable_thinking: true` (which fills `reasoning_content`).\n */\n completion: (options: {\n /** Configured `[[generators]]` model; defaults to the first one. */\n model?: string\n messages?: { role: string; content: any }[]\n /**\n * Raw prompt sent without the chat template \u2014 the fallback for models\n * whose template the server cannot apply. Use instead of `messages`.\n */\n prompt?: string\n /** Cap on generated tokens. Unbounded when omitted. */\n max_tokens?: number\n temperature?: number\n /** Emit the model's reasoning into `reasoning_content` (default false). */\n enable_thinking?: boolean\n /** Called for every streamed token event. */\n onToken?: (event: { token?: string; content?: string; [key: string]: any }) => void\n /** Any other backend sampling option (`top_p`, `stop`, `tools`, \u2026). */\n [param: string]: any\n }) => Promise<ButtressCompletionResult>\n\n /**\n * Embed text with a GGML generator whose `[generators.model]` table sets\n * `embedding = true`. The vector is returned as plain numbers.\n */\n embedding: (options: {\n model?: string\n text: string\n /** llama.cpp normalization mode; 2 (L2) is the native default. */\n embd_normalize?: number\n }) => Promise<ButtressEmbeddingResult>\n\n /** Tokenize text with a configured GGML or MLX generator. */\n tokenize: (options: {\n model?: string\n text: string\n params?: Record<string, any>\n }) => Promise<Record<string, any> & { tokens: number[] }>\n\n /** Turn model token ids back into text. */\n detokenize: (options: { model?: string; tokens: number[] }) => Promise<string>\n\n /** Transcribe audio with this server's STT generator. */\n transcribe: (options: {\n /** Must match a configured STT model (`repo_id` or `repo_id:filename`). */\n model?: string\n filePath?: string\n audioData?: Uint8Array | Buffer\n options?: Record<string, any>\n }) => Promise<any>\n\n /**\n * Synthesize speech with this server's TTS generator (onnx-tts or\n * ggml-tts). The WAV is written into `tempDir`; return\n * `fileUrl(path)` to let callers download it.\n */\n synthesize: (options: {\n /** Must match a configured TTS model when given. */\n model?: string\n text: string\n /** Backend options; `options.speaker` picks a registered voice. */\n options?: Record<string, any>\n }) => Promise<{ path: string; sampling_rate: number; channels: number }>\n\n /**\n * Answer typed questions about a state with this server's `ggml-decision`\n * generator (TypeSafe `/v1/systemone` shape): calibrated probabilities from\n * one forward pass per answer, no generated tokens. `answers[id]` is typed\n * from the question's `type` and choice keys.\n */\n decide: <const Q extends Record<string, ButtressDecisionQuestion>>(options: {\n /** Must match a configured decision model (`repo_id` or `repo_id:filename`). */\n model?: string\n /** The content to evaluate: text, or a JSON object/array. */\n state: ButtressDecisionContent\n questions: Q\n /** Local file paths or data URLs; the generator needs an mmproj configured. */\n images?: string[]\n }) => Promise<ButtressDecisionResult<Q>>\n }\n\n /**\n * Daemon functions running on this server (files with `meta.daemon`).\n */\n daemons: {\n /**\n * Deliver an event to the named daemon's `context.onEvent` handlers;\n * it arrives as `{ event, data, source }`. Throws when no daemon of\n * that name is running, or when it registered no handler.\n */\n emit: (name: string, event: string, data?: unknown) => void\n /** Names of the daemons currently running. */\n list: () => string[]\n }\n\n /**\n * The bound workspace's remote Data Bank (read/write; daemon functions can\n * also subscribe to changes via `bank.subscribe`). Every method throws\n * until credentials are stored via `bricks buttress bank-key` (run on\n * this host, then restart the server).\n */\n bank: {\n /** List properties, optionally filtered. */\n list: (options?: {\n /** Match against definition title/description or tags. */\n keyword?: string\n meta?: ButtressBankPropertyMeta\n /** Restrict to these property ids. */\n ids?: string[]\n }) => Promise<ButtressBankProperty[]>\n\n /** One property, or null when it does not exist. */\n get: (propertyId: string) => Promise<ButtressBankProperty | null>\n\n /**\n * Create or update properties (upsert by default). Updates notify\n * subscribed devices unless `dontNotify` is set.\n */\n update: (\n properties: ButtressBankPropertyInput[],\n options?: { dontNotify?: boolean },\n ) => Promise<ButtressBankProperty[]>\n\n /** Delete a property. Resolves false when it did not exist. */\n remove: (propertyId: string) => Promise<boolean>\n\n /**\n * Watch property ids for remote changes. Only available inside daemon\n * functions (throws elsewhere); closed automatically when the daemon\n * stops. The connection is shared and reconnects on its own \u2014 a network\n * drop never stops the daemon.\n */\n subscribe: (\n propertyIds: string[],\n onChange: (properties: ButtressBankProperty[]) => unknown,\n ) => { close: () => void }\n }\n\n fetch: typeof fetch\n /** Server-side log, prefixed with the function name. */\n log: (...args: unknown[]) => void\n /** Emit a progress event. Delivered only to SSE callers; a no-op otherwise. */\n emit: (event: string, data?: unknown) => void\n /** Aborted when the call times out or the caller disconnects. */\n signal: AbortSignal\n env: Record<string, string | undefined>\n /**\n * The `[functions.config]` table from the server config. Read once at\n * server start \u2014 unlike function files, config edits need a restart.\n */\n config: Record<string, any>\n /** Per-call scratch directory, created on first access. */\n tempDir: string\n /**\n * Download URL path (`/functions/files/...`) for a file inside `tempDir`;\n * relative input resolves against it. Callers fetch the URL with the same\n * auth as any function call. Scratch dirs are swept after ~24h.\n */\n fileUrl: (target: string) => string\n /** Absolute path of this functions directory. */\n dir: string\n /** Helper libraries: _, lodash, moment, math, mathjs, voca, chroma, json5, qs, bytes, ms, nanoid, md5. */\n libs: Record<string, any>\n}\n\ntype ButtressFunctionMeta = {\n /** Shown to MCP clients in `tools/list`. */\n description?: string\n /** JSON Schema for the input object, passed to MCP verbatim. */\n parameters?: Record<string, any>\n /**\n * Deadline for this function: ms, or a duration string like \"10m\".\n * Ignored for daemons \u2014 a daemon has no deadline.\n */\n timeout?: number | string\n /**\n * `true` declares this file as a daemon: a long-lived background\n * function. Its default export runs once, with a ButtressDaemonContext as\n * its only argument, and stays alive \u2014 everything registered there\n * (`setInterval` timers, `bank.subscribe` subscriptions, `onEvent`\n * handlers) keeps firing until the file changes or the server stops.\n * A daemon is not an MCP tool and cannot be called over HTTP.\n */\n daemon?: boolean\n}\n\n/** An event another local function sent via `context.daemons.emit`. */\ntype ButtressDaemonEmittedEvent = {\n event: string\n data?: unknown\n /** Name of the local function (or daemon) that emitted it. */\n source: string\n}\n\n/**\n * What a daemon's default export receives: the full function context plus\n * lifetime APIs. `context.signal` aborts when the daemon stops (file\n * changed/removed, or server shutdown); an optional cleanup function\n * *returned* by the handler also runs at that point.\n */\ntype ButtressDaemonContext = ButtressFunctionContext & {\n /**\n * A managed `setInterval`: the callback keeps firing until cleared or\n * the daemon stops. A callback that throws is logged (and shown on\n * /status) \u2014 it never stops the timer or the daemon.\n */\n setInterval: (callback: () => unknown, ms: number) => unknown\n clearInterval: (handle: unknown) => void\n /** Receive events other local functions send via `context.daemons.emit`. */\n onEvent: (handler: (event: ButtressDaemonEmittedEvent) => unknown) => void\n}\n\n// --- Custom auth ------------------------------------------------------------\n// Drop an `_auth.ts` into this directory to gate the /functions endpoints\n// with your own logic. It exports the same shape as a function file:\n//\n// export const meta: ButtressAuthMeta = { mode: 'both' }\n// export default async function (\n// request: ButtressAuthRequest,\n// context: ButtressAuthContext,\n// ): Promise<ButtressAuthResult> { ... }\n//\n// While an `_auth` file exists but fails to load, every call is rejected.\n\ntype ButtressAuthMeta = {\n /**\n * 'both' (default): runs after the built-in workspace auth passes, as an\n * extra gate. 'override': replaces workspace auth \u2014 this function is the\n * only authority (a presented workspace token is still verified into\n * `request.workspaceAuth` so you can choose to honor it).\n */\n mode?: 'override' | 'both'\n}\n\ntype ButtressAuthRequest = {\n method: string\n path: string\n /** Function name for `GET`/`POST /functions/<name>`; undefined for list and MCP. */\n name?: string\n headers: Record<string, string | undefined>\n query: Record<string, string | undefined>\n /** Raw bearer token (Authorization header or `?token=`), if any. */\n token: string | null\n workspaceAuth: {\n /** Whether this server is bound to a workspace. */\n bound: boolean\n /** Whether the caller presented a valid workspace access token. */\n authenticated: boolean\n identity: {\n workspaceId: string\n subjectType: 'ws' | 'dev'\n subjectId: string\n jti?: string\n exp: number\n } | null\n }\n}\n\ntype ButtressAuthContext = {\n /** Server-side log, prefixed with \"_auth\". */\n log: (...args: unknown[]) => void\n fetch: typeof fetch\n env: Record<string, string | undefined>\n /** The `[functions.config]` table, same as `context.config` in functions. */\n config: Record<string, any>\n /** Absolute path of this functions directory. */\n dir: string\n /** Same helper libraries functions get. */\n libs: Record<string, any>\n}\n\n/** Only `true` (or `{ ok: true }`) allows the request; anything else denies. */\ntype ButtressAuthResult =\n | boolean\n | {\n ok: boolean\n /** Response status for a denial, 400-499 (default 403). */\n status?: number\n /** Message returned to the caller on denial. */\n error?: string\n }\n\n// The only non-builtin packages the local-function loader accepts. These\n// declarations keep editor support working when this directory is outside the\n// server package's own node_modules resolution tree.\ndeclare module 'sqlite3' {\n type SqliteCallback = (error: Error | null) => void\n\n class Database {\n constructor(filename: string, callback?: SqliteCallback)\n run(sql: string, ...params: any[]): this\n all<T = Record<string, any>>(\n sql: string,\n ...params: [...any[], (error: Error | null, rows: T[]) => void]\n ): this\n exec(sql: string, callback?: SqliteCallback): this\n loadExtension(filename: string, callback?: SqliteCallback): this\n close(callback?: SqliteCallback): void\n }\n\n const sqlite3: { Database: typeof Database }\n export { Database }\n export default sqlite3\n}\n\ndeclare module 'sqlite-vec' {\n export function getLoadablePath(): string\n export function load(database: { loadExtension(path: string): unknown }): void\n}\n";
13
+ export declare const TYPES_TEMPLATE = "// Generated by @fugood/buttress-server \u2014 do not edit.\n// Rewritten on every server start to match the running version.\n//\n// Local functions are EXPERIMENTAL: this contract may change between\n// releases \u2014 after a server upgrade, re-read this file for the current shape.\n\n/** Result of `context.spawn(...)`. */\ntype ButtressSpawnResult = {\n /** Exit code, or null when the process was killed by a signal. */\n code: number | null\n signal: NodeJS.Signals | null\n stdout: string | Buffer\n stderr: string | Buffer\n /** True when output hit `maxBuffer` and capture stopped early. */\n truncated: boolean\n}\n\ntype ButtressSpawnOptions = {\n cwd?: string\n /** Merged over the server's own environment. */\n env?: Record<string, string | undefined>\n /** Written to stdin, which is then closed. */\n input?: string | Uint8Array\n /** 'utf8' (default) yields strings; 'buffer' yields Buffers. */\n encoding?: 'utf8' | 'buffer'\n /** Per-stream capture cap in bytes (default 8MB). */\n maxBuffer?: number\n onStdout?: (chunk: Buffer) => void\n onStderr?: (chunk: Buffer) => void\n}\n\ntype ButtressCompletionResult = {\n content: string\n reasoning_content?: string\n tool_calls?: any[]\n interrupted?: boolean\n usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number }\n}\n\ntype ButtressEmbeddingResult = {\n /** Plain numbers, ready for JSON or conversion into a sqlite-vec float32 BLOB. */\n embedding: number[]\n}\n\n/** A string, or any JSON object/array (given to the model as JSON text). */\ntype ButtressDecisionContent = string | readonly any[] | { [key: string]: any }\n\ntype ButtressDecisionQuestion =\n | {\n type: 'choice'\n instructions: ButtressDecisionContent\n /**\n * Option key \u2192 description (or null), shown in key order. Whole-number\n * keys ('1', '10') sort first in JavaScript, so prefix them ('n1').\n */\n criteria: { [key: string]: string | null }\n }\n | {\n type: 'score'\n instructions: ButtressDecisionContent\n /** 2 to 10 level descriptions, lowest first. */\n criteria: readonly string[]\n }\n | {\n type: 'noul'\n instructions: ButtressDecisionContent\n /** `lfm2-d1-omni` also takes `yes` / `no`. */\n criteria?: {\n true?: string | null\n false?: string | null\n yes?: string | null\n no?: string | null\n }\n }\n\n/** The answer for one question, narrowed by its type (choice keys included). */\ntype ButtressDecisionAnswer<Q> = Q extends { type: 'choice'; criteria: infer C }\n ? {\n type: 'choice'\n /** The option with the highest probability. */\n choice: keyof C & string\n /** Option \u2192 probability, summing to 1. */\n probabilities: { [K in keyof C & string]: number }\n /** 0 when all options are equally likely, 1 when one has all the mass. */\n confidence: number\n }\n : Q extends { type: 'score' }\n ? {\n type: 'score'\n /** Expected level index, weighted by probability (may fall between levels). */\n score: number\n /** Level index \u2192 description. */\n legend: Record<string, string>\n /** Level index \u2192 probability, summing to 1. */\n probabilities: Record<string, number>\n confidence: number\n }\n : {\n type: 'noul'\n /** Probability that the statement is true. */\n noul: number\n }\n\ntype ButtressDecisionResult<Q extends Record<string, ButtressDecisionQuestion>> = {\n /** `general.name` of the model, or its file name. */\n model: string\n answers: { [id in keyof Q]: ButtressDecisionAnswer<Q[id]> }\n /** `output_tokens` is always 0: no token is generated. */\n usage: { input_tokens: number; output_tokens: number }\n}\n\n/** 'InSubspace' scopes a property to the space; 'Global' is cross-application. */\ntype ButtressBankPropertyMeta = 'InSubspace' | 'Global'\n\ntype ButtressBankProperty = {\n propertyId: string\n meta: ButtressBankPropertyMeta\n definition: Record<string, any> | null\n value: any\n tags: string[] | null\n lastUpdateHash: string | null\n lastUpdateNote: string | null\n lastUpdateKey: string | null\n createAt: string | null\n updateAt: string | null\n}\n\n/**\n * The Bank replaces `value` unconditionally on update \u2014 an omitted `value`\n * clears the stored one. Read-merge first when a partial update is intended.\n */\ntype ButtressBankPropertyInput = {\n propertyId: string\n /** Defaults to 'InSubspace'. */\n meta?: ButtressBankPropertyMeta\n definition?: Record<string, any>\n newDefinitionFallback?: Record<string, any>\n value?: any\n updateNote?: string\n /** Bank defaults upsert to true; pass false to require an existing property. */\n upsert?: boolean\n tags?: string[]\n}\n\ntype ButtressFunctionContext = {\n /**\n * Run a child process. Resolves once it exits \u2014 a non-zero `code` is a\n * normal resolution, so check it yourself. Rejects only when the process\n * cannot be started. Every process a call spawns is killed when the call\n * ends or times out.\n */\n spawn: (\n command: string,\n args?: string[],\n options?: ButtressSpawnOptions,\n ) => Promise<ButtressSpawnResult>\n\n buttress: {\n /**\n * Run a chat completion on this server's LLM generator. `messages` are\n * rendered with the model's own chat template, and thinking is off unless\n * you pass `enable_thinking: true` (which fills `reasoning_content`).\n */\n completion: (options: {\n /** Configured `[[generators]]` model; defaults to the first one. */\n model?: string\n messages?: { role: string; content: any }[]\n /**\n * Raw prompt sent without the chat template \u2014 the fallback for models\n * whose template the server cannot apply. Use instead of `messages`.\n */\n prompt?: string\n /** Cap on generated tokens. Unbounded when omitted. */\n max_tokens?: number\n temperature?: number\n /** Emit the model's reasoning into `reasoning_content` (default false). */\n enable_thinking?: boolean\n /** Called for every streamed token event. */\n onToken?: (event: { token?: string; content?: string; [key: string]: any }) => void\n /** Any other backend sampling option (`top_p`, `stop`, `tools`, \u2026). */\n [param: string]: any\n }) => Promise<ButtressCompletionResult>\n\n /**\n * Embed text with a GGML generator whose `[generators.model]` table sets\n * `embedding = true`. The vector is returned as plain numbers.\n */\n embedding: (options: {\n model?: string\n text: string\n /** llama.cpp normalization mode; 2 (L2) is the native default. */\n embd_normalize?: number\n }) => Promise<ButtressEmbeddingResult>\n\n /** Tokenize text with a configured GGML or MLX generator. */\n tokenize: (options: {\n model?: string\n text: string\n params?: Record<string, any>\n }) => Promise<Record<string, any> & { tokens: number[] }>\n\n /** Turn model token ids back into text. */\n detokenize: (options: { model?: string; tokens: number[] }) => Promise<string>\n\n /** Transcribe audio with this server's STT generator. */\n transcribe: (options: {\n /** Must match a configured STT model (`repo_id` or `repo_id:filename`). */\n model?: string\n filePath?: string\n audioData?: Uint8Array | Buffer\n options?: Record<string, any>\n }) => Promise<any>\n\n /**\n * Synthesize speech with this server's TTS generator (onnx-tts or\n * ggml-tts). The WAV is written into `tempDir`; return\n * `fileUrl(path)` to let callers download it.\n */\n synthesize: (options: {\n /** Must match a configured TTS model when given. */\n model?: string\n text: string\n /** Backend options; `options.speaker` picks a registered voice. */\n options?: Record<string, any>\n }) => Promise<{ path: string; sampling_rate: number; channels: number }>\n\n /**\n * Answer typed questions about a state with this server's `ggml-decision`\n * generator (TypeSafe `/v1/systemone` shape): calibrated probabilities from\n * one forward pass per answer, no generated tokens. `answers[id]` is typed\n * from the question's `type` and choice keys.\n */\n decide: <const Q extends Record<string, ButtressDecisionQuestion>>(options: {\n /** Must match a configured decision model (`repo_id` or `repo_id:filename`). */\n model?: string\n /**\n * The content to evaluate: text, or a JSON object/array. `null` asks\n * about the media only (`lfm2-d1`, `lfm2-d1-omni` models).\n */\n state: ButtressDecisionContent | null\n questions: Q\n /**\n * Images, or audio clips for a model that takes audio, as local file\n * paths or data URLs; the generator needs an mmproj configured.\n */\n images?: string[]\n /** Alias of `images`; both lists are used. */\n files?: string[]\n }) => Promise<ButtressDecisionResult<Q>>\n }\n\n /**\n * Daemon functions running on this server (files with `meta.daemon`).\n */\n daemons: {\n /**\n * Deliver an event to the named daemon's `context.onEvent` handlers;\n * it arrives as `{ event, data, source }`. Throws when no daemon of\n * that name is running, or when it registered no handler.\n */\n emit: (name: string, event: string, data?: unknown) => void\n /** Names of the daemons currently running. */\n list: () => string[]\n }\n\n /**\n * The bound workspace's remote Data Bank (read/write; daemon functions can\n * also subscribe to changes via `bank.subscribe`). Every method throws\n * until credentials are stored via `bricks buttress bank-key` (run on\n * this host, then restart the server).\n */\n bank: {\n /** List properties, optionally filtered. */\n list: (options?: {\n /** Match against definition title/description or tags. */\n keyword?: string\n meta?: ButtressBankPropertyMeta\n /** Restrict to these property ids. */\n ids?: string[]\n }) => Promise<ButtressBankProperty[]>\n\n /** One property, or null when it does not exist. */\n get: (propertyId: string) => Promise<ButtressBankProperty | null>\n\n /**\n * Create or update properties (upsert by default). Updates notify\n * subscribed devices unless `dontNotify` is set.\n */\n update: (\n properties: ButtressBankPropertyInput[],\n options?: { dontNotify?: boolean },\n ) => Promise<ButtressBankProperty[]>\n\n /** Delete a property. Resolves false when it did not exist. */\n remove: (propertyId: string) => Promise<boolean>\n\n /**\n * Watch property ids for remote changes. Only available inside daemon\n * functions (throws elsewhere); closed automatically when the daemon\n * stops. The connection is shared and reconnects on its own \u2014 a network\n * drop never stops the daemon.\n */\n subscribe: (\n propertyIds: string[],\n onChange: (properties: ButtressBankProperty[]) => unknown,\n ) => { close: () => void }\n }\n\n fetch: typeof fetch\n /** Server-side log, prefixed with the function name. */\n log: (...args: unknown[]) => void\n /** Emit a progress event. Delivered only to SSE callers; a no-op otherwise. */\n emit: (event: string, data?: unknown) => void\n /** Aborted when the call times out or the caller disconnects. */\n signal: AbortSignal\n env: Record<string, string | undefined>\n /**\n * The `[functions.config]` table from the server config. Read once at\n * server start \u2014 unlike function files, config edits need a restart.\n */\n config: Record<string, any>\n /** Per-call scratch directory, created on first access. */\n tempDir: string\n /**\n * Download URL path (`/functions/files/...`) for a file inside `tempDir`;\n * relative input resolves against it. Callers fetch the URL with the same\n * auth as any function call. Scratch dirs are swept after ~24h.\n */\n fileUrl: (target: string) => string\n /** Absolute path of this functions directory. */\n dir: string\n /** Helper libraries: _, lodash, moment, math, mathjs, voca, chroma, json5, qs, bytes, ms, nanoid, md5. */\n libs: Record<string, any>\n}\n\ntype ButtressFunctionMeta = {\n /** Shown to MCP clients in `tools/list`. */\n description?: string\n /** JSON Schema for the input object, passed to MCP verbatim. */\n parameters?: Record<string, any>\n /**\n * Deadline for this function: ms, or a duration string like \"10m\".\n * Ignored for daemons \u2014 a daemon has no deadline.\n */\n timeout?: number | string\n /**\n * `true` declares this file as a daemon: a long-lived background\n * function. Its default export runs once, with a ButtressDaemonContext as\n * its only argument, and stays alive \u2014 everything registered there\n * (`setInterval` timers, `bank.subscribe` subscriptions, `onEvent`\n * handlers) keeps firing until the file changes or the server stops.\n * A daemon is not an MCP tool and cannot be called over HTTP.\n */\n daemon?: boolean\n}\n\n/** An event another local function sent via `context.daemons.emit`. */\ntype ButtressDaemonEmittedEvent = {\n event: string\n data?: unknown\n /** Name of the local function (or daemon) that emitted it. */\n source: string\n}\n\n/**\n * What a daemon's default export receives: the full function context plus\n * lifetime APIs. `context.signal` aborts when the daemon stops (file\n * changed/removed, or server shutdown); an optional cleanup function\n * *returned* by the handler also runs at that point.\n */\ntype ButtressDaemonContext = ButtressFunctionContext & {\n /**\n * A managed `setInterval`: the callback keeps firing until cleared or\n * the daemon stops. A callback that throws is logged (and shown on\n * /status) \u2014 it never stops the timer or the daemon.\n */\n setInterval: (callback: () => unknown, ms: number) => unknown\n clearInterval: (handle: unknown) => void\n /** Receive events other local functions send via `context.daemons.emit`. */\n onEvent: (handler: (event: ButtressDaemonEmittedEvent) => unknown) => void\n}\n\n// --- Custom auth ------------------------------------------------------------\n// Drop an `_auth.ts` into this directory to gate the /functions endpoints\n// with your own logic. It exports the same shape as a function file:\n//\n// export const meta: ButtressAuthMeta = { mode: 'both' }\n// export default async function (\n// request: ButtressAuthRequest,\n// context: ButtressAuthContext,\n// ): Promise<ButtressAuthResult> { ... }\n//\n// While an `_auth` file exists but fails to load, every call is rejected.\n\ntype ButtressAuthMeta = {\n /**\n * 'both' (default): runs after the built-in workspace auth passes, as an\n * extra gate. 'override': replaces workspace auth \u2014 this function is the\n * only authority (a presented workspace token is still verified into\n * `request.workspaceAuth` so you can choose to honor it).\n */\n mode?: 'override' | 'both'\n}\n\ntype ButtressAuthRequest = {\n method: string\n path: string\n /** Function name for `GET`/`POST /functions/<name>`; undefined for list and MCP. */\n name?: string\n headers: Record<string, string | undefined>\n query: Record<string, string | undefined>\n /** Raw bearer token (Authorization header or `?token=`), if any. */\n token: string | null\n workspaceAuth: {\n /** Whether this server is bound to a workspace. */\n bound: boolean\n /** Whether the caller presented a valid workspace access token. */\n authenticated: boolean\n identity: {\n workspaceId: string\n subjectType: 'ws' | 'dev'\n subjectId: string\n jti?: string\n exp: number\n } | null\n }\n}\n\ntype ButtressAuthContext = {\n /** Server-side log, prefixed with \"_auth\". */\n log: (...args: unknown[]) => void\n fetch: typeof fetch\n env: Record<string, string | undefined>\n /** The `[functions.config]` table, same as `context.config` in functions. */\n config: Record<string, any>\n /** Absolute path of this functions directory. */\n dir: string\n /** Same helper libraries functions get. */\n libs: Record<string, any>\n}\n\n/** Only `true` (or `{ ok: true }`) allows the request; anything else denies. */\ntype ButtressAuthResult =\n | boolean\n | {\n ok: boolean\n /** Response status for a denial, 400-499 (default 403). */\n status?: number\n /** Message returned to the caller on denial. */\n error?: string\n }\n\n// The only non-builtin packages the local-function loader accepts. These\n// declarations keep editor support working when this directory is outside the\n// server package's own node_modules resolution tree.\ndeclare module 'sqlite3' {\n type SqliteCallback = (error: Error | null) => void\n\n class Database {\n constructor(filename: string, callback?: SqliteCallback)\n run(sql: string, ...params: any[]): this\n all<T = Record<string, any>>(\n sql: string,\n ...params: [...any[], (error: Error | null, rows: T[]) => void]\n ): this\n exec(sql: string, callback?: SqliteCallback): this\n loadExtension(filename: string, callback?: SqliteCallback): this\n close(callback?: SqliteCallback): void\n }\n\n const sqlite3: { Database: typeof Database }\n export { Database }\n export default sqlite3\n}\n\ndeclare module 'sqlite-vec' {\n export function getLoadablePath(): string\n export function load(database: { loadExtension(path: string): unknown }): void\n}\n";
14
14
  export declare const TSCONFIG_TEMPLATE = "{\n // Editor support for Buttress local functions.\n // Install @types/node here for typings on \"node:*\" imports.\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Bundler\",\n \"lib\": [\"ES2023\"],\n \"strict\": true,\n \"noEmit\": true,\n \"allowJs\": true,\n \"skipLibCheck\": true\n },\n \"include\": [\"**/*.ts\", \"**/*.js\"]\n}\n";
15
15
  export declare const EXAMPLE_TEMPLATE = "// Example Buttress local function.\n//\n// Rename (or copy) this file to expose it: files starting with \"_\" are\n// ignored. The tool name is the file name \u2014 \"video-duration.ts\" becomes the\n// tool \"video-duration\", callable over MCP, at POST /functions/video-duration\n// with a JSON body, and at GET /functions/video-duration?path=... with the\n// input in the query string.\n\nexport const meta: ButtressFunctionMeta = {\n description: 'Report the duration of a video file using ffprobe',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Absolute path to a video file' },\n },\n required: ['path'],\n },\n timeout: '2m',\n}\n\nexport default async function (\n { path }: { path: string },\n context: ButtressFunctionContext,\n): Promise<{ seconds: number }> {\n const { code, stdout, stderr } = await context.spawn('ffprobe', [\n '-v',\n 'error',\n '-show_entries',\n 'format=duration',\n '-of',\n 'default=noprint_wrappers=1:nokey=1',\n path,\n ])\n\n if (code !== 0) throw new Error(`ffprobe failed (${code}): ${stderr}`)\n\n return { seconds: Number(String(stdout).trim()) }\n}\n";
16
16
  export declare const EXAMPLE_DAEMON_TEMPLATE = "// Example Buttress daemon function.\n//\n// Rename (or copy) this file to activate it: files starting with \"_\" are\n// ignored. A file with `meta.daemon = true` runs as a daemon \u2014 a\n// long-lived background function. It is not exposed as an MCP tool or\n// endpoint; its live status shows on /status.\n//\n// The default export runs ONCE when the daemon starts, and everything it\n// registers on the context keeps running after it returns:\n//\n// context.setInterval(cb, ms) periodic work (cleared on stop;\n// a throwing callback never stops it)\n// context.bank.subscribe(ids, cb) Data Bank change notifications\n// (needs `bricks buttress bank-key`)\n// context.onEvent(cb) events from other local functions:\n// context.daemons.emit(name, event, data)\n//\n// The daemon stops when this file changes or the server shuts down:\n// context.signal aborts, timers and subscriptions are cleaned up, and a\n// cleanup function returned here gets a final (bounded) run.\n\nexport const meta: ButtressFunctionMeta = {\n description: 'Log a heartbeat and react to Data Bank changes',\n daemon: true,\n}\n\nexport default async function (context: ButtressDaemonContext) {\n let ticks = 0\n\n context.setInterval(() => {\n ticks += 1\n context.log(`heartbeat #${ticks}`)\n }, 60_000)\n\n // Requires stored Bank credentials \u2014 uncomment after `bricks buttress bank-key`:\n // context.bank.subscribe(['some-property-id'], (properties) => {\n // for (const property of properties) {\n // context.log(`bank property changed: ${property.propertyId}`)\n // }\n // })\n\n context.onEvent(({ event, data, source }) => {\n context.log(`event \"${event}\" from ${source}`, data)\n })\n\n context.log('daemon started')\n return () => context.log(`stopping after ${ticks} tick(s)`)\n}\n";