@chatpanel/gateway 0.99.0 → 0.103.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.
Files changed (63) hide show
  1. package/native/darwin-arm64/chatpanel-apple-model +0 -0
  2. package/package.json +3 -3
  3. package/src/agent.js +1 -3
  4. package/src/budget.js +1 -1
  5. package/src/capability-adapters.js +1 -1
  6. package/src/capability-embedded.js +1 -1
  7. package/src/capability-endpoints.js +1 -1
  8. package/src/capability-providers.js +1 -3
  9. package/src/capability-proxy.js +1 -1
  10. package/src/capability-tools.js +1 -3
  11. package/src/cloudevents.js +1 -4
  12. package/src/config.js +1 -1
  13. package/src/coreml-stt-engine.js +3 -0
  14. package/src/cross-encoder.js +1 -1
  15. package/src/diarize-engine.js +1 -1
  16. package/src/embedded-models.js +1 -1
  17. package/src/embedder.js +1 -0
  18. package/src/engine-pacer.js +1 -1
  19. package/src/engine.js +1 -1
  20. package/src/event-stats.js +1 -1
  21. package/src/event-sync.js +1 -1
  22. package/src/event.js +1 -1
  23. package/src/extract/handler.js +1 -1
  24. package/src/extract-capability.js +1 -5
  25. package/src/extraction.js +1 -4
  26. package/src/gate.js +1 -1
  27. package/src/inference-lane.js +1 -0
  28. package/src/job.js +1 -5
  29. package/src/kb-store.js +4 -0
  30. package/src/kb.js +2 -0
  31. package/src/knowledge.js +1 -3
  32. package/src/mcp.js +23 -20
  33. package/src/memory.js +1 -2
  34. package/src/model-ledger.js +1 -1
  35. package/src/ner-engine.js +1 -1
  36. package/src/observability.js +1 -1
  37. package/src/openai.js +2 -2
  38. package/src/order.js +1 -1
  39. package/src/project.js +1 -1
  40. package/src/providers.js +1 -1
  41. package/src/read-document.js +1 -10
  42. package/src/recruit.js +1 -4
  43. package/src/ref.js +1 -1
  44. package/src/rrf.js +1 -1
  45. package/src/scorecard.js +1 -1
  46. package/src/search-api.js +1 -1
  47. package/src/search-outcome.js +1 -1
  48. package/src/search-searxng.js +1 -1
  49. package/src/segment-engine.js +1 -0
  50. package/src/serp-anchors.js +1 -1
  51. package/src/server.js +32 -32
  52. package/src/site-policy.js +1 -1
  53. package/src/structured.js +1 -4
  54. package/src/stt-engine.js +1 -1
  55. package/src/stt-models.js +1 -1
  56. package/src/subject-kinds.js +1 -1
  57. package/src/subject-name.js +1 -1
  58. package/src/team-board.js +1 -6
  59. package/src/team-record.js +1 -1
  60. package/src/team.js +1 -1
  61. package/src/version.js +1 -1
  62. package/src/web-search-tool.js +1 -19
  63. package/src/web-search.js +1 -1
