@chatpanel/events 0.432.2 → 0.435.0

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.
@@ -0,0 +1,4 @@
1
+ import{listRows as be,findRow as X,rowsFor as Se,breadcrumb as _,linkToRow as ke,setValue as $e,effectiveValue as ve,describeValue as Ne,gateOf as Y}from"./settings-registry.js";import{makeDispatchProvider as Oe}from"./tool-dispatch.js";import{exprLit as S}from"./a2ui-tool-cards.js";const oe="settings",z="settings_find",H="settings_change",ie="settings_run",K=Object.freeze({allow:"chap.settings.allow",deny:"chap.settings.deny",open:"chap.settings.open"}),M=6,xe=new Set(["bridge-url","bridge-token","gw-url","gw-token","ch-token"]),Te=new Set(["internal-restore","license-deactivate","backup-import","btn-subscribe-pro","btn-check-purchase","btn-restore","gw-pro-activate","link-pair","link-partner-pair","ch-pair","ch-connect","drive-connect"]),Ce=Object.freeze({"memory-clear":"forget","activity-clear":"clear","obs-clear":"clear","usage-clear":"clear","reset-skills":"reset","drive-disconnect":"disconnect","ch-disconnect":"disconnect","drive-backup-restore":"restore","drive-backup-restore-all":"restore"}),_e=new Set(["local-recheck","bridge-test","priv-ner-check","gw-check","gw-ner-check","gw-logs-refresh","rt-recheck","obs-refresh","check-updates","plugins-refresh","skill-sources-refresh"]),se=new Set(["toggle","select","text","number","textarea","picker"]),Ee=500,Ae=8e3;function Re(e,{bound:t={},actions:s={},choices:n=null}={}){const o=e?.row;return!o||o.composer?"none":o.type==="secret"||xe.has(o.id)||o.consent?"open":e.page?.id==="plan"||e.group?.id==="privacy"&&!(o.stricter&&se.has(o.type))?o.type==="status"?"read":"open":o.type==="status"?"read":o.type==="link"?"open":o.type==="action"?Te.has(o.id)?"open":typeof s[o.id]?.run=="function"?"run":"open":typeof s[o.id]?.run=="function"?"run":se.has(o.type)?o.store==="local"||o.store==="gateway"||!o.key?typeof t[o.id]?.write=="function"?"change":"open":o.type==="picker"&&typeof n!="function"?"open":"change":"open"}const A=e=>String(e??"").trim().toLowerCase(),Je=new Set(["true","on","yes","1","enable","enabled"]),je=new Set(["false","off","no","0","disable","disabled"]);function ae(e,t){return e.type==="secret"?t?"set":"not set":Ne(e,t)||(t==null||t===""?"not set":String(t))}function Ie(e,t,{options:s=e.options}={}){switch(e.type){case"toggle":{if(typeof t=="boolean")return{ok:!0,value:t};const n=A(t);return Je.has(n)?{ok:!0,value:!0}:je.has(n)?{ok:!0,value:!1}:{ok:!1,why:`"${e.label}" is on or off`}}case"select":case"picker":{const n=Array.isArray(s)?s:[];if(!n.length)return{ok:!1,why:`there are no choices for "${e.label}" here`};const o=n.find(l=>String(l[0])===String(t))||n.find(l=>A(l[0])===A(t)||A(l[1])===A(t));return o?{ok:!0,value:o[0]}:{ok:!1,why:`"${t}" is not one of the choices for "${e.label}": ${n.slice(0,12).map(l=>l[1]||l[0]).join(", ")}`}}case"number":{const n=typeof t=="number"?t:Number(String(t??"").trim());return!Number.isFinite(n)||String(t??"").trim()===""?{ok:!1,why:`"${e.label}" takes a number`}:n<0?{ok:!1,why:`"${e.label}" cannot be negative`}:Number.isFinite(e.min)&&n<e.min?{ok:!1,why:`"${e.label}" is at least ${e.min}`}:Number.isFinite(e.max)&&n>e.max?{ok:!1,why:`"${e.label}" is at most ${e.max}`}:{ok:!0,value:n}}case"text":case"textarea":{if(typeof t!="string"&&typeof t!="number")return{ok:!1,why:`"${e.label}" takes text`};const n=String(t),o=e.type==="text"?Ee:Ae;return n.length>o?{ok:!1,why:`"${e.label}" takes at most ${o} characters`}:/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(n)||e.type==="text"&&/[\r\n]/.test(n)?{ok:!1,why:`"${e.label}" takes plain text on one line`}:{ok:!0,value:e.type==="text"?n.trim():n}}default:return{ok:!1,why:`"${e.label}" is not set by value`}}}function Le(e,t,s){const n=e?.stricter;if(!n)return!1;if(n===!0){const b=t==null?e.default===!0:t===!0;return s===!0||s===b}const o=Array.isArray(n.order)?n.order.map(String):[],l=o.indexOf(String(t==null||t===""?n.unset:t)),p=o.indexOf(String(s));return l!==-1&&p!==-1&&p>=l}const f=(e,t=160)=>{const s=String(e??"");return s.length>t?`${s.slice(0,t-1)}…`:s};function ce({title:e,items:t=[],reason:s="",ticket:n="",allowLabel:o="Apply",note:l="",mustType:p=""}){const b=t.map(y=>({l:f(y.label,60),w:f(y.where,80),f:f(y.from,60),t:f(y.to,80)}));return[`$/c = ${S({title:f(e,80),reason:s?`Chap says: ${f(s,200)}`:"",note:f(l,200),warn:p?"This cannot be undone":"",typeLabel:p?`Type “${p}” to confirm`:""})}`,...p?['$/typed = ""']:[],`$/items = ${S(b)}`,'head = Row([Icon("settings"), Text($/c/title, "h3")])','items = List(_template($/items, Column([Text($l), Text($w, "caption"), Row([Badge($f), Text("→"), Badge($t, "info")])])))',...s?['why = Text($/c/reason, "caption")']:[],...l?['note = Text($/c/note, "caption")']:[],...p?['warn = Badge($/c/warn, "bad")',"typed = TextField($/c/typeLabel, $/typed, "+S(p)+', "shortText")']:[],`allow = Button(Text(${S(o)}), "primary", Event(${S(K.allow)}, {ticket: ${S(n)}${p?", typed: $/typed":""}}))`,`deny = Button(Text("Not now"), _, Event(${S(K.deny)}, {ticket: ${S(n)}}))`,`root = Card(Column([head, items, ${s?"why, ":""}${l?"note, ":""}${p?"warn, typed, ":""}Row([allow, deny])]))`].join(`
2
+ `)}function Fe({items:e=[],why:t=""}){const s=e.slice(0,M).map(o=>({l:f(o.label,60),w:f(o.where,80),id:o.id}));return[`$/c = ${S({why:f(t||"You change these in Settings yourself.",200)})}`,`$/items = ${S(s)}`,'head = Row([Icon("settings"), Text("In Settings", "h3")])',`items = List(_template($/items, Row([Column([Text($l), Text($w, "caption")]), Button(Text("Open"), "borderless", Event(${S(K.open)}, {row: $id}))])))`,'root = Card(Column([head, Text($/c/why, "caption"), items]))'].join(`
3
+ `)}const Pe=new Set("the a an and or but to of in on at by for with from into onto my me i you your we our it its this that these those is are was were be been am do does did can could would should will shall may might must please hey chap just also so then than there here what which who whom how why when where all any some each every not no yes ok okay get got make made let use using want need like".split(" ")),qe=e=>e.length>4&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,L=e=>String(e||"").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!Pe.has(t)).map(qe);let Q=null;function De(e){const{row:t}=e;return{name:new Set([t.label,...t.synonyms||[]].flatMap(L)),names:[t.label,...t.synonyms||[]].map(L).filter(s=>s.length),opts:new Set((t.options||[]).flatMap(s=>L(s[1]))),place:new Set([e.page.label,e.section.label].flatMap(L))}}function Ge(){return Q||(Q=new Map(be().map(e=>[e.row.id,De(e)]))),Q}function Ue(e,t){let s=e.indexOf(t[0]);for(;s!==-1;){let n=s,o=!0;for(const l of t.slice(1))if(e[n+1]===l)n+=1;else if(e[n+2]===l)n+=2;else{o=!1;break}if(o)return!0;s=e.indexOf(t[0],s+1)}return!1}function le(e,{rows:t=null,min:s=10,limit:n=3}={}){const o=L(e),l=[...new Set(o)];if(!l.length)return[];const p=t?new Set(t):null,b=[];for(const[x,y]of Ge()){if(p&&!p.has(x))continue;let v=0,F=0;for(const k of l){const E=y.name.has(k)?3:y.opts.has(k)?2:y.place.has(k)?1:0;E&&(v+=E,F+=1)}const R=y.names.filter(k=>Ue(o,k));R.length&&(v+=4);const T=R.some(k=>k.length>1);v>=s&&(F>=2||T)&&b.push({id:x,score:v})}return b.sort((x,y)=>y.score-x.score).slice(0,n)}const Me={name:z,description:"Look up Chap's own settings — models and which model does what, voices, search engines, backups, updates, privacy, everything on the Settings pages — and their current values.",parameters:{type:"object",properties:{query:{type:"string",description:'What the setting is about, in a few words ("title model", "dark mode", "backup").'}},required:["query"]},annotations:{readOnlyHint:!0}},Ve={name:H,description:"Propose a change to one or more of Chap's settings. The person sees a card and decides; nothing changes until they apply it.",parameters:{type:"object",properties:{changes:{type:"array",description:`Up to ${M}, applied together on one card.`,items:{type:"object",properties:{id:{type:"string",description:"The setting id from settings_find."},value:{description:"The new value: true/false, a choice's value, a number or text."}},required:["id","value"]}},reason:{type:"string",description:"One short sentence the person reads on the card: why this change."}},required:["changes"]}},Be={name:ie,description:"Run one of Chap's settings actions (back up now, check for updates, download a model…). One that changes something shows the person a card first.",parameters:{type:"object",properties:{id:{type:"string",description:"The action id from settings_find."},args:{type:"object",description:"The action's own arguments, when settings_find lists any."},reason:{type:"string",description:"One short sentence the person reads on the card."}},required:["id"]}},We='Chap\'s own settings: `settings_find` looks them up with their values and what you may do with each (`can`): "change" → propose with `settings_change` (the person decides on a card); "run" → `settings_run`; "open" → the person changes it in Settings — say so, Chap shows them the way. Never claim a setting changed unless the result says it did.';let Xe=0;const he=e=>(typeof e=="string"?e:e?.decision)==="allow"?"allow":"deny";function Ke({client:e="browser",read:t=()=>({}),write:s=null,bound:n={},choices:o=null,actions:l={},runtime:p=()=>({}),confirm:b=null,record:x=null,newTicket:y=()=>`s${Date.now().toString(36)}${Xe+=1}`}={}){const v=new Set(Se(e)),F={bound:n,actions:l,choices:o},R=r=>{const h=X(String(r||""));return h&&v.has(h.row.id)?h:null},T=r=>Re(r,F),k=(r,h)=>n[r.row.id]?.read?n[r.row.id].read():ve(h,r.row),E=(r,h)=>r.row.type==="picker"?typeof o=="function"?o(r.row.id,h):null:r.row.options,V=r=>{try{x?.(r)}catch{}};function ue(r,h){const g=T(r),a=g==="change"?E(r,h):null,d=Y(r.row,p()||{});return{id:r.row.id,label:r.row.label,where:_(r),...r.row.key||n[r.row.id]?.read?{value:ae(r.row,k(r,h))}:{},can:g,type:r.row.type,...a?.length?{choices:a.slice(0,12).map($=>$[0])}:{},...l[r.row.id]?.args?{args:l[r.row.id].args}:{},...d.ok?{}:{blocked:d.reason},...r.row.pro?{pro:!0}:{},...r.row.help?{help:f(r.row.help,140)}:{}}}function de({query:r=""}={}){const h=t()||{},g=le(r,{rows:[...v],min:3,limit:8}).map(a=>a.id);return g.length?JSON.stringify({matches:g.map(a=>ue(X(a),h)).filter(a=>a.can!=="none")}):JSON.stringify({matches:[],hint:"Nothing matched — try other words for the setting (what it does, or where it lives in Settings)."})}const Z=(r,h)=>({text:JSON.stringify({changed:!1,open:r.map(g=>g.id),say:`${h} Chap shows the person a card that opens it in Settings; do not say it changed.`}),card:{lang:"a2ui",source:Fe({items:r,why:h})}});async function pe({changes:r,reason:h="",id:g,value:a}={}){const d=Array.isArray(r)?r:g?[{id:g,value:a}]:[];if(!d.length)return JSON.stringify({error:'No change given. Pass {"changes":[{"id":"<from settings_find>","value":…}]}.'});if(d.length>M)return JSON.stringify({error:`At most ${M} changes on one card.`});const $=t()||{},J=p()||{},w=[],u=[],m=[];for(const c of d){const i=R(c?.id);if(!i){u.push({id:c?.id,why:"no such setting here — look it up with settings_find"});continue}const B=T(i);if(B==="open"){m.push({id:i.row.id,label:i.row.label,where:_(i)});continue}if(B!=="change"){u.push({id:i.row.id,why:B==="run"?"this is an action — use settings_run":"this one is shown, not set"});continue}const D=Y(i.row,J);if(!D.ok){u.push({id:i.row.id,why:`${D.reason}${D.fix?` (${D.fix})`:""}`});continue}const C=Ie(i.row,c.value,{options:E(i,$)});if(!C.ok){u.push({id:i.row.id,why:C.why});continue}const G=k(i,$),W=(G==null||G==="")&&i.row.stricter?.unset!==void 0?i.row.stricter.unset:G;if(JSON.stringify(W)===JSON.stringify(C.value))continue;if(i.group?.id==="privacy"&&!Le(i.row,W,C.value)){m.push({id:i.row.id,label:i.row.label,where:_(i)}),u.push({id:i.row.id,why:"that loosens privacy — the person changes it in Settings"});continue}const te=E(i,$);if(te?.find(U=>String(U[0])===String(C.value))?.[2]?.leaves===!0){m.push({id:i.row.id,label:i.row.label,where:_(i)}),u.push({id:i.row.id,why:"that choice sends your words off this device"});continue}const ne=U=>{const re=te?.find(me=>String(me[0])===String(U));return re?re[1]:ae(i.row,U)};w.push({e:i,value:C.value,item:{id:i.row.id,label:i.row.label,where:_(i),from:ne(W),to:ne(C.value)}})}if(m.length&&!w.length)return Z(m,u.length?`Not changed from the chat: ${u.map(c=>c.why).join("; ")}.`:"These are changed by the person in Settings, not from the chat.");if(!w.length)return u.length?JSON.stringify({changed:!1,refused:u}):JSON.stringify({changed:!1,unchanged:!0,say:"Already set that way — nothing to change."});if(typeof b!="function"||typeof s!="function"&&w.some(c=>!n[c.e.row.id]?.write))return JSON.stringify({changed:!1,error:"Settings cannot be changed from this chat here — the person can change them in Settings."});const j=y(),I=w.map(c=>c.item.id),N=w.length===1?`Change ${w[0].item.label}?`:`Change ${w.length} settings?`,O=w.map(c=>`${c.item.label}: ${c.item.from} → ${c.item.to}`).join(`
4
+ `),P=m.length?`Not on this card — change in Settings: ${m.map(c=>c.label).join(", ")}.`:"";let q="deny";try{q=he(await b({kind:"change",title:N,detail:O,reason:f(h,200),card:ce({title:N,items:w.map(c=>c.item),reason:h,ticket:j,note:P}),ticket:j,ids:I}))}catch{q="deny"}if(V({kind:"change",ids:I,decision:q==="allow"?"allow":"deny"}),q!=="allow")return JSON.stringify({changed:!1,declined:I,say:"The person kept their settings as they were. Do not propose this again unless they ask."});try{const c=w.filter(i=>!n[i.e.row.id]?.write);c.length&&await s(c.map(i=>({id:i.e.row.id,key:i.e.row.key,value:i.value})));for(const i of w)n[i.e.row.id]?.write&&await n[i.e.row.id].write(i.value)}catch(c){return JSON.stringify({changed:!1,error:`Could not save: ${f(c?.message||c,160)}`})}return JSON.stringify({changed:!0,now:w.map(c=>({id:c.item.id,label:c.item.label,value:c.item.to})),...u.length?{refused:u}:{},...m.length?{open:m.map(c=>c.id)}:{}})}async function fe({id:r,args:h={},reason:g=""}={}){const a=R(r);if(!a)return JSON.stringify({error:"No such action here — look it up with settings_find."});const d=T(a);if(d==="open")return Z([{id:a.row.id,label:a.row.label,where:_(a)}],`"${a.row.label}" is done by the person in Settings, not from the chat.`);if(d!=="run")return JSON.stringify({error:d==="change"?"This is a setting — propose it with settings_change.":"This one is shown, not run."});const $=Y(a.row,p()||{});if(!$.ok)return JSON.stringify({ran:!1,why:`${$.reason}${$.fix?` (${$.fix})`:""}`});const J=l[a.row.id],w=h&&typeof h=="object"?h:{};if(_e.has(a.row.id))V({kind:"run",ids:[a.row.id],decision:"look"});else{if(typeof b!="function")return JSON.stringify({ran:!1,error:"Actions cannot be run from this chat here — the person can run it in Settings."});let u="";try{u=J.preview?String(J.preview(w)||""):""}catch{u=""}const m=y(),j=`${a.row.label}?`,I={id:a.row.id,label:a.row.label,where:_(a),from:"now",to:f(u||a.row.help||a.row.label,80)},N=Ce[a.row.id]||"";let O="deny";try{const P=await b({kind:"run",title:j,detail:u||a.row.help||"",reason:f(g,200),card:ce({title:j,items:[I],reason:g,ticket:m,allowLabel:a.row.label,mustType:N}),ticket:m,ids:[a.row.id],...N?{mustType:N}:{}});O=he(P),N&&O==="allow"&&A(P?.typed)!==N&&(O="deny")}catch{O="deny"}if(V({kind:"run",ids:[a.row.id],decision:O==="allow"?"allow":"deny"}),O!=="allow")return JSON.stringify({ran:!1,declined:a.row.id,say:"The person chose not to. Do not ask again unless they do."})}try{const u=await J.run(w);return JSON.stringify({ran:!0,id:a.row.id,result:f(typeof u=="string"?u:JSON.stringify(u??""),1500)})}catch(u){return JSON.stringify({ran:!1,id:a.row.id,error:f(u?.message||u,200)})}}const ee=Object.keys(l).some(r=>typeof l[r]?.run=="function"&&v.has(r)),ge=[Me,Ve,...ee?[Be]:[]],we=Oe({name:oe,description:"Chap's own settings — look up, propose a change (the person approves), run an action.",resident:We,inner:{specs:ge,async execute(r,h={}){return r===z?de(h):r===H?pe(h):r===ie&&ee?fe(h):JSON.stringify({error:`Unknown settings action: ${r}`})}}});function ye(r,{small:h=!1}={}){const g=le(r,{rows:[...v],min:h?12:10,limit:3}).map(d=>X(d.id)).filter(d=>d&&T(d)!=="none");return g.length?`[Chap] This may be about Chap's own settings: ${g.map(d=>`${d.row.label} (\`${d.row.id}\`, ${T(d)})`).join("; ")}. Through \`tools\`: {"action":"${z}","args":{"query":"…"}} for values and choices, then {"action":"${H}","args":{"changes":[{"id":"…","value":…}]}} — the person approves on a card.`:""}return{...we,id:oe,quiet:!0,hint:ye}}const Qe=e=>ke(e);function Ze(e,t=[]){return(t||[]).filter(s=>s?.key).reduce((s,n)=>$e(s,n.key,n.value),e||{})}export{_e as LOOK_ONLY_ACTIONS,M as MAX_CHANGES,H as SETTINGS_CHANGE,K as SETTINGS_EVENTS,z as SETTINGS_FIND,oe as SETTINGS_GROUP,ie as SETTINGS_RUN,Ce as TYPE_TO_RUN,Ze as applyChanges,ce as changeCard,Re as chatReachOf,Ie as coerceValue,Le as isStricter,Fe as openCard,le as rankForMessage,Ke as settingsChatProvider,Qe as settingsLinkFor,ae as shownValue};