@@ -1 +1 @@
1
- const g=Object.freeze({perHost:2,total:4});function p(t,s){if(t==null)return null;const l=String(t).trim();if(!l)return null;if(/^\d+$/.test(l))return Number(l)*1e3;const n=Date.parse(l);return Number.isNaN(n)?null:Math.max(0,n-s)}function y({now:t=()=>Date.now(),perHost:s=g.perHost,total:l=g.total}={}){const n=new Map;let a=0;const r=[],u=new Map,c=e=>a<l&&(n.get(e)||0)<s,d=e=>{n.set(e,(n.get(e)||0)+1),a+=1;let i=!1;return()=>{i||(i=!0,n.set(e,n.get(e)-1),n.get(e)===0&&n.delete(e),a-=1,b())}},b=()=>{for(let e=0;e<r.length;e++)if(c(r[e].host)){const{host:i,resolve:o}=r.splice(e,1)[0];if(o(d(i)),e-=1,a>=l)break}};return{acquire(e){const i=String(e||"").toLowerCase();return c(i)?Promise.resolve(d(i)):new Promise(o=>r.push({host:i,resolve:o}))},noteRetryAfter(e,i){const o=p(i,t());if(o==null||o<=0)return 0;const f=Math.min(o,15*6e4);return u.set(String(e||"").toLowerCase(),t()+f),f},holdFor(e){const i=u.get(String(e||"").toLowerCase());if(!i)return 0;const o=i-t();return o<=0?(u.delete(String(e||"").toLowerCase()),0):o},snapshot(){return{inFlight:Object.fromEntries(n),total:a,waiting:r.length,holds:u.size}}}}const w=200,m=/\b(paywall|subscribe to (continue|read)|subscription required|subscribers? only|become a (member|subscriber)|to continue reading|unlock this (article|story)|premium (article|content))\b/i,h=/(type=["']password["']|\b(sign in|log in|login) to (continue|view|read)\b|\bplease (sign|log) in\b|\byou must be logged in\b)/i;function T({status:t=200,headers:s={},html:l="",words:n=0}={}){const a=r=>{if(!s)return null;if(typeof s.get=="function")return s.get(r);const u=Object.keys(s).find(c=>c.toLowerCase()===r.toLowerCase());return u?s[u]:null};if(t===429||t===503){const r=a("retry-after");return{reason:"rate_limited",detail:r?`HTTP ${t}, Retry-After ${r}`:`HTTP ${t}`}}if(t===401||t===402||t===403)return{reason:t===402?"paywall":"login",detail:`HTTP ${t}`};if(n<w){const r=String(l||"");if(m.test(r))return{reason:"paywall",detail:"a subscription wall with little readable text"};if(h.test(r))return{reason:"login",detail:"a login form with little readable text"}}return null}function x(t){if(!t)return"";switch(t.reason){case"login":return"could not be read: the page is behind a login";case"paywall":return"could not be read: the page is behind a paywall";case"rate_limited":return"could not be read: the site asked us to slow down";case"robots":return"was not read: the site's robots.txt disallows it";case"tdm":return"was not read: the site reserves its content from automated mining";default:return"could not be read"}}export{g as HOST_BUDGET_DEFAULTS,w as THIN_PAGE_WORDS,y as createHostBudget,x as describeRestriction,p as parseRetryAfter,T as restrictionOf};
1
+ export*from"@chatpanel/events/site-policy.js";
package/src/structured.js CHANGED
@@ -1,4 +1 @@
1
- class m extends Error{constructor(t,r){super(r),this.name="StructuredError",this.code=t}}const P=Object.freeze(["string","number","integer","boolean","enum","string[]","number[]","object[]"]),E=/^(?:none|n\/a|na|nothing|no|null|nil|empty|no results?|nothing found|no request|-{1,3}|\.)\s*[.!]?$/i,K=/^(?:(?:sure|certainly|of course|okay|ok|got it|here(?:'s| is)(?: the)?(?: \w+)?|the (?:json|answer|result|output)(?: is)?|json|output|answer|result)\s*[:.!,-]*\s*)+/i,b=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ne=(e,t)=>e.length>t?`${e.slice(0,t)}`:e;function re(e={}){const t=String(e.name||"").trim();if(!t)throw new m("no-name","a schema needs a name");if(!b(e.fields)||!Object.keys(e.fields).length)throw new m("no-fields",`schema ${t} declares no fields`);const r={};for(const[n,i]of Object.entries(e.fields))r[n]=L(t,n,i);if(e.nothingIf!=null&&!(e.nothingIf instanceof RegExp))throw new m("bad-nothing",`schema ${t}: nothingIf must be a RegExp`);if(e.fallback!=null&&e.fallback!=="lines"&&typeof e.fallback!="function")throw new m("bad-fallback",`schema ${t}: fallback must be 'lines' or a function`);return Object.freeze({name:t,purpose:String(e.purpose||"").trim(),fields:Object.freeze(r),order:Object.freeze(Object.keys(r)),nothing:e.nothing??null,nothingIf:e.nothingIf??null,fallback:e.fallback??null,strictRequired:e.strictRequired!==!1})}function L(e,t,r){const n=typeof r=="string"?{type:r}:{...r||{}},i=String(n.type||"string");if(!P.includes(i))throw new m("bad-type",`schema ${e}.${t}: unknown type ${JSON.stringify(i)}`);if(i==="enum"){const l=(n.values||[]).map(o=>String(o));if(!l.length)throw new m("bad-enum",`schema ${e}.${t}: enum with no values`);if(n.default!=null&&!l.includes(String(n.default)))throw new m("bad-default",`schema ${e}.${t}: default ${JSON.stringify(n.default)} is not one of its values`);n.values=Object.freeze(l);const s=new Map;for(const o of l)s.set(o.toLowerCase(),o);for(const[o,u]of Object.entries(n.aliases||{})){if(!l.includes(String(u)))throw new m("bad-alias",`schema ${e}.${t}: alias → ${u}, which is not a value`);s.set(String(o).toLowerCase(),String(u))}n.aliasMap=s}if(i==="object[]"){if(!b(n.fields))throw new m("bad-items",`schema ${e}.${t}: object[] needs \`fields\``);const l={};for(const[s,o]of Object.entries(n.fields))l[s]=L(`${e}.${t}[]`,s,o);n.fields=Object.freeze(l),n.order=Object.freeze(Object.keys(l))}if(n.emptyIf!=null&&!(n.emptyIf instanceof RegExp))throw new m("bad-emptyif",`schema ${e}.${t}: emptyIf must be a RegExp`);return n.type=i,n.describe=String(n.describe||"").trim(),Object.freeze(n)}const I=e=>e==="string[]"||e==="number[]"||e==="object[]";function q(e){const t=e.order.filter(r=>I(e.fields[r].type));return t.length===1?t[0]:null}function ie(e,{fences:t=!1}={}){const r=e.order.map(i=>`${JSON.stringify(i)}: ${A(e.fields[i])}`).join(", "),n=[];for(const i of e.order){const l=e.fields[i],s=[];l.describe&&s.push(l.describe),l.required&&s.push("required"),l.default!=null&&!l.required&&s.push(`defaults to ${JSON.stringify(l.default)}`),l.type==="string"&&l.max&&s.push(`at most ${l.max} characters`),I(l.type)&&l.maxItems&&s.push(`at most ${l.maxItems} items`),s.length&&n.push(`- ${i} — ${s.join("; ")}.`)}return[e.purpose?`${e.purpose}`:"",(e.purpose,""),t?"Return a single JSON object in a ```json code fence and nothing else:":"Return ONLY a JSON object — no prose, no code fences, no explanation:",`{${r}}`,(n.length,""),...n].filter(i=>i!=="").join(`
2
- `)}function A(e){switch(e.type){case"enum":return e.values.map(t=>JSON.stringify(t)).join("|");case"string[]":return"[string, …]";case"number[]":return"[number, …]";case"object[]":return`[{${e.order.map(t=>`${JSON.stringify(t)}: ${A(e.fields[t])}`).join(", ")}}, …]`;case"integer":return"integer";case"number":return"number";case"boolean":return"true|false";default:return"string"}}function U(e,{strict:t=!0}={}){const r={};for(const i of e.order)r[i]=_(e.fields[i]);const n=t?e.order.slice():e.order.filter(i=>e.fields[i].required);return{type:"object",properties:r,required:n,additionalProperties:!1}}function _(e){const t=e.describe?{description:e.describe}:{};switch(e.type){case"enum":return{...t,type:"string",enum:e.values.slice()};case"integer":return{...t,type:"integer"};case"number":return{...t,type:"number"};case"boolean":return{...t,type:"boolean"};case"string[]":return{...t,type:"array",items:{type:"string"}};case"number[]":return{...t,type:"array",items:{type:"number"}};case"object[]":return{...t,type:"array",items:{type:"object",properties:Object.fromEntries(e.order.map(r=>[r,_(e.fields[r])])),required:e.order.slice(),additionalProperties:!1}};default:return{...t,type:"string"}}}function se(e,{mode:t="schema",strict:r=!0}={}){return t==="none"?null:t==="object"?{response_format:{type:"json_object"}}:{response_format:{type:"json_schema",json_schema:{name:e.name.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"answer",strict:r,schema:U(e,{strict:r})}}}}const le=Object.freeze(["schema","object","none"]);function v(e){let t=String(e??"").trim();const r=t.match(/```(?:json|jsonc|json5)?\s*\n?([\s\S]*?)(?:```|$)/i);r&&r[1].trim()&&(t=r[1].trim());const n=t.replace(K,"");return n!==t&&/^[[{"]/.test(n)&&(t=n),t.trim()}function F(e){const t=String(e??"");let r=null;for(let n=0;n<t.length;n++){const i=t[n];if(i!=="{"&&i!=="[")continue;const l=W(t,n);if(l.complete)return{text:t.slice(n,l.end),start:n,end:l.end,complete:!0};r||(r={text:t.slice(n),start:n,end:t.length,complete:!1})}return r}function W(e,t){const r=[];let n=!1,i='"';for(let l=t;l<e.length;l++){const s=e[l];if(n){if(s==="\\"){l++;continue}s===i&&(n=!1);continue}if(j.has(s)){n=!0,i=j.get(s);continue}if(s==="{"||s==="["){r.push(s);continue}if((s==="}"||s==="]")&&(r.pop(),!r.length))return{end:l+1,complete:!0,depth:0,inStr:!1}}return{end:e.length,complete:!1,depth:r.length,inStr:n}}const B=new Map([["true","true"],["false","false"],["null","null"],["True","true"],["False","false"],["None","null"],["TRUE","true"],["FALSE","false"],["NULL","null"],["yes","true"],["no","false"],["Yes","true"],["No","false"],["undefined","null"],["NaN","null"],["Infinity","null"]]),j=new Map([['"','"'],["'","'"],["“","”"],["”","”"],["‘","’"],["’","’"]]),D=e=>j.has(e);function z(e,{partial:t=!1}={}){const r=String(e??"");let n="";const i=[],l=new Set;let s=!1,o=null,u=-1,d=-1,f=!1;const g=()=>i[i.length-1]||null,x=()=>{s&&(d=n.length,n+=",",s=!1)},$=()=>{const c=g();c&&c.kind==="{"?(i.length===1&&o&&l.add(o),c.expect="comma"):c&&(c.expect="comma")};for(let c=0;c<r.length;c++){const p=r[c];if(/\s/.test(p)){n&&!/\s$/.test(n)&&(n+=" ");continue}if(p==="/"&&(r[c+1]==="/"||r[c+1]==="*")){if(r[c+1]==="/")for(;c<r.length&&r[c]!==`
3
- `;)c++;else{const a=r.indexOf("*/",c+2);c=a<0?r.length:a+1}continue}if(p==="{"||p==="["){x(),i.push({kind:p,expect:p==="{"?"key":"value"}),n+=p;continue}if(p==="}"||p==="]"){s=!1;const a=g();if(!a)continue;a.kind==="{"&&(a.expect==="colon"||a.expect==="value"&&n.endsWith(":"))&&O(),i.pop(),n+=a.kind==="{"?"}":"]",$();continue}if(p===":"){n+=":";const a=g();a&&(a.expect="value");continue}if(p===","){s=!0;const a=g();a&&(a.expect=a.kind==="{"?"key":"value");continue}if(D(p)){x();const a=g(),k=!!a&&a.kind==="{"&&a.expect!=="value";k&&(u=n.length);const y=G(r,c,p);if(c=y.end,!y.closed){if(f=!0,!t)return{json:null,complete:!1,settled:l,truncated:!0};if(k){O();break}n+=`${JSON.stringify(y.value)}`,i.length;break}n+=JSON.stringify(y.value),k?(i.length===1&&(o=y.value),a&&(a.expect="colon")):$();continue}const h=H(r,c);if(!h.value)continue;c=h.end,x();const S=g();if(!!S&&S.kind==="{"&&S.expect!=="value"){u=n.length,n+=JSON.stringify(h.value),i.length===1&&(o=h.value),S.expect="colon";continue}const J=B.get(h.value);J?n+=J:/^-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?$/.test(h.value)?n+=h.value:n+=JSON.stringify(h.value),t&&h.end>=r.length-1?f=!0:$()}function O(){u<0||(n=n.slice(0,d>=0&&d>=u-1?d:u),n.endsWith(",")&&(n=n.slice(0,-1)),u=-1,i.length===1&&(o=null))}if(i.length){if(f=!0,!t)return{json:null,complete:!1,settled:l,truncated:!0};const c=g();for(c&&c.kind==="{"&&c.expect==="colon"&&O(),n.trimEnd().endsWith(":")&&(n+="null"),n.trimEnd().endsWith(",")&&(n=n.trimEnd().slice(0,-1));i.length;)n+=i.pop().kind==="{"?"}":"]"}return{json:n.trim(),complete:!f,settled:l,truncated:f}}function G(e,t,r){const n=j.get(r)||'"';let i="";for(let l=t+1;l<e.length;l++){const s=e[l];if(s==="\\"){const o=e[l+1];if(o===void 0)return{value:i,end:e.length,closed:!1};o==="n"?i+=`
4
- `:o==="t"?i+=" ":o==="r"?i+="\r":o==="u"&&/^[0-9a-fA-F]{4}$/.test(e.slice(l+2,l+6))?(i+=String.fromCharCode(parseInt(e.slice(l+2,l+6),16)),l+=4):i+=o,l++;continue}if(s===n)return{value:i,end:l,closed:!0};i+=s}return{value:i,end:e.length,closed:!1}}function H(e,t){let r=t;for(;r<e.length&&!/[\s,:{}[\]"']/.test(e[r]);)r++;return{value:e.slice(t,r),end:r-1}}function oe(e,{partial:t=!1}={}){const r=F(v(e));return r?z(r.text,{partial:t}).json:null}function C(e,t,{partial:r=!1}={}){const n=String(e??"").trim();if(!n)return null;const i=v(n);if(E.test(i)||t.nothingIf?.test(i))return N(t);const l=F(i);let s=null,o=!1,u=new Set;if(l){const f=z(l.text,{partial:r});if(o=f.complete&&l.complete,u=f.settled,f.json)try{s=JSON.parse(f.json)}catch{s=null}}if(s==null){const f=V(i,t);if(f){const g=R(f,t,{partial:r});if(g===w)return N(t);if(g)return{value:g,complete:!0,settled:t.order.slice(),source:"fallback"}}return null}if(Array.isArray(s)){const f=q(t);if(!f)return null;s={[f]:s}}if(!b(s))return null;const d=R(s,t,{partial:r});return d===w?N(t):d==null?null:{value:d,complete:o,settled:[...u].filter(f=>t.order.includes(f)),source:"json"}}const w=Symbol("nothing");function N(e){return e.nothing==null?null:{value:e.nothing,complete:!0,settled:e.order.slice(),source:"nothing"}}function ue(e,t,r){return C(e,t,r)?.value??null}function V(e,t){if(typeof t.fallback=="function")try{const s=t.fallback(e);return b(s)?s:null}catch{return null}if(t.fallback!=="lines")return null;const r=q(t);if(!r)return null;const n=e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean),i=n.filter(s=>/^(?:[-*+•]|\d+[.)])\s+/.test(s));if(!i.length&&n.length<2)return null;const l=(i.length?i:n).map(s=>s.replace(/^(?:[-*+•]|\d+[.)])\s*/,"").replace(/^["'`]|["'`]$/g,"").trim()).filter(Boolean);return l.length?{[r]:l}:null}function R(e,t,{partial:r}){const n={};let i=!1,l=!1,s=!1;for(const o of t.order){const u=t.fields[o],d=Q(e,o),f=M(d,u);if(f===void 0){u.required&&(i=!0),u.default!==void 0?n[o]=u.default:r||(n[o]=Z(u));continue}s=!0,n[o]=f,u.required&&Y(f)&&(l=!0)}return s?r?n:l?w:i&&t.strictRequired?null:n:null}const Y=e=>e===""||e===null||Array.isArray(e)&&e.length===0;function Q(e,t){if(t in e)return e[t];const r=t.toLowerCase().replace(/[^a-z0-9]/g,"");for(const n of Object.keys(e))if(n.toLowerCase().replace(/[^a-z0-9]/g,"")===r)return e[n]}function Z(e){return I(e.type)?[]:e.type==="boolean"?!1:e.type==="number"||e.type==="integer"?null:e.type==="enum"?e.default??e.values[0]:""}function M(e,t){if(e!=null)switch(t.type){case"string":{const r=T(e,t);return r===void 0?void 0:r}case"enum":{const r=String(typeof e=="string"?e:e?.value??e).trim().toLowerCase().replace(/[.!]+$/,""),n=t.aliasMap.get(r)??t.aliasMap.get(r.replace(/^(?:a|an|the)\s+/,""));return n||(t.default!==void 0?t.default:void 0)}case"number":case"integer":{const r=typeof e=="number"?e:Number(String(e).replace(/[^0-9.eE+-]/g,""));if(!Number.isFinite(r))return;const n=t.type==="integer"?Math.round(r):r;return t.min!=null&&n<t.min?t.min:t.max!=null&&n>t.max?t.max:n}case"boolean":{if(typeof e=="boolean")return e;const r=String(e).trim().toLowerCase();return/^(?:true|yes|y|1)$/.test(r)?!0:/^(?:false|no|n|0)$/.test(r)?!1:void 0}case"string[]":case"number[]":case"object[]":{const r=Array.isArray(e)?e:e===""?[]:[e],n=t.type==="string[]"?s=>T(s,{max:t.itemMax,emptyIf:t.itemEmptyIf}):t.type==="number[]"?s=>M(s,{type:"number",min:t.min,max:t.max}):s=>b(s)?R(s,{order:t.order,fields:t.fields,strictRequired:!0},{partial:!1}):void 0,i=[],l=new Set;for(const s of r){const o=n(s);if(!(o==null||o===""||o===w)){if(t.dedupe!==!1){const u=typeof o=="object"?JSON.stringify(o):String(o).toLowerCase();if(l.has(u))continue;l.add(u)}if(i.push(o),t.maxItems&&i.length>=t.maxItems)break}}return i}default:return}}function T(e,t={}){if(e==null)return;let n=(typeof e=="string"?e:b(e)?String(e.value??e.text??e.name??""):String(e)).replace(/\s+/g," ").trim();if(t.emptyIf&&t.emptyIf.test(n)||E.test(n))return"";if(n=n.replace(/^["'`]+|["'`]+$/g,"").trim(),t.max&&n.length>t.max){const i=n.slice(0,t.max);n=/\s/.test(i)?i.replace(/\s+\S*$/,""):i}return n}function ce(e){return E.test(String(e??"").trim())}const X=/[{}[\]",:]/,ee=12;function fe(e,{onChange:t=null}={}){let r="",n=0,i=null,l="";const s=o=>{const u=C(r,e,{partial:o});if(u){i=u;const d=JSON.stringify(u.value);d!==l&&(l=d,t?.(u.value,u.settled))}return n=0,i};return{push(o){const u=String(o??"");return u&&(r+=u,n+=u.length),u&&(X.test(u)||n>=ee)&&s(!0),this.snapshot()},end(){return s(!1),i||s(!0),this.snapshot()},snapshot(){return{value:i?.value??null,settled:i?.settled??[],complete:!!i?.complete,source:i?.source??null,text:r}},reset(){r="",n=0,i=null,l=""},get text(){return r}}}export{P as FIELD_TYPES,le as RESPONSE_MODES,m as StructuredError,C as coerce,fe as createStructuredStream,re as defineSchema,ie as describeSchema,F as findJson,ce as isNothing,ue as parseStructured,oe as repairJson,se as responseFormat,z as rewriteJson,U as toJsonSchema,v as unfence};
1
+ export*from"@chatpanel/events/structured.js";
package/src/stt-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as I}from"node:path";import{existsSync as ee,readdirSync as te}from"node:fs";import{randomUUID as ne}from"node:crypto";import{ensureLib as B,modelRoot as Y}from"./ner-engine.js";import{runtimeDtype as v,runtimeName as j,DTYPE_SUFFIX as re}from"./model-runtime.js";import{verifyModelWeights as oe}from"./model-integrity.js";import{DEFAULT_STT_MODEL as W,isEnglishOnly as G,sttModelDtype as z,isKnownSttModel as ie,sttModelEngine as H}from"./stt-models.js";import*as k from"./parakeet-engine.js";import*as E from"./diarize-engine.js";import{diarizeApproxMB as le}from"./diarize-models.js";import{makeWarmTimer as C}from"./warm-timer.js";const m=16e3,ae=m,se=3*m,ce=2,ue=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function fe(e,t){if(t>ce*m)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?ue.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let c="off",p=null,f=null,M=null,A=null,g=null,D=null,_=null;function de(e=p||W,t=z(e)||v()){if(H(e)==="parakeet-tdt")return k.parakeetOnDisk(e,k.parakeetDtype(t));const n=I(Y(),...e.split("/"),"onnx");if(!ee(n))return!1;const r=re[t]??"";try{const o=te(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(l=>l===`decoder_model_merged${r}.onnx`||l===`decoder_model${r}.onnx`)}catch{return!1}}function Ue(){return c}function P(){return c==="ready"&&!!f}function Ke(){return g}function Oe(){return{configured:c!=="off",ok:P(),state:c,model:p,dtype:D,runtime:j(),error:M,warmMs:_?.warmMs??null}}function Xe(){return!!_?.pending()}function b(){return T.size>0||c==="loading"||c==="downloading"}async function U({log:e=()=>{}}={}){if(b())return!1;_?.disarm();const t=f;if(f=null,A=null,D=null,g=null,M=null,c="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((_?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function q(e){return e.then(t=>(t&&!b()&&_?.arm(),t))}async function Q(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(H(e)==="parakeet-tdt")return me(e,{log:t,allowDownload:n,dtype:r});const o=f,l=p;let a;try{a=await B()}catch(d){return c="error",M=`engine load failed: ${d.message}`,t(`[stt] transformers.js not available (${d.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||z(e)||v(),s=de(e,i);if(a.env.allowRemoteModels=s?!1:!!n,!s&&!n)return c="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const y=a.env.remoteHost,w=!ie(e);if(!s&&w)try{a.env.remoteHost="https://huggingface.co/"}catch{}c=s?"loading":"downloading",s||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${w?", from Hugging Face":""})…`));try{const d=u=>{if(!u)return;const R=typeof u.progress=="number"?Math.round(u.progress):g?.pct??0;u.status==="progress"||u.status==="download"||u.status==="initiate"?g={model:e,file:u.file||g?.file||null,pct:R}:u.status==="done"&&u.file&&t(`[stt] fetched ${u.file}`)};let S;try{S=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:d})}catch(u){if(s||w||!n)throw u;t(`[stt] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),a.env.remoteHost="https://huggingface.co/",a.env.allowRemoteModels=!0,S=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:d})}if(!s)try{oe(e,{modelsDir:Y(),log:t})}catch(u){try{await S.dispose?.()}catch{}throw u}if(f=S,p=e,c="ready",M=null,g=null,D=i,o&&o!==S)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(d){return M=d.message,g=null,o?(f=o,p=l,c="ready"):c="error",t(`[stt] model load failed (${d.message})${o?" — keeping previous model":""}`),!1}finally{try{a.env.remoteHost=y}catch{}}}async function me(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=f,l=p,a=k.parakeetDtype(r&&r!=="auto"?r:pe()),h=k.parakeetOnDisk(e,a);if(!h&&!n)return c="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;c=h?"loading":"downloading",h||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await k.loadRecognizer({modelId:e,dtype:a,allowDownload:n,log:t,onProgress:y=>{g={model:e,file:y.file||null,pct:typeof y.pct=="number"?y.pct:g?.pct??0}}}),s=async y=>({text:await i.transcribe(y)});if(s.__parakeet=!0,s.dispose=()=>i.dispose(),f=s,p=e,c="ready",M=null,g=null,D=a,o&&o!==s)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return M=i.message,g=null,o?(f=o,p=l,c="ready"):c="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function pe(){return k.PARAKEET_DEFAULT_DTYPE}const ge=30;function he({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:r=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof r=="number"&&r<=ge||e==="download"?{allowDownload:!0}:null}function K(e,{log:t=()=>{},warmMs:n}={}){const r=he({mode:e,onDisk:E.modelOnDisk(),ready:E.isReady(),approxMB:le(E.activeModel())});r&&E.init({...r,warmMs:n,onLog:t})}function Be(e={}){if(A)return A;const t=typeof e.onLog=="function"?e.onLog:()=>{};return p=e.model||W,c="loading",_=C({warmMs:e.warmMs,busy:b,log:t,unload:()=>U({log:t})}),A=q(Q(p,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&K(e.speaker,{log:t,warmMs:e.warmMs}),n)),A}async function Ye(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=H(e)==="parakeet-tdt"?k.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:k.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:z(e)||v();if(e===p&&P()&&D===r)return K(t.speaker,{log:n,warmMs:t.warmMs}),!0;_??=C({warmMs:t.warmMs,busy:b,log:n,unload:()=>U({log:n})});const o=await q(Q(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&K(t.speaker,{log:n,warmMs:t.warmMs}),o}const ye=8,_e=12e4,we=6e4,Me=1200,V=12,O=700,$=.008,Te=30,T=new Map,x=new Map;let N=Promise.resolve();function je(){return T.size}const ke=300,Ee=3e3;function Se(e){const t=Number(e);return Number.isFinite(t)?Math.min(Ee,Math.max(ke,Math.round(t))):O}function We({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=O,interims:l=!0,remote:a=null,poll:h=!1}={}){if(T.size>=ye){const s=new Error("too many concurrent dictation sessions");throw s.code="too_many_sessions",s}const i={id:ne(),endSilenceMs:Se(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new E.Diarizer:null,remote:a||null,interims:l!==!1&&!a,chunks:[],samples:0,listeners:new Set,poll:h?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return T.set(i.id,i),_?.disarm(),i.diarizer&&E.retain(),J(i),{id:i.id}}function X(e){return T.get(String(e||""))||null}function Ge(e,t){const n=X(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function L(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function qe(e){const t=String(e||""),n=T.get(t);if(n)return n.poll?n.poll.splice(0):null;const r=x.get(t);return r?(clearTimeout(r.timer),x.delete(t),r.session.poll.splice(0)):null}function Qe(e){return x.get(String(e||""))?.session||null}function J(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>Le(e.id).catch(()=>{}),we),e.idleTimer.unref?.()}function Ve(e,t){const n=X(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,J(n),xe(n))}function Je(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function xe(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+Me-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,N=N.then(()=>Z(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function Ae(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function F(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let l=t;l<n;l++)r+=e[l]*e[l];return Math.sqrt(r/o)}function De(e){const t=Math.round(.02*m);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(F(e,o,o+t)>=$){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(F(e,o,o+t)>=$){r=o+t;break}return r>n?e.subarray(n,r):e}async function be(e){try{const t=await B(),n=f?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>m*8?e.subarray(0,m*8):e,o=await f.processor(r),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),a=await f.model({...o,decoder_input_ids:l});let h=null,i=-1/0;for(const[s,y]of Object.entries(n.lang_to_id)){const w=Number(a.logits.data[y]);w>i&&(i=w,h=s)}return h?h.slice(2,-2):null}catch{return null}}async function Z(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!P()||!e.samples)return;e.lastDecodeAt=Date.now();const n=Ae(e),r=Math.round((e.endSilenceMs||O)/1e3*m),o=n.length>r&&F(n,n.length-r)<$;if(F(n)<$){n.length>m*5&&(e.chunks=[n.subarray(n.length-m)],e.samples=m);return}if(!e.interims&&!t&&!o&&n.length<V*m)return;if(!e.remote&&!e.lang&&!e.langTried&&!G(p)&&!f?.__parakeet&&n.length>=m){e.langTried=!0;const i=await be(n);i&&(e.lang=i,L(e,{type:"language",lang:i}))}let l="";try{if(e.remote)l=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const i=G(p)?{}:{language:e.lang||void 0,task:"transcribe"},s=await f(n,i);l=String(s?.text||"").trim()}}catch(i){L(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!l)return;const a=n.length>=V*m,h=n.length>=Te*m;if(t||o||a||h){const i=t?"flush":o?"silence":h?"overflow":"length",s=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";const y=De(n);if(fe(l,y?y.length:0))return;let w=null;if(e.diarizer)try{const d=e.speakerLabel?null:y,S=d?await E.embed(d):null,u=!!d&&d.length<ae,R=!!d&&d.length<se;w=e.diarizer.assign(S,{pinnedLabel:e.speakerLabel,weak:u,thin:R})}catch{}L(e,{type:"final",text:l,reason:i,endOfTurn:s,durationMs:Math.round(n.length/m*1e3),...w?{speaker:w}:{}})}else l!==e.lastInterim&&(e.lastInterim=l,L(e,{type:"interim",text:l}))}async function Le(e){const t=X(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(N=N.then(()=>Z(t,{flush:!0}).catch(()=>{})))}finally{if(L(t,{type:"end"}),t.listeners.clear(),T.delete(t.id),t.poll){const n=setTimeout(()=>x.delete(t.id),_e);n.unref?.(),x.set(t.id,{session:t,timer:n})}t.diarizer&&E.release(),T.size===0&&P()&&_?.arm()}return!0}function Ze(){for(const e of T.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);T.clear();for(const e of x.values())clearTimeout(e.timer);x.clear(),_?.disarm(),_=null,c="off",p=null,f=null,M=null,A=null,g=null}function Ie(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){f=e,p=t,c=e?"ready":"off",D=r,n!==null&&(_=C({warmMs:n,busy:b,unload:()=>U()}),e&&_.arm())}export{ge as AUTO_FETCH_MAX_MB,m as SAMPLE_RATE,se as THIN_SPEAKER_SAMPLES,ae as WEAK_SPEAKER_SAMPLES,Ze as _reset,Ie as _setPipeForTest,Se as clampEndSilence,We as createSession,qe as drainEvents,Le as endSession,Qe as endedSession,X as getSession,Oe as health,Be as init,P as isReady,fe as looksHallucinated,de as modelOnDisk,Ke as progress,Ve as pushAudio,v as runtimeDtype,j as runtimeName,je as sessionCount,Ye as setModel,he as speakerPlan,Ue as state,Ge as subscribe,Je as toFloat32,U as unload,Xe as warmPending};
1
+ import{join as Ee}from"node:path";import{existsSync as Te,readdirSync as ke}from"node:fs";import{randomUUID as xe}from"node:crypto";import{ensureLib as oe,modelRoot as ie}from"./ner-engine.js";import{runtimeDtype as B,runtimeName as le,DTYPE_SUFFIX as Se}from"./model-runtime.js";import{verifyModelWeights as be}from"./model-integrity.js";import{DEFAULT_STT_MODEL as ae,isEnglishOnly as se,sttModelDtype as q,isKnownSttModel as De,sttModelEngine as P}from"./stt-models.js";import*as D from"./parakeet-engine.js";import*as Q from"./coreml-stt-engine.js";import*as b from"./diarize-engine.js";import*as L from"./segment-engine.js";import{turnsFromSpans as Le,mainLocal as Ae,timeByLocal as ve,audioOfLocal as $e}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as Fe}from"./diarize-models.js";import{makeWarmTimer as V}from"./warm-timer.js";const h=16e3,ce=h,ue=3*h,Pe=2,Ne=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function Re(e,t){if(t>Pe*h)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?Ne.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let s="off",w=null,g=null,M=null,A=null,y=null,v=null,E=null;function Oe(e=w||ae,t=q(e)||B()){if(P(e)==="parakeet-tdt")return D.parakeetOnDisk(e,D.parakeetDtype(t));if(P(e)==="coreml-tdt")return Q.coremlOnDisk(e);const n=Ee(ie(),...e.split("/"),"onnx");if(!Te(n))return!1;const r=Se[t]??"";try{const o=ke(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(i=>i===`decoder_model_merged${r}.onnx`||i===`decoder_model${r}.onnx`)}catch{return!1}}function mt(){return s}function K(){return s==="ready"&&!!g}function pt(){return y}function ht(){return{configured:s!=="off",ok:K(),state:s,model:w,dtype:v,runtime:le(),error:M,warmMs:E?.warmMs??null}}function gt(){return!!E?.pending()}function O(){return k.size>0||s==="loading"||s==="downloading"}async function J({log:e=()=>{}}={}){if(O())return!1;E?.disarm();const t=g;if(g=null,A=null,v=null,y=null,M=null,s="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((E?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function fe(e){return e.then(t=>(t&&!O()&&E?.arm(),t))}async function de(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(P(e)==="parakeet-tdt")return ze(e,{log:t,allowDownload:n,dtype:r});if(P(e)==="coreml-tdt")return He(e,{log:t,allowDownload:n});const o=g,i=w;let l;try{l=await oe()}catch(_){return s="error",M=`engine load failed: ${_.message}`,t(`[stt] transformers.js not available (${_.message}) — dictation falls back to the browser engine`),!1}const a=(r&&r!=="auto"?r:null)||q(e)||B(),f=Oe(e,a);if(l.env.allowRemoteModels=f?!1:!!n,!f&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=l.env.remoteHost,d=!De(e);if(!f&&d)try{l.env.remoteHost="https://huggingface.co/"}catch{}s=f?"loading":"downloading",f||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${d?", from Hugging Face":""})…`));try{const _=m=>{if(!m)return;const j=typeof m.progress=="number"?Math.round(m.progress):y?.pct??0;m.status==="progress"||m.status==="download"||m.status==="initiate"?y={model:e,file:m.file||y?.file||null,pct:j}:m.status==="done"&&m.file&&t(`[stt] fetched ${m.file}`)};let c;try{c=await l.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:_})}catch(m){if(f||d||!n)throw m;t(`[stt] mirror fetch failed (${String(m.message).slice(0,80)}) — retrying from Hugging Face…`),l.env.remoteHost="https://huggingface.co/",l.env.allowRemoteModels=!0,c=await l.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:_})}if(!f)try{be(e,{modelsDir:ie(),log:t})}catch(m){try{await c.dispose?.()}catch{}throw m}if(g=c,w=e,s="ready",M=null,y=null,v=a,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (in-process, offline) — local dictation active`),!0}catch(_){return M=_.message,y=null,o?(g=o,w=i,s="ready"):s="error",t(`[stt] model load failed (${_.message})${o?" — keeping previous model":""}`),!1}finally{try{l.env.remoteHost=p}catch{}}}async function ze(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=g,i=w,l=D.parakeetDtype(r&&r!=="auto"?r:Ce()),u=D.parakeetOnDisk(e,l);if(!u&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=u?"loading":"downloading",u||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await D.loadRecognizer({modelId:e,dtype:l,allowDownload:n,log:t,onProgress:p=>{y={model:e,file:p.file||null,pct:typeof p.pct=="number"?p.pct:y?.pct??0}}}),f=async p=>({text:await a.transcribe(p)});if(f.__transducer=!0,f.dispose=()=>a.dispose(),g=f,w=e,s="ready",M=null,y=null,v=l,o&&o!==f)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${l} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return M=a.message,y=null,o?(g=o,w=i,s="ready"):s="error",t(`[stt] model load failed (${a.message})${o?" — keeping previous model":""}`),!1}}function Ce(){return D.PARAKEET_DEFAULT_DTYPE}const me="fp16";async function He(e,{log:t=()=>{},allowDownload:n=!0}={}){const r=g,o=w,i=Q.coremlOnDisk(e);if(!i&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=i?"loading":"downloading",i||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let l=null;const u=await Q.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:a=>{y={model:e,file:a.file||null,pct:typeof a.pct=="number"?a.pct:y?.pct??0}},onExit:a=>{g===l&&(g=null,A=null,s="error",M=a,E?.disarm(),t(`[stt] ${a} — reloads on the next dictation`))}});if(l=async a=>({text:await u.transcribe(a)}),l.__transducer=!0,l.dispose=()=>u.dispose(),g=l,w=e,s="ready",M=null,y=null,v=me,r&&r!==l)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${u.version}, windows ${u.windows.join("/")} s, offline) — local dictation active`),!0}catch(l){return M=l.message,y=null,r?(g=r,w=o,s="ready"):s="error",t(`[stt] model load failed (${l.message})${r?" — keeping previous model":""}`),!1}}const Ue=30;function pe({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:r=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof r=="number"&&r<=Ue||e==="download"?{allowDownload:!0}:null}function Z(e,{log:t=()=>{},warmMs:n,allowDownload:r=!0}={}){const o=pe({mode:e,onDisk:b.modelOnDisk(),ready:b.isReady(),approxMB:Fe(b.activeModel())});if(o&&b.init({allowDownload:o.allowDownload&&r!==!1,warmMs:n,onLog:t}),e==="off"||I)return;const i=pe({mode:e,onDisk:L.modelOnDisk(),ready:L.isReady(),approxMB:L.SEGMENT_MODEL_APPROX_MB});i&&L.init({allowDownload:i.allowDownload&&r!==!1,warmMs:n,onLog:t})}let I=!1;function yt(e={}){if(A)return A;const t=typeof e.onLog=="function"?e.onLog:()=>{};return w=e.model||ae,I=e.segment===!1,s="loading",E=V({warmMs:e.warmMs,busy:O,log:t,unload:()=>J({log:t})}),A=fe(de(w,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&Z(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),n)),A}async function wt(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(I=t.segment===!1);const r=P(e)==="parakeet-tdt"?D.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:D.PARAKEET_DEFAULT_DTYPE):P(e)==="coreml-tdt"?me:t.dtype&&t.dtype!=="auto"?t.dtype:q(e)||B();if(e===w&&K()&&v===r)return Z(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;E??=V({warmMs:t.warmMs,busy:O,log:n,unload:()=>J({log:n})});const o=await fe(de(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&Z(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),o}const Be=8,Ke=12e4,Xe=6e4,je=1200,ee=12,te=700,ne=.008,Ye=.002,Ge=4;function We(e){return e>0?Math.min(ne,Math.max(Ye,e*Ge)):ne}function qe(e){const t=Math.round(.1*h),n=Math.floor(e.length/t);if(n<5)return null;const r=new Float32Array(n);for(let o=0;o<n;o++)r[o]=C(e,o*t,(o+1)*t);return r.sort(),r[Math.floor(n*.1)]}const he=30,k=new Map,$=new Map;let F=Promise.resolve();function _t(){return k.size}const Qe=300,Ve=3e3;function Je(e){const t=Number(e);return Number.isFinite(t)?Math.min(Ve,Math.max(Qe,Math.round(t))):te}function Mt({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=te,interims:i=!0,remote:l=null,poll:u=!1}={}){if(k.size>=Be){const f=new Error("too many concurrent dictation sessions");throw f.code="too_many_sessions",f}const a={id:xe(),endSilenceMs:Je(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new b.Diarizer:null,remote:l||null,interims:i!==!1&&!l,chunks:[],samples:0,listeners:new Set,poll:u?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return k.set(a.id,a),E?.disarm(),a.diarizer&&(b.retain(),L.retain()),ge(a),{id:a.id}}function X(e){return k.get(String(e||""))||null}function Et(e,t){const n=X(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function z(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Tt(e){const t=String(e||""),n=k.get(t);if(n)return n.poll?n.poll.splice(0):null;const r=$.get(t);return r?(clearTimeout(r.timer),$.delete(t),r.session.poll.splice(0)):null}function kt(e){return $.get(String(e||""))?.session||null}function ge(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>nt(e.id).catch(()=>{}),Xe),e.idleTimer.unref?.()}function xt(e,t){const n=X(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,ge(n),Ze(n))}function St(e){const t=X(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),F=F.then(()=>re(t).catch(()=>{})),F)}function bt(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function Ze(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+je-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,F=F.then(()=>re(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function ye(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function Ie(e,t,n){const r=h/100,o=Math.max(0,e.length-t),i=Math.floor((e.length-o)/r),l=Math.max(1,Math.round(n/r));if(i<=l)return 0;const u=new Float32Array(i);for(let d=0;d<i;d++){let _=0;const c=o+d*r;for(let m=0;m<r;m++)_+=e[c+m]*e[c+m];u[d]=_/r}let a=-1,f=1/0,p=0;for(let d=0;d<l;d++)p+=u[d];for(let d=0;d+l<=i;d++)d>0&&(p+=u[d+l-1]-u[d-1]),p<f&&(f=p,a=d);return a<0?0:o+Math.round((a+l/2)*r)}function C(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let i=t;i<n;i++)r+=e[i]*e[i];return Math.sqrt(r/o)}function et(e,t=ne){const n=Math.round(.02*h);let r=0,o=e.length;for(let i=0;i+n<=e.length;i+=n)if(C(e,i,i+n)>=t){r=i;break}for(let i=e.length-n;i>=0;i-=n)if(C(e,i,i+n)>=t){o=i+n;break}return o>r?e.subarray(r,o):e}async function tt(e){try{const t=await oe(),n=g?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>h*8?e.subarray(0,h*8):e,o=await g.processor(r),i=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),l=await g.model({...o,decoder_input_ids:i});let u=null,a=-1/0;for(const[f,p]of Object.entries(n.lang_to_id)){const d=Number(l.logits.data[p]);d>a&&(a=d,u=f)}return u?u.slice(2,-2):null}catch{return null}}async function re(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!K()||!e.samples)return;e.lastDecodeAt=Date.now();let n=ye(e);const r=n.length,o=Math.max(0,(e.pushed||0)-e.samples),i=Math.round((e.endSilenceMs||te)/1e3*h),l=qe(n);l!==null&&(e.noiseFloor==null||l<e.noiseFloor)&&(e.noiseFloor=l);const u=We(e.noiseFloor),a=n.length>i&&C(n,n.length-i)<u;if(C(n)<u){n.length>h*5&&(e.chunks=[n.subarray(n.length-h)],e.samples=h);return}if(!e.interims&&!t&&!a&&n.length<ee*h)return;let f=null;if(!t&&!a&&r>=ee*h&&r<he*h){const c=Ie(n,3*h,Math.round(.2*h));c>0&&c<n.length&&(f=n.subarray(c),n=n.subarray(0,c))}if(!e.remote&&!e.lang&&!e.langTried&&!se(w)&&!g?.__transducer&&n.length>=h){e.langTried=!0;const c=await tt(n);c&&(e.lang=c,z(e,{type:"language",lang:c}))}let p="";try{if(e.remote)p=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const c=se(w)?{}:{language:e.lang||void 0,task:"transcribe"},m=await g(n,c);p=String(m?.text||"").trim()}}catch(c){z(e,{type:"error",code:"decode_failed",message:c.message,fatal:!1});return}if(!p)return;const d=r>=ee*h,_=r>=he*h;if(t||a||d||_){const c=t?"flush":a?"silence":_?"overflow":"length",m=c==="flush"||c==="silence",j=e.samples-r,H=[];f&&H.push(f),j>0&&H.push(ye(e).subarray(r)),e.chunks=H,e.samples=H.reduce((T,x)=>T+x.length,0),e.lastInterim="";const Y=et(n,u);if(Re(p,Y?Y.length:0))return;let N=null,G=null;if(e.diarizer)try{const T=e.speakerLabel?null:await L.spans(n),x=T?Le(T):[];if(x.length){const R=new Map;for(const{local:S}of ve(x)){const U=$e(n,x,S),we=U.length?await b.embed(U):null,_e=U.length<ce,Me=U.length<ue;R.set(S,e.diarizer.assign(we,{pinnedLabel:null,weak:_e,thin:Me}))}const W=Math.round(o/h*1e3);G=x.map(S=>({startMs:W+Math.round(S.start*1e3),durationMs:Math.round((S.end-S.start)*1e3),speaker:R.get(S.local)})).filter(S=>S.speaker),N=R.get(Ae(x))||null}}catch{}if(e.diarizer&&!N)try{const T=Y,x=T?await b.embed(T):null,R=!!T&&T.length<ce,W=!!T&&T.length<ue;N=e.diarizer.assign(x,{pinnedLabel:e.speakerLabel,weak:R,thin:W})}catch{}z(e,{type:"final",text:p,reason:c,endOfTurn:m,durationMs:Math.round(n.length/h*1e3),startMs:Math.round(o/h*1e3),...N?{speaker:N}:{},...G?.length?{turns:G}:{}})}else p!==e.lastInterim&&(e.lastInterim=p,z(e,{type:"interim",text:p}))}async function nt(e){const t=X(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(F=F.then(()=>re(t,{flush:!0}).catch(()=>{})))}finally{if(z(t,{type:"end"}),t.listeners.clear(),k.delete(t.id),t.poll){const n=setTimeout(()=>$.delete(t.id),Ke);n.unref?.(),$.set(t.id,{session:t,timer:n})}t.diarizer&&(b.release(),L.release()),k.size===0&&K()&&E?.arm()}return!0}function Dt(){for(const e of k.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);k.clear();for(const e of $.values())clearTimeout(e.timer);$.clear(),E?.disarm(),E=null,s="off",w=null,g=null,M=null,A=null,y=null}function Lt(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){g=e,w=t,s=e?"ready":"off",v=r,n!==null&&(E=V({warmMs:n,busy:O,unload:()=>J()}),e&&E.arm())}export{Ue as AUTO_FETCH_MAX_MB,h as SAMPLE_RATE,ue as THIN_SPEAKER_SAMPLES,ce as WEAK_SPEAKER_SAMPLES,Dt as _reset,Lt as _setPipeForTest,Je as clampEndSilence,Mt as createSession,St as decodeNow,Tt as drainEvents,nt as endSession,kt as endedSession,X as getSession,ht as health,yt as init,K as isReady,Re as looksHallucinated,Oe as modelOnDisk,qe as noiseFloorOf,pt as progress,xt as pushAudio,Ie as quietestCut,B as runtimeDtype,le as runtimeName,_t as sessionCount,wt as setModel,We as silenceGate,pe as speakerPlan,mt as state,Et as subscribe,bt as toFloat32,J as unload,gt as warmPending};
package/src/stt-models.js CHANGED
@@ -1 +1 @@
1
- const i="istupakov/parakeet-tdt-0.6b-v3-onnx",a=[{id:"onnx-community/whisper-tiny.en",label:"Tiny (English)",lang:"English",tier:"light",approxMB:150,ramMB:400,note:"Fastest, lightest. English only — great for quick dictation on any machine."},{id:"onnx-community/whisper-base",label:"Base (multilingual)",lang:"99 languages (auto-detected)",tier:"balanced",approxMB:300,ramMB:700,note:"Small and quick to install. Detects the spoken language automatically; good accuracy at real-time speed."},{id:"onnx-community/whisper-small",label:"Small (multilingual)",lang:"99 languages (auto-detected)",tier:"accurate",approxMB:950,ramMB:1600,note:"Noticeably more accurate; needs a faster CPU to keep up in real time."},{id:"onnx-community/whisper-large-v3-turbo",label:"Large v3 Turbo (multilingual)",lang:"99 languages (auto-detected)",tier:"max",approxMB:1600,ramMB:3200,note:"Best accuracy. For powerful machines; use the native (npm) gateway for speed."},{id:"istupakov/parakeet-tdt-0.6b-v3-onnx",label:"Parakeet TDT 0.6B v3 (multilingual, fast)",lang:"25 European languages (auto-detected)",tier:"accurate",engine:"parakeet-tdt",recommended:!0,approxMB:690,ramMB:1600,note:"Recommended — NVIDIA Parakeet transducer. Several× faster than Whisper at similar or better accuracy, English + 24 EU languages. One-time download; best on the native (npm) gateway."}],l="istupakov/parakeet-tdt-0.6b-v3-onnx";function r(e){return n(e)?.engine||"whisper"}function s(e){return a.some(t=>t.id===e)}function n(e){return a.find(t=>t.id===e)||null}function u(e){return/\.en$/.test(String(e||""))}function c(e){return n(e)?.dtype||null}function d(e){const t=String(e||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(t)&&!t.includes("..")}const o=[{id:"auto",label:"Auto (recommended)",note:"q8 on the native gateway, fp32 on the WASM binary."},{id:"q8",label:"q8 — fast, balanced",note:"Int8. Best speed/quality trade-off (native default)."},{id:"q4",label:"q4 — smallest & fastest",note:"4-bit. Least memory; slightly lower accuracy."},{id:"int8",label:"int8",note:"Alternative int8 export."},{id:"fp16",label:"fp16 — more accurate",note:"Half precision. Larger, a bit slower."},{id:"fp32",label:"fp32 — most accurate (slow)",note:"Full precision. Largest + slowest; the only one that loads on the WASM binary."}];function p(e){return o.some(t=>t.id===e)}export{i as DEFAULT_STT_MODEL,l as RECOMMENDED_STT_MODEL,o as STT_DTYPES,a as STT_MODEL_CATALOG,u as isEnglishOnly,s as isKnownSttModel,d as isValidCustomSttId,p as isValidDtype,n as sttModel,c as sttModelDtype,r as sttModelEngine};
1
+ const i="istupakov/parakeet-tdt-0.6b-v3-onnx",a=[{id:"onnx-community/whisper-tiny.en",label:"Tiny (English)",lang:"English",tier:"light",approxMB:150,ramMB:400,note:"Fastest, lightest. English only — great for quick dictation on any machine."},{id:"onnx-community/whisper-base",label:"Base (multilingual)",lang:"99 languages (auto-detected)",tier:"balanced",approxMB:300,ramMB:700,note:"Small and quick to install. Detects the spoken language automatically; good accuracy at real-time speed."},{id:"onnx-community/whisper-small",label:"Small (multilingual)",lang:"99 languages (auto-detected)",tier:"accurate",approxMB:950,ramMB:1600,note:"Noticeably more accurate; needs a faster CPU to keep up in real time."},{id:"onnx-community/whisper-large-v3-turbo",label:"Large v3 Turbo (multilingual)",lang:"99 languages (auto-detected)",tier:"max",approxMB:1600,ramMB:3200,note:"Best accuracy. For powerful machines; use the native (npm) gateway for speed."},{id:"istupakov/parakeet-tdt-0.6b-v3-onnx",label:"Parakeet TDT 0.6B v3 (multilingual, fast)",lang:"25 European languages (auto-detected)",tier:"accurate",engine:"parakeet-tdt",recommended:!0,approxMB:690,ramMB:1600,note:"Recommended — NVIDIA Parakeet transducer. Several× faster than Whisper at similar or better accuracy, English + 24 EU languages. One-time download; best on the native (npm) gateway."},{id:"ConwayResearch/Underdog-Bark-3.0",label:"Parakeet TDT 0.6B v3 for the Neural Engine (English)",lang:"English",tier:"light",engine:"coreml-tdt",platforms:["darwin-arm64"],approxMB:200,ramMB:500,note:"The same Parakeet model, repacked for the Apple Neural Engine: a 200 MB download and the fastest dictation on a Mac. English only. Needs the Apple helper."}],s="istupakov/parakeet-tdt-0.6b-v3-onnx";function p(e){return n(e)?.engine||"whisper"}function u(e,{platform:t=process.platform,arch:r=process.arch,helper:l=!1}={}){return Array.isArray(e?.platforms)&&!e.platforms.includes(`${t}-${r}`)?"Needs a Mac with Apple Silicon.":e?.engine==="coreml-tdt"&&!l?"Needs the Apple helper — Install it on the Apple on-device row (Runtime).":null}function d(e){return a.some(t=>t.id===e)}function n(e){return a.find(t=>t.id===e)||null}function c(e){return/\.en$/.test(String(e||""))}function m(e){return n(e)?.dtype||null}function g(e){const t=String(e||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(t)&&!t.includes("..")}const o=[{id:"auto",label:"Auto (recommended)",note:"q8 on the native gateway, fp32 on the WASM binary."},{id:"q8",label:"q8 — fast, balanced",note:"Int8. Best speed/quality trade-off (native default)."},{id:"q4",label:"q4 — smallest & fastest",note:"4-bit. Least memory; slightly lower accuracy."},{id:"int8",label:"int8",note:"Alternative int8 export."},{id:"fp16",label:"fp16 — more accurate",note:"Half precision. Larger, a bit slower."},{id:"fp32",label:"fp32 — most accurate (slow)",note:"Full precision. Largest + slowest; the only one that loads on the WASM binary."}];function h(e){return o.some(t=>t.id===e)}export{i as DEFAULT_STT_MODEL,s as RECOMMENDED_STT_MODEL,o as STT_DTYPES,a as STT_MODEL_CATALOG,c as isEnglishOnly,d as isKnownSttModel,g as isValidCustomSttId,h as isValidDtype,n as sttModel,m as sttModelDtype,p as sttModelEngine,u as sttModelUnavailable};
@@ -1 +1 @@
1
- const e=Object.freeze(["person","topic","tag","title"]);export{e as SUBJECT_KINDS};
1
+ export*from"@chatpanel/events/subject-kinds.js";
@@ -1 +1 @@
1
- import{SUBJECT_KINDS as n}from"./subject-kinds.js";const u=Object.freeze({records:3,mentions:5}),p=500,s=60,c=Object.freeze(["you","me","myself","yourself","i"]);function l(e){return c.includes(t(e))}function f(e){return String(e??"").replace(/\s*[([{][^)\]}]*[)\]}]\s*/g," ").replace(/\s+[-–—|·,]\s+.*$/,"").replace(/\s+/g," ").trim()}function t(e){const r=String(e??"").normalize("NFKC").trim().replace(/^[#@]+/,"");return r?r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim().slice(0,s).trim():""}function m(e,r){const o=t(r);return!o||!n.includes(e)?"":`${e}:${o}`}function S(e){const r=t(e);return r?r.split(" ").filter(Boolean):[]}export{u as DEFAULT_THRESHOLD,p as MAX_SUBJECTS,s as MAX_SUBJECT_CHARS,c as SELF_LABELS,l as isSelfLabel,t as normalizeSubject,f as stripQualifiers,m as subjectKey,S as subjectTokens};
1
+ export*from"@chatpanel/events/subject-name.js";
package/src/team-board.js CHANGED
@@ -1,6 +1 @@
1
- import{defineSchema as R,describeSchema as F,coerce as q}from"./structured.js";const N=Object.freeze(["claim","draft","link","question","answer"]),E=40,M=12e3,B=R({name:"findings",purpose:"what this task established, each item on its own with where it came from",fields:{findings:{type:"object[]",required:!0,maxItems:E,describe:"one entry per fact, draft, link or open question — never a paragraph of several",fields:{kind:{type:"enum",values:N,default:"claim"},text:{type:"string",required:!0,max:2e3},refs:{type:"string[]",maxItems:8,describe:"record ids or URLs this rests on, when any"},confidence:{type:"number",describe:"0–1, how sure"}}}},nothing:{findings:[]}});function W(){return`When you are done, end your answer with your findings in this shape:
2
- ${F(B)}`}function Y(d,{role:i,taskId:n}={}){const f=String(d||"").trim();if(!f)return[];const t=q(f,B),o=Array.isArray(t?.value?.findings)?t.value.findings.filter(u=>u&&String(u.text||"").trim()):[],a=(u,c)=>({id:`${n||"t"}:${c+1}`,kind:N.includes(u.kind)?u.kind:"claim",text:String(u.text).trim().slice(0,2e3),refs:Array.isArray(u.refs)?u.refs.map(String).filter(Boolean).slice(0,8):[],confidence:Number.isFinite(Number(u.confidence))&&Number(u.confidence)>0?Math.min(1,Number(u.confidence)):null,role:i||null,taskId:n||null});if(o.length)return o.slice(0,E).map(a);const m=f.replace(/```json[\s\S]*$/i,"").trim()||f;return[a({kind:"draft",text:m.slice(0,2e3),refs:[]},0)]}const P=Object.freeze(["task","ask","discussion","proposal"]),D=Object.freeze(["open","waiting","resolved","failed","approved","rejected"]),K=Object.freeze(["finding","note","question","answer","draft","decision","request"]),X=Object.freeze(["open","proposed","approved","rejected"]),L=Object.freeze(["info","budget","permission","direction"]),v="runner",x="person",U=4e3,j=(d,i)=>String(d||"").trim().slice(0,i),G=d=>Array.isArray(d)?d.map(String).filter(Boolean).slice(0,8):[];function O(){return{threads:[],posts:[]}}function J(d,i){const n=d&&Array.isArray(d.threads)&&Array.isArray(d.posts)?d:O(),f=String(i?.type||""),t=i?.payload&&typeof i.payload=="object"?i.payload:i||{};if(f==="board.thread"&&t.thread?.id)n.threads.some(o=>o.id===t.thread.id)||n.threads.push({...t.thread});else if(f==="board.post"&&t.post?.id){if(Array.isArray(n.removed)&&n.removed.includes(t.post.threadId))return n;n.posts.some(a=>a.id===t.post.id)||n.posts.push({...t.post});const o=n.threads.find(a=>a.id===t.post.threadId);o&&(o.lastAt=t.post.at,o.lastBy=t.post.by,o.posts=(o.posts||0)+1)}else if(f==="board.decision"&&t.postId){const o=n.posts.find(a=>a.id===t.postId);o&&(o.status=t.status,o.decidedBy=t.by,o.decidedAt=t.at??i?.at)}else if(f==="board.thread-status"&&t.threadId){const o=n.threads.find(a=>a.id===t.threadId);o&&(o.status=t.status,t.status!=="waiting"&&(o.waitingOn=null),t.holder&&(o.holder=t.holder))}else f==="board.thread-removed"&&t.threadId&&(n.threads=n.threads.filter(o=>o.id!==t.threadId),n.posts=n.posts.filter(o=>o.threadId!==t.threadId),Array.isArray(n.removed)||(n.removed=[]),n.removed.includes(t.threadId)||n.removed.push(t.threadId));return n}function Q({now:d=()=>Date.now(),newId:i=null,state:n=null,onEvent:f=null}={}){const t=n&&Array.isArray(n.threads)?{threads:n.threads.map(e=>({...e})),posts:(n.posts||[]).map(e=>({...e})),...Array.isArray(n.removed)&&n.removed.length?{removed:[...n.removed]}:{}}:O(),o=new Set;let a=t.posts.length+t.threads.length;const m=e=>i?i(e):`${e}_${(++a).toString(36)}${Math.random().toString(36).slice(2,6)}`,u=(e,r)=>{const l={type:e,at:d(),...r};return f&&f(e,l),l},c=e=>t.threads.find(r=>r.id===e),p=e=>t.posts.find(r=>r.id===e),w=e=>t.threads.find(r=>r.kind==="task"&&r.taskId===e),h={openThread({id:e=null,taskId:r=null,kind:l="discussion",title:s="",by:y=v,status:g="open",ask:S=null,parent:b=null,holder:k=null}={}){if(l==="task"&&r){const $=w(r);if($)return $}const A={id:e||m("th"),kind:P.includes(l)?l:"discussion",taskId:r,title:j(s,200),by:y,status:D.includes(g)?g:"open",at:d(),posts:0,...S?{ask:S}:{},...b?{parent:b}:{},...k?{holder:k}:{}};return t.threads.push(A),u("board.thread",{thread:{...A}}),A},post({id:e=null,threadId:r,by:l,kind:s="note",text:y="",refs:g=[],replyTo:S=null,status:b="open",finding:k=null,ask:A=null,proposal:$=null}={}){const I=c(r);if(!I)throw new Error(`no thread ${r}`);if(e&&p(e))return p(e);const T={id:e||m("p"),threadId:r,by:String(l||v),kind:K.includes(s)?s:"note",text:j(y,U),refs:G(g),replyTo:S,status:X.includes(b)?b:"open",at:d(),...k?{finding:k}:{},...A?{ask:A}:{},...$&&typeof $=="object"?{proposal:$}:{}};t.posts.push(T),I.lastAt=T.at,I.lastBy=T.by,I.posts=(I.posts||0)+1,u("board.post",{post:{...T}});for(const z of o)z(T);return T},reply({postId:e,...r}){const l=p(e||r.replyTo);if(!l)throw new Error(`no post ${e}`);return h.post({...r,threadId:l.threadId,replyTo:l.id})},decide(e,r,l=x){const s=p(e);return!s||!["approved","rejected","proposed","open"].includes(r)?null:(s.status=r,s.decidedBy=l,s.decidedAt=d(),u("board.decision",{postId:e,status:r,by:l,at:s.decidedAt}),s)},setThreadStatus(e,r,l={}){const s=c(e);return!s||!D.includes(r)?null:(s.status=r,r!=="waiting"&&(s.waitingOn=null),Object.assign(s,l),u("board.thread-status",{threadId:e,status:r,...l}),s)},removeThread(e,{by:r=x}={}){const l=c(e);return!l||l.kind==="ask"&&l.status==="waiting"?null:(t.threads=t.threads.filter(s=>s.id!==e),t.posts=t.posts.filter(s=>s.threadId!==e),(t.removed||=[]).push(e),u("board.thread-removed",{threadId:e,by:r}),l)},ask({taskId:e=null,by:r,type:l="info",text:s,options:y=[],timeoutMs:g=0,title:S=""}={}){const b={type:L.includes(l)?l:"info",options:(Array.isArray(y)?y:[]).map(String).slice(0,6),timeoutMs:g},k=h.openThread({taskId:e,kind:"ask",title:S||j(s,120),by:r,status:"waiting",ask:b});k.waitingOn=x;const A=h.post({threadId:k.id,by:r,kind:"question",text:s,ask:b});return{thread:k,post:A}},answer(e,{id:r=null,text:l,by:s=x}={}){if(!c(e))return null;const g=h.post({id:r,threadId:e,by:s,kind:"answer",text:l});return h.setThreadStatus(e,"resolved",{answeredAt:g.at}),g},thread:c,threadForTask:w,threads:()=>t.threads.map(e=>({...e})),posts:(e=null)=>t.posts.filter(r=>!e||r.threadId===e).map(r=>({...r})),postById:p,waiting:()=>t.threads.filter(e=>e.kind==="ask"&&e.status==="waiting").map(e=>({...e})),state:()=>({threads:t.threads.map(e=>({...e})),posts:t.posts.map(e=>({...e})),...t.removed?.length?{removed:[...t.removed]}:{}}),add(e,{by:r=null}={}){let l=0;for(const s of Array.isArray(e)?e:[e]){if(!s||!s.text)continue;const y=s.taskId?w(s.taskId)||h.openThread({taskId:s.taskId,kind:"task",title:s.taskId}):t.threads.find(g=>g.kind==="discussion"&&g.title==="findings")||h.openThread({kind:"discussion",title:"findings"});h.post({id:s.id,threadId:y.id,by:r||s.role||v,kind:"finding",text:s.text,refs:s.refs,finding:{kind:s.kind||"claim",confidence:s.confidence??null}}),l+=1}return l},all:()=>t.posts.filter(e=>e.kind==="finding").map(_(t)),byTask:e=>h.all().filter(r=>r.taskId===e),byRole:e=>h.all().filter(r=>r.role===e),onFinding(e){const r=l=>{l.kind==="finding"&&e(_(t)(l))};return o.add(r),()=>o.delete(r)},get size(){return t.posts.filter(e=>e.kind==="finding").length}};return h}function _(d){return i=>{const n=d.threads.find(f=>f.id===i.threadId);return{id:i.id,kind:i.finding?.kind||"claim",text:i.text,refs:i.refs||[],confidence:i.finding?.confidence??null,role:i.by,taskId:n?.taskId||null,at:i.at,status:i.status,...i.finding?.prior?{prior:!0}:{}}}}function Z(d){const i=d&&Array.isArray(d.posts)?d:O();return i.posts.filter(n=>n.kind==="finding").map(_(i))}function ee(d,{taskIds:i=null,max:n=M,role:f=null}={}){const t=d&&typeof d.state=="function"?d.state():d&&Array.isArray(d.posts)?d:null,o=t?C(t,{taskIds:i,role:f}):H(d,i);if(!o.length)return"";const a=t?"The board so far":"Findings so far",m=o.join(`
3
- `);if(m.length<=n)return`${a}:
4
- ${m}`;const u=[];let c=0;for(let p=o.length-1;p>=0&&!(c+o[p].length+1>n);p-=1)u.unshift(o[p]),c+=o[p].length+1;return`${a} (${o.length-u.length} earlier lines omitted for length):
5
- ${u.join(`
6
- `)}`}function H(d,i){return(d||[]).filter(n=>!i||i.includes(n.taskId)).map(n=>`- [${n.kind}${n.role?` · ${n.role}`:""}${n.confidence!=null?` · ${Math.round(n.confidence*100)}%`:""}] ${n.text}${n.refs?.length?` (refs: ${n.refs.join(", ")})`:""}`)}function C(d,{taskIds:i,role:n}){const f=[],t=d.posts,o=d.threads.filter(a=>a.kind==="task"?!i||i.includes(a.taskId):a.kind==="ask"?a.status==="resolved"&&(!n||a.by===n||a.by===v):a.kind==="discussion");for(const a of o){const m=t.filter(c=>c.threadId===a.id&&c.status!=="rejected");if(!m.length)continue;f.push(`## ${a.kind}${a.by&&a.by!==v?` by ${a.by}`:""}: ${a.title}${a.holder?` (held by ${a.holder})`:""}${a.status==="resolved"&&a.kind==="ask"?" (answered)":""}`);const u=(c,p)=>{const w=[c.kind==="finding"?c.finding?.kind||"claim":c.kind,c.by,c.finding?.confidence!=null?`${Math.round(c.finding.confidence*100)}%`:null,c.status==="approved"?"APPROVED":c.status==="proposed"?"proposed":null,c.kind==="decision"||c.by===x?"SETTLED":null].filter(Boolean).join(" · ");f.push(`${" ".repeat(p)}- [${w}] ${c.text}${c.refs?.length?` (refs: ${c.refs.join(", ")})`:""}`);for(const h of m.filter(e=>e.replyTo===c.id))u(h,p+1)};for(const c of m.filter(p=>!p.replyTo))u(c,0)}return f}function te(d){return(d||[]).filter(i=>i.kind==="claim"&&i.text).map(i=>({text:i.text,refs:(i.refs||[]).map(n=>{const f=/^([a-z][a-z0-9_-]*):(?!\/\/)(.+)$/.exec(String(n));return f?{kind:f[1],id:f[2]}:{kind:"url",id:String(n)}}),by:i.role||"team",confidence:i.confidence}))}export{L as ASK_TYPES,M as BOARD_TEXT_MAX,B as FINDINGS_SCHEMA,N as FINDING_KINDS,E as MAX_FINDINGS_PER_TASK,U as MAX_POST_TEXT,x as PERSON,K as POST_KINDS,X as POST_STATUSES,v as RUNNER,P as THREAD_KINDS,D as THREAD_STATUSES,ee as boardText,Q as createBoard,O as emptyBoardState,W as findingsInstruction,Z as findingsOf,J as foldBoard,Y as parseFindings,te as toBriefClaims};
1
+ export*from"@chatpanel/events/team-board.js";
@@ -1 +1 @@
1
- import{foldBoard as I,emptyBoardState as g}from"./team-board.js";const p=Object.freeze(["planning","running","merging","waiting"]),A=Object.freeze(["waiting","stopped","failed","partial","over-budget","answered"]),w=2e4;function x({id:e,client:a="",now:n=Date.now()}={}){return{id:e,client:String(a||"").slice(0,40),createdAt:n,lastEventAt:n,status:"planning",team:"",request:"",roles:[],plan:null,tasks:[],jobs:[],board:[],threads:g(),checkpoint:null,proposal:null,usage:null,stopRequested:null,startedAt:null,endedAt:null}}const r=(e,a)=>e.tasks.find(n=>n.id===a);function S(e,a){const n=String(a?.type||""),t=a?.payload&&typeof a.payload=="object"?a.payload:a||{},d=Number(a?.at)||Date.now();switch(e.lastEventAt=d,n){case"run.started":case"run.resumed":e.team=t.team||e.team,e.request=t.request??e.request,e.budget=t.budget||e.budget,e.roles=Array.isArray(t.roles)?t.roles:e.roles,e.status="planning",e.startedAt=e.startedAt||d,n==="run.resumed"&&(e.endedAt=null,e.checkpoint=null,e.resumedAt=d);break;case"plan.ready":e.plan={by:t.by||"fixed",tasks:Array.isArray(t.tasks)?t.tasks:[]},e.tasks=e.plan.tasks.map(s=>({...r(e,s.id)||{},id:s.id,role:s.role,title:s.title,status:r(e,s.id)?.status==="ok"?"ok":s.parent&&!s.role?"unassigned":"pending",findings:r(e,s.id)?.findings||0,...s.parent?{parent:s.parent,requestedBy:s.requestedBy||null}:{},...s.grants?{grants:s.grants,why:s.why||""}:{},...s.kind?{kind:s.kind}:{}})),e.status="running";break;case"task.requested":if(t.taskId&&!r(e,t.taskId)){const s={id:t.taskId,role:null,title:t.title||t.taskId,prompt:t.prompt||"",dependsOn:Array.isArray(t.dependsOn)?t.dependsOn:[],parent:t.parent||null,requestedBy:t.by||null,needs:t.needs||null,depth:t.depth||1,wait:t.wait!==!1};e.plan&&(e.plan.tasks=[...e.plan.tasks||[],s]),e.tasks.push({id:s.id,role:null,title:s.title,status:"requested",findings:0,parent:s.parent,requestedBy:s.requestedBy,needs:s.needs,requestedAt:d})}break;case"task.added":if(t.taskId&&!r(e,t.taskId)){const s={id:t.taskId,role:t.role||null,title:t.title||t.taskId,dependsOn:Array.isArray(t.dependsOn)?t.dependsOn:[],...t.kind?{kind:t.kind}:{}};e.plan&&(e.plan.tasks=[...e.plan.tasks||[],s]),e.tasks.push({id:s.id,role:s.role,title:s.title,status:"pending",findings:0,...t.kind?{kind:t.kind}:{}})}break;case"task.taken":{const s=r(e,t.taskId);s&&(s.role=t.role,s.status="pending",s.takenBy={by:t.by||"fit",role:t.role,fit:t.fit??null,reasons:t.reasons||[],agentId:t.agentId||null,engine:t.engine||null,why:t.why||"",at:d});const o=e.plan?.tasks?.find(l=>l.id===t.taskId);o&&(o.role=t.role);break}case"task.posted":{const s=r(e,t.taskId);s&&(s.job=t.job||null),t.job&&!e.jobs.some(o=>o.id===t.job.id)&&e.jobs.push({...t.job,taskId:t.taskId,at:d});break}case"task.proposed":{const s=r(e,t.taskId);s&&(s.proposal={agent:t.agent||null,threadId:t.threadId||null,postId:t.postId||null,why:t.why||"",at:d});break}case"task.unassigned":{const s=r(e,t.taskId);s&&(s.status="unassigned",s.error=t.why||null,s.endedAt=d);const o=e.jobs.find(l=>l.taskId===t.taskId);o&&(o.status="failed");break}case"task.nudged":{const s=r(e,t.taskId);s&&(s.nudged=[...s.nudged||[],{grants:t.grants||[],at:d}]);break}case"run.role-added":if(t.role?.id&&!e.roles.includes(t.role.id)){e.roles.push(t.role.id),e.recruited=[...e.recruited||[],{...t.role,jobId:t.jobId||null,at:d}];const s=e.jobs.find(o=>o.id===t.jobId);s&&(s.status="recruited",s.recruited={agentId:t.role.agent||t.role.id,engine:t.role.engine||null,at:d})}break;case"task.started":{let s=r(e,t.taskId);!s&&t.taskId&&(s={id:t.taskId,role:t.role||null,title:t.title||t.taskId,status:"pending",findings:0,...t.taskId==="merge"?{kind:"merge"}:{}},e.tasks.push(s)),s&&(s.status="running",s.startedAt=d,s.error=null),e.status="running";break}case"task.model":{const s=r(e,t.taskId);s&&(s.model=t.model,s.attempts=[...s.attempts||[],{model:t.model,...t.label?{label:t.label}:{},at:d,attempt:t.attempt}]);break}case"task.routed":{const o=r(e,t.taskId)?.attempts?.at?.(-1);o&&t.engine&&(o.attempt==null||o.attempt===t.attempt)&&(o.engine=t.engine);break}case"task.step":{const s=r(e,t.taskId);s&&Array.isArray(t.steps)&&(s.transcript=[...s.transcript||[],...t.steps]);break}case"task.handoff":{const s=r(e,t.taskId);s&&(s.model=t.to,s.handoffs=[...s.handoffs||[],{from:t.from,to:t.to,by:t.by,reason:t.reason,at:d}]);break}case"task.tool":{const s=r(e,t.taskId);s&&(s.tools=(s.tools||0)+1);break}case"task.delta":{const s=r(e,t.taskId);s&&(s.text=String(t.text||"").slice(0,w));break}case"task.finding":if(t.finding&&t.finding.text){e.board.push({...t.finding,at:d});const s=r(e,t.taskId);s&&(s.findings+=1)}break;case"task.waiting":{const s=r(e,t.taskId);s&&(s.status="waiting",s.waitingOn=t.threadId);break}case"task.done":case"task.failed":{const s=r(e,t.taskId);s&&(s.status=t.status||(n==="task.done"?"ok":"failed"),s.error=t.error||null,s.ms=t.ms,s.endedAt=d);const o=e.jobs.find(l=>l.taskId===t.taskId);o&&(o.status=n==="task.done"?"done":"failed",o.endedAt=d);break}case"run.merging":e.status="merging";break;case"run.waiting":e.status="running";break;case"run.usage":e.usage=t.usage||e.usage;break;case"run.done":e.status=t.status||"completed",e.usage=t.usage||e.usage,e.proposal=t.proposal??e.proposal,e.endedAt=d,t.checkpoint&&(e.checkpoint=t.checkpoint);break;case"run.stop-requested":e.stopRequested=d;break;case"board.thread":case"board.post":case"board.decision":case"board.thread-status":case"board.thread-removed":e.threads=I(e.threads||g(),a),n==="board.thread-status"&&t.status!=="waiting"&&e.status==="waiting"&&!(e.threads.threads||[]).some(s=>s.kind==="ask"&&s.status==="waiting")&&(e.status="answered");break;default:break}return e}function E(e,a,n={}){const t=x({id:e,...n});for(const d of a||[])S(t,d);return t}function N(e){return e?.plan?.tasks?.length?e.checkpoint?.plan?.tasks?.length?{...e.checkpoint,board:e.threads&&e.threads.threads?.length>=(e.checkpoint.board?.threads?.length||0)?e.threads:e.checkpoint.board}:{runId:e.id,startedAt:e.startedAt||e.createdAt,plan:e.plan,tasks:e.tasks.map(a=>({id:a.id,role:a.role,title:a.title,status:a.status==="running"||a.status==="pending"?"stopped":a.status,text:a.text||"",error:a.error||null,transcript:a.transcript||[],attempts:a.attempts||[],usage:null})),board:e.threads||g(),budget:{cap:e.usage?.cap||e.budget||{},spent:e.usage?.spent||{}},budgetAsked:!1}:null}function v(e){return e?.plan?.tasks?.length?A.includes(e.status)?!0:!!e.stale&&p.includes(e.status):!1}function O(e,{now:a=Date.now()}={}){const n=e?.usage?.cap||e?.budget||null;if(!n||!Object.keys(n).length)return null;const t={tokens:0,calls:0,usd:0,ms:0,...e?.usage?.spent||{}},d=q(e,{now:a});p.includes(e?.status)&&e?.startedAt&&(t.ms=Math.max(t.ms||0,(d.key==="stalled"&&Number(e.lastEventAt)||a)-e.startedAt));const s=n.tokens?Math.min(100,Math.round((t.tokens||0)/n.tokens*100)):n.ms?Math.min(100,Math.round((t.ms||0)/n.ms*100)):null,o=j.filter(l=>n[l]&&(t[l]||0)>=n[l]);return{cap:n,spent:t,pct:s,exhausted:e?.usage?.exhausted||o[0]||null,over:o}}const j=["tokens","calls","usd","ms"],$=2*6e4;function q(e,{now:a=Date.now(),stalledAfterMs:n=$}={}){const t=String(e?.status||"planning"),d=Number.isFinite(e?.quietMs)?e.quietMs:Math.max(0,a-(Number(e?.lastEventAt)||a)),s=o=>{const l=Math.round(o/1e3);return l<60?`${l} s`:l<3600?`${Math.round(l/60)} min`:`${Math.round(l/3600)} h`};return t==="waiting"?{key:"waiting",label:"waiting on you",tone:"warn",detail:""}:p.includes(t)?e?.stale===!0||d>n?{key:"stalled",label:"stalled",tone:"err",detail:`no events for ${s(d)} — its client stopped writing; Resume here picks it up from the record`}:{key:"running",label:t==="merging"?"merging":t==="planning"?"planning":"running",tone:"on",detail:`last event ${s(d)} ago`}:t==="completed"?{key:"done",label:"done",tone:"ok",detail:""}:t==="partial"?{key:"partial",label:"done with failures",tone:"warn",detail:"a member failed; the rest merged"}:t==="answered"?{key:"answered",label:"answered — resume to continue",tone:"warn",detail:""}:t==="over-budget"?{key:"over-budget",label:"over budget",tone:"err",detail:"stopped with what it had"}:t==="stopped"?{key:"stopped",label:"stopped",tone:"muted",detail:""}:t==="failed"?{key:"failed",label:"failed",tone:"err",detail:""}:{key:t,label:t,tone:"muted",detail:""}}function _(e,{team:a="",request:n="",excludeId:t=null,minSimilarity:d=.6,maxAgeMs:s=168*36e5,now:o=Date.now(),limit:l=3}={}){const f=i=>new Set(String(i||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(c=>c.length>2)),u=f(n);if(!u.size)return[];const h=i=>{const c=f(i);if(!c.size)return 0;let b=0;for(const y of u)c.has(y)&&(b+=1);return b/Math.max(u.size,c.size)};return(e||[]).filter(i=>i&&i.id&&i.id!==t&&(!a||i.team===a)&&!p.includes(i.status)&&(Number(i.findings)||(Array.isArray(i.board)?i.board.length:0))>0&&o-(Number(i.createdAt)||0)<=s).map(i=>({id:i.id,at:i.createdAt,similarity:Math.round(h(i.request)*100)/100,findings:Number(i.findings)||(Array.isArray(i.board)?i.board.length:0),status:i.status})).filter(i=>i.similarity>=d).sort((i,c)=>c.similarity-i.similarity||c.at-i.at).slice(0,l)}const m=e=>{const a=Math.max(0,Math.round((Number(e)||0)/1e3));return a>=60?`${Math.floor(a/60)}m${String(a%60).padStart(2,"0")}s`:`${a}s`},k=e=>(Number(e)||0).toLocaleString("en-US");function B(e){if(!e?.cap)return"";const{cap:a,spent:n}=e,t=d=>(e.over||[]).includes(d)?" (over)":"";return[a.tokens?`${k(n.tokens)} / ${k(a.tokens)} tokens${t("tokens")}`:"",a.calls?`${k(n.calls)} / ${k(a.calls)} calls${t("calls")}`:"",a.usd?`$${(Number(n.usd)||0).toFixed(2)} / $${Number(a.usd).toFixed(2)}${t("usd")}`:"",a.ms?`${m(n.ms)} / ${m(a.ms)}${t("ms")}`:""].filter(Boolean).join(" · ")}export{p as LIVE_RUN_STATUSES,A as RESUMABLE_RUN_STATUSES,$ as STALLED_AFTER_MS,N as checkpointFrom,B as describeSpend,x as emptyRun,S as foldRun,v as isResumable,_ as priorWorkFor,E as runFromEvents,q as runState,O as spendOf};
1
+ export*from"@chatpanel/events/team-record.js";
package/src/team.js CHANGED
@@ -1 +1 @@
1
- import{validateBudget as y,normalizeBudget as x}from"./budget.js";import{normalizeEngineSpec as O,validateEngineSpec as j,tierOf as $}from"./engine.js";const k=/^[a-z][a-z0-9_-]{0,63}$/i,E=/^[a-z][a-z0-9_-]{0,31}$/i,c=Object.freeze(["model","subagent","recipe"]),l=Object.freeze(["cheap","balanced","strong"]),p=Object.freeze(["judge","converge","concat","first"]),g=Object.freeze(["fixed","planner"]),N=Object.freeze(["none","data","web","mcp","history","shell","fs:write","scm:read","scm:push","scm:pr","scm:merge"]),M=Object.freeze(["shell","fs:write","scm:read","scm:push","scm:pr","scm:merge"]),f=/^(none|data|web|history|mcp|mcp:[a-zA-Z0-9_.:-]{1,64}|shell|fs:write|scm:(read|push|pr|merge))$/,h=8,R=/^[a-z][a-z0-9_-]{0,63}$/i;class T extends Error{constructor(t,i){super(i),this.name="TeamError",this.code=t}}const u=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function m(e){const t=(Array.isArray(e)?e:typeof e=="string"?[e]:[]).map(n=>String(n||"").trim()).filter(Boolean),i=[...new Set(t.filter(n=>f.test(n)))];return!i.length||i.includes("none")?["none"]:i}function b(e){const t=[];if(!u(e))return{ok:!1,errors:["team must be an object"]};if(k.test(String(e.name||""))||t.push("name: a short identifier (letters, digits, _ -)"),!Array.isArray(e.roles)||!e.roles.length)t.push("roles: a non-empty array");else{e.roles.length>h&&t.push(`roles: at most ${h}`);const n=new Set;e.roles.forEach((s,o)=>{const r=`roles[${o}]`;if(!u(s)){t.push(`${r}: must be an object`);return}E.test(String(s.id||""))?n.has(s.id)&&t.push(`${r}.id: duplicate "${s.id}"`):t.push(`${r}.id: a short identifier`),n.add(s.id),s.mode!==void 0&&!c.includes(s.mode)&&t.push(`${r}.mode: one of ${c.join(", ")}`),s.prefer!==void 0&&!l.includes(s.prefer)&&t.push(`${r}.prefer: one of ${l.join(", ")}`),(s.mode||"model")==="recipe"&&!s.recipe&&t.push(`${r}.recipe: a recipe name is required in recipe mode`),s.agent!==void 0&&s.agent!==null&&!R.test(String(s.agent))&&t.push(`${r}.agent: an agent id`),(s.mode||"model")!=="recipe"&&!s.agent&&!String(s.prompt||"").trim()&&t.push(`${r}.prompt: what this role does`),t.push(...j(s.engine,`${r}.engine`));const a=(Array.isArray(s.grants)?s.grants:[]).filter(d=>!f.test(String(d)));a.length&&t.push(`${r}.grants: not grantable: ${a.join(", ")}${a.some(d=>/^page/.test(String(d)))?" (a tab is one person's; a team may not act on it)":""}`)})}e.merge!==void 0&&!p.includes(e.merge)&&t.push(`merge: one of ${p.join(", ")}`),e.plan!==void 0&&!g.includes(e.plan)&&t.push(`plan: one of ${g.join(", ")}`),e.judge!==void 0&&e.judge!==null&&!(Array.isArray(e.roles)&&e.roles.some(n=>n?.id===e.judge))&&t.push("judge: must name one of the roles");const i=y(e.budget);return i.ok||t.push(...i.errors.map(n=>`budget: ${n}`)),{ok:t.length===0,errors:t}}function S(e,{builtin:t=!1}={}){const i=b(e);if(!i.ok)throw new T("INVALID",i.errors.join("; "));return{name:String(e.name),description:String(e.description||"").trim().slice(0,300),plan:g.includes(e.plan)?e.plan:"fixed",merge:p.includes(e.merge)?e.merge:e.judge?"judge":"concat",judge:e.judge||null,roles:e.roles.map(n=>({id:String(n.id),name:String(n.name||n.id).slice(0,60),mode:c.includes(n.mode)?n.mode:"model",prefer:l.includes(n.prefer)?n.prefer:n.engine?$(n.engine):"balanced",...n.model?{model:String(n.model)}:{},...n.agent?{agent:String(n.agent)}:{},...n.engine?{engine:O(n.engine)}:{},prompt:String(n.prompt||"").trim().slice(0,4e3),...n.agent&&!(Array.isArray(n.grants)&&n.grants.length)?{}:{grants:m(n.grants)},...n.recipe?{recipe:String(n.recipe)}:{},...Array.isArray(n.dependsOn)?{dependsOn:n.dependsOn.map(String).filter(s=>s!==n.id)}:{},...Array.isArray(n.skills)&&n.skills.length?{skills:n.skills.map(String).slice(0,32)}:{},...n.workdir?{workdir:String(n.workdir).slice(0,400)}:{},...n.egress==="redacted"||n.egress==="delegated"?{egress:n.egress}:{},...n.memoryScope?{memoryScope:String(n.memoryScope).slice(0,120)}:{}})),budget:x(e.budget),enabled:e.enabled!==!1,...e.origin&&u(e.origin)?{origin:{...e.origin}}:{},...t?{builtin:!0}:{},...e.createdAt?{createdAt:e.createdAt}:{}}}function D(e){return Object.freeze(S(e))}function G(e,t,i=""){const n=m(e);return n.includes("none")||t==="page"?!1:t==="mcp"?n.includes("mcp")||!!i&&n.includes(`mcp:${i}`):n.includes(t)}const w=["read","push","pr","merge"];function B(e,t){const i=m(e),n=w.indexOf(String(t||"").replace(/^scm:/,""));return n<0||i.includes("none")?!1:Math.max(-1,...i.filter(o=>o.startsWith("scm:")).map(o=>w.indexOf(o.slice(4))))>=n}function F(e){const t=e.model||e.prefer||"balanced",i=(e.grants||["none"]).join(", ");return`${e.name||e.id}${e.agent?` (agent: ${e.agent})`:""} — ${t}${e.mode&&e.mode!=="model"?` (${e.mode})`:""} · tools: ${i}`}const z=Object.freeze([{name:"research",description:"Research a question from the web and your own notes, then write it up.",plan:"fixed",merge:"judge",judge:"writer",roles:[{id:"researcher",prompt:"Research the request thoroughly. Search the web and the user's own history. Report each fact as a finding with where it came from; note disagreements between sources.",prefer:"balanced",grants:["web","data"]},{id:"writer",prompt:"Write the answer the user asked for from the board's findings, citing them. Say plainly what was not found.",prefer:"strong",grants:["none"]}],budget:{tokens:4e4,ms:3e5}},{name:"review",description:"Two independent reads of a draft, reconciled into one set of comments.",plan:"fixed",merge:"converge",roles:[{id:"editor",prompt:"Read the draft as an editor: structure, clarity, what is missing. One finding per issue, with the passage it refers to.",prefer:"strong",grants:["none"]},{id:"checker",prompt:"Read the draft as a fact-checker: every claim that could be wrong, with what you checked against. Use the user's history and the web.",prefer:"balanced",grants:["data","web"]}],budget:{tokens:3e4,ms:24e4}},{name:"feature",description:"Architect plans, an Implementer builds on a branch, Reviewer and Tester check, Scribe writes it up. The Architect judges.",plan:"planner",merge:"judge",judge:"architect",roles:[{id:"architect",agent:"architect"},{id:"implementer",agent:"implementer",dependsOn:["architect"]},{id:"reviewer",agent:"reviewer",dependsOn:["implementer"]},{id:"tester",agent:"tester",dependsOn:["implementer"]},{id:"scribe",agent:"scribe",dependsOn:["reviewer","tester"]}],budget:{tokens:4e5,ms:36e5}},{name:"fix",description:"One Implementer fixes it on a branch, the Tester runs the guard, the Scribe notes it.",plan:"fixed",merge:"concat",roles:[{id:"implementer",agent:"implementer"},{id:"tester",agent:"tester",dependsOn:["implementer"]},{id:"scribe",agent:"scribe",dependsOn:["tester"]}],budget:{tokens:15e4,ms:18e5}},{name:"docs",description:"The Architect decides what the docs should say; the Scribe proposes the text.",plan:"fixed",merge:"concat",roles:[{id:"architect",agent:"architect"},{id:"scribe",agent:"scribe",dependsOn:["architect"]}],budget:{tokens:8e4,ms:9e5}},{name:"release",description:"The Tester runs the guard on the merged branch, Release bumps and asks before publishing, the Scribe records the version.",plan:"fixed",merge:"concat",roles:[{id:"tester",agent:"tester"},{id:"release",agent:"release",dependsOn:["tester"]},{id:"scribe",agent:"scribe",dependsOn:["release"]}],budget:{tokens:6e4,ms:18e5}}]);function _(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^[^a-z]+/,"").replace(/-+$/,"").slice(0,64)}function I(){return z.map(e=>({...e,roles:e.roles.map(t=>({...t,...t.grants?{grants:[...t.grants]}:{},...t.dependsOn?{dependsOn:[...t.dependsOn]}:{}})),budget:{...e.budget}}))}function q(){return{name:"",description:"",plan:"fixed",merge:"concat",judge:null,roles:[{id:"role1",prompt:"",prefer:"balanced",grants:["none"]}],budget:{tokens:2e4,ms:3e5}}}const A=e=>String(Array.isArray(e)?e.join(","):e||"").split(/[,\s]+/).map(t=>t.trim()).filter(Boolean);function C(e){const t=(Array.isArray(e.roles)?e.roles:[]).map(r=>({id:String(r.id||"").trim(),name:String(r.name||"").trim()||void 0,prompt:String(r.prompt||""),prefer:r.prefer||"balanced",...r.model?{model:String(r.model)}:{},...r.agent?{agent:String(r.agent).trim()}:{},...r.engine?{engine:r.engine}:{},...Array.isArray(r.dependsOn)?{dependsOn:r.dependsOn.map(String)}:{},...A(r.grants).length?{grants:A(r.grants)}:r.agent?{}:{grants:["none"]}})),i={};for(const r of["tokens","calls","ms","usd"]){const a=Number(e.budget?.[r]);e.budget?.[r]!==""&&e.budget?.[r]!=null&&Number.isFinite(a)&&a>0&&(i[r]=a)}const n=e.merge||"concat",s={name:_(e.name),description:String(e.description||"").trim(),plan:e.plan||"fixed",merge:n,judge:n==="judge"&&(e.judge||t[t.length-1]?.id)||null,roles:t,budget:i,enabled:e.enabled!==!1,...e.createdAt?{createdAt:e.createdAt}:{}},o=b(s);return o.ok?{ok:!0,team:S(s)}:{ok:!1,errors:o.errors}}export{R as AGENT_REF_RE,N as GRANTABLE,f as GRANT_RE,h as MAX_ROLES,p as MERGE_POLICIES,g as PLAN_MODES,E as ROLE_ID_RE,c as ROLE_MODES,l as ROLE_PREFERS,z as STARTER_TEAMS,k as TEAM_NAME_RE,T as TeamError,M as WORK_GRANTS,q as blankTeam,D as defineTeam,F as describeRole,G as grantAllows,m as normalizeGrants,S as normalizeTeam,B as scmAllows,_ as slugTeamName,I as starterTeams,C as teamFromForm,b as validateTeam};
1
+ export*from"@chatpanel/events/team.js";
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.99.0";export{o as VERSION};
1
+ const o="0.103.0";export{o as VERSION};
@@ -1,19 +1 @@
1
- import{summarizeSearch as l,engineLabel as h}from"./search-outcome.js";const d={nothing:"nothing found",blocked:"search blocked",resting:"every engine resting",offline:"offline","no-engines":"no engine on"},c="web_search",y='You can call web_search to look up current information from the web — prices, news, recent events, documentation, or anything time-sensitive or that may have changed since your training. Call it whenever the user asks about such things instead of guessing or saying you are unsure. Cite results inline as markdown links — e.g. ([1](https://…)) — never HTML, <sup>, or bare numbers, and finish with a "Sources" list of the links you used.',g=Object.freeze({name:c,annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!0},description:"Search the web and return ranked result snippets with their source URLs. Use this for current events, live prices/quotes, news, product/library docs, or any fact you are unsure about or that may have changed since training — prefer it over guessing.",parameters:{type:"object",properties:{query:{type:"string",description:"The search query — a few keywords work best."}},required:["query"],additionalProperties:!1}});function p(e){if(!e?.results?.length){if(Array.isArray(e?.asked)||Array.isArray(e?.resting)){const{line:r,advice:s}=l(e);return`No web results for "${e?.query||""}"${r?` (${r})`:""}. ${s} Do NOT conclude the information is unavailable; say plainly that the search failed and why.`}const n=(e?.engines||[]).join(", ");return`No web results for "${e?.query||""}"`+(n?` (searched: ${n}).`:".")+" This may mean the engine blocked the request rather than that nothing exists — do NOT conclude the information is unavailable. Try a shorter, more general query (drop dates and qualifiers), and tell the user they can enable another search engine in ChatPanel settings if it keeps failing."}const i=Array.isArray(e.engines)?e.engines:[],u=e.results.map(n=>`[${n.rank}] [${n.title}](${n.url})`).join(`
2
- `),a=e.results[0].url,t=`Web search results for "${e.query}" (engines: ${i.join(", ")}).
3
-
4
- Citation rules: when a claim draws on a result below, cite it inline as a markdown link to that result's URL — e.g. ([1](${a})). Cite multiple sources as separate links: ([1](url)) ([3](url)). Do NOT output HTML, <sup>, or bare bracket numbers like [1] — every citation must be a clickable markdown link. Finish with a "Sources" section that repeats, as markdown links, each source you cited.
5
-
6
- Sources:
7
- ${u}`,o=e.results.map(n=>`### [${n.rank}] ${n.title}
8
- <${n.url}>
9
-
10
- ${n.text}`).join(`
11
-
12
- ---
13
-
14
- `);return`${t}
15
-
16
- ---
17
- Result details:
18
-
19
- ${o}`}function m({search:e}={}){if(typeof e!="function")throw new Error("webSearchToolProvider: search required");return{specs:[g],system:y,async execute(i,u){if(i!==c)return JSON.stringify({error:`Unknown tool: ${i}`});const a=String(u?.query||"").trim();if(!a)return"No query provided to web_search.";try{const t=await e(a),o=[...new Set((t?.results||[]).map(s=>s.engine).filter(Boolean))].map(s=>h(s)),n=(o.length?o:t?.engines||[]).join(", "),r=!t?.results?.length&&Array.isArray(t?.asked)?d[l(t).status]:"";return{text:p(t),note:r?`ChatPanel · ${r}`:n?`ChatPanel · ${n}`:"ChatPanel"}}catch(t){return`web_search failed: ${t?.message||t}`}}}}export{g as WEB_SEARCH_SPEC,c as WEB_SEARCH_TOOL_NAME,y as WEB_SEARCH_TOOL_SYSTEM,p as searchResultsToText,m as webSearchToolProvider};
1
+ export*from"@chatpanel/events/web-search-tool.js";
package/src/web-search.js CHANGED
@@ -1 +1 @@
1
- const m=Object.freeze([Object.freeze({id:"startpage",name:"Startpage",url:"https://www.startpage.com/sp/search?query=%s",enabled:!0}),Object.freeze({id:"duckduckgo",name:"DuckDuckGo",url:"https://html.duckduckgo.com/html/?q=%s",enabled:!0}),Object.freeze({id:"google",name:"Google",url:"https://www.google.com/search?q=%s",enabled:!1}),Object.freeze({id:"bing",name:"Bing",url:"https://www.bing.com/search?q=%s",enabled:!0})]),d=5;function E(n,t,{assertFetchable:e}={}){const r=String(n||"").trim();if(!/^https:\/\//i.test(r))throw new Error("Search engine URL must start with https://");if(!r.includes("%s")&&!r.includes("{q}"))throw new Error("Search engine URL must contain a %s (or {q}) query placeholder");const s=r.replace(/%s|\{q\}/g,encodeURIComponent(String(t||"").trim()));return typeof e=="function"&&e(s),s}const w="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function S(n){let t=0,e=0,r="";for(const s of n){const o=w.indexOf(s);if(o<0)return"";e=e<<6|o,t+=6,t>=8&&(t-=8,r+="%"+(e>>t&255).toString(16).padStart(2,"0"))}try{return decodeURIComponent(r)}catch{return""}}function b(n){try{const t=new URL(n,"https://duckduckgo.com"),e=t.searchParams.get("uddg");if(e)return decodeURIComponent(e);const r=t.searchParams.get("url")||t.searchParams.get("u");if(r&&/^https?:/i.test(r))return r;const s=r&&/^a1[A-Za-z0-9_-]+$/.test(r)?S(r.slice(2)):"";return/^https?:\/\//i.test(s)?s:t.href}catch{return String(n||"")}}const k=/(^|\.)(startpage\.com|startmail\.com|startpage\.dev|mojeek\.com|buttondown\.(com|email)|ecosia\.org|duckduckgo\.com|search\.brave\.com|qwant\.com|admarketplace\.(net|com)|googleadservices\.com|doubleclick\.net)$/i,R=/^\/(aclick|pagead\/aclk|aclk)\b/i;function y(n,t=""){const e=String(n||"").toLowerCase();if(!e||k.test(e))return!1;const r=String(t||"").split(".").slice(-2).join(".").toLowerCase();return!(r&&(e===r||e.endsWith(`.${r}`)))}function L(n,{engineHost:t="",limit:e=d,fallback:r=!1}={}){const s=[],o=new Map;for(const c of n||[]){const a=b(c?.href||"");let i;try{i=new URL(a)}catch{continue}if(i.protocol!=="https:"&&i.protocol!=="http:"||!y(i.hostname,t)||R.test(i.pathname)||r&&c.chrome)continue;const u=String(c?.text||"").replace(/\s+/g," ").trim();if(u.length<6||/^\S+\s+https?:\/\/\S+/.test(u))continue;const h=i.origin+i.pathname;if(o.has(h)){const l=o.get(h);l&&!l.snippet&&u.length>l.title.length+10&&(l.snippet=u);continue}const f={url:a,title:u,snippet:String(c?.snippet||"").replace(/\s+/g," ").trim()};if(o.set(h,f),s.push(f),s.length>=e)break}return s}const x=n=>[...new Set(String(n||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(t=>t.length>=4))],p=n=>n.replace(/(ies|ing|ed|es|s|y)$/u,""),g=(n,t)=>n.includes(t)||p(t).length>=3&&n.includes(p(t));function q(n,t){const e=x(t);if(e.length<2||!n?.length)return!1;const r=n.map(o=>`${o.title||""} ${o.snippet||""} ${o.url||""}`.toLowerCase());if(e.some(o=>o.length>=6&&!r.some(c=>g(c,o))))return!0;const s=Math.ceil(e.length/2);return!r.some(o=>e.filter(c=>g(o,c)).length>=s)}const U=/^(www\.)?(bing|google(\.[a-z]{2,3}){1,2}|duckduckgo|search\.yahoo|yandex|baidu|startpage|search\.brave)\.[a-z.]*$|^(www\.)?google\.[a-z.]+$/i;function z(n){try{const t=new URL(n);return U.test(t.hostname)&&/^\/(search|news\/search|web|html|sp\/search|s)\b/i.test(t.pathname)}catch{return!1}}function C(n,t=8){const e=[],r=new Set;for(const s of n||[])for(const o of s||[]){let c;try{const a=new URL(o.url);c=a.origin+a.pathname}catch{c=o.url}if(!r.has(c)&&(r.add(c),e.push(o),e.length>=t))return e}return e}function O(n=m){const t=(Array.isArray(n)?n:[]).filter(e=>e&&e.url&&!e.retired);return[...t.filter(e=>e.enabled!==!1),...t.filter(e=>e.enabled===!1)]}export{d as RESULTS_PER_ENGINE,m as SEARCH_ENGINES,E as buildSearchUrl,O as engineOrder,y as isResultHost,z as isSearchPage,C as mergeEngineResults,q as offTopic,L as pickResults,b as unwrapRedirect};
1
+ export*from"@chatpanel/events/web-search.js";