@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.
- package/native/darwin-arm64/chatpanel-apple-model +0 -0
- package/package.json +3 -3
- package/src/agent.js +1 -3
- package/src/budget.js +1 -1
- package/src/capability-adapters.js +1 -1
- package/src/capability-embedded.js +1 -1
- package/src/capability-endpoints.js +1 -1
- package/src/capability-providers.js +1 -3
- package/src/capability-proxy.js +1 -1
- package/src/capability-tools.js +1 -3
- package/src/cloudevents.js +1 -4
- package/src/config.js +1 -1
- package/src/coreml-stt-engine.js +3 -0
- package/src/cross-encoder.js +1 -1
- package/src/diarize-engine.js +1 -1
- package/src/embedded-models.js +1 -1
- package/src/embedder.js +1 -0
- package/src/engine-pacer.js +1 -1
- package/src/engine.js +1 -1
- package/src/event-stats.js +1 -1
- package/src/event-sync.js +1 -1
- package/src/event.js +1 -1
- package/src/extract/handler.js +1 -1
- package/src/extract-capability.js +1 -5
- package/src/extraction.js +1 -4
- package/src/gate.js +1 -1
- package/src/inference-lane.js +1 -0
- package/src/job.js +1 -5
- package/src/kb-store.js +4 -0
- package/src/kb.js +2 -0
- package/src/knowledge.js +1 -3
- package/src/mcp.js +23 -20
- package/src/memory.js +1 -2
- package/src/model-ledger.js +1 -1
- package/src/ner-engine.js +1 -1
- package/src/observability.js +1 -1
- package/src/openai.js +2 -2
- package/src/order.js +1 -1
- package/src/project.js +1 -1
- package/src/providers.js +1 -1
- package/src/read-document.js +1 -10
- package/src/recruit.js +1 -4
- package/src/ref.js +1 -1
- package/src/rrf.js +1 -1
- package/src/scorecard.js +1 -1
- package/src/search-api.js +1 -1
- package/src/search-outcome.js +1 -1
- package/src/search-searxng.js +1 -1
- package/src/segment-engine.js +1 -0
- package/src/serp-anchors.js +1 -1
- package/src/server.js +32 -32
- package/src/site-policy.js +1 -1
- package/src/structured.js +1 -4
- package/src/stt-engine.js +1 -1
- package/src/stt-models.js +1 -1
- package/src/subject-kinds.js +1 -1
- package/src/subject-name.js +1 -1
- package/src/team-board.js +1 -6
- package/src/team-record.js +1 -1
- package/src/team.js +1 -1
- package/src/version.js +1 -1
- package/src/web-search-tool.js +1 -19
- package/src/web-search.js +1 -1
package/src/mcp.js
CHANGED
|
@@ -1,46 +1,49 @@
|
|
|
1
|
-
import{loadConfig as y}from"./config.js";import{VERSION as b}from"./version.js";import{readBridgeToken as x}from"./bridge.js";import{ensureGatewayToken as k}from"./gateway-token.js";import{MEMORY_KINDS as
|
|
2
|
-
`);async function
|
|
3
|
-
`)}catch{return""}}function S(){try{return y().mcp?.ask||{}}catch{return{}}}let m="unknown";function O(t){try{const e=k();fetch(`${f()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(t)}).catch(()=>{})}catch{}}function f(){const t=process.env.CHATPANEL_GATEWAY_URL;if(t)return t.replace(/\/+$/,"");let e=4320;try{e=y().port||4320}catch{}return`http://127.0.0.1:${e}`}function C(){try{return String(y().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function J(){try{return x(y().bridge?.token||"")}catch{return x("")}}async function $(t){const e=J(),i=await fetch(C()+t,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),a=await i.json().catch(()=>({}));if(!i.ok||a.ok===!1)throw new Error(a?.error||`bridge ${i.status}`);return a}const G=[{name:"smart_search",description:'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in natural language."},queries:{type:"array",items:{type:"string"},description:"Your own 2-4 keyword formulations of it — these lead the search."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".'},before:{type:"string",description:"Latest date: a date or window like `since`."},limit:{type:"number",description:"Max fused results (default 10)."}},required:["question"]}},{name:"research",description:'Research a question about the user\'s OWN meetings, notes and past chats from the WHOLE ChatPanel store, not a few snippets: it frames the question (which kind of record, which people, which dates, the latest or the first, a count, counts per person or per month), queries every record that matches — sorted by date when the question asks for the last one, counted when it asks how many — reads the top records in full, and returns what it searched, what it found (with record ids and dates) and what those records say. Use it for "when was my last meeting with Alex", "how many calls did I have in August", "who do I meet with most", "what did we decide about pricing". For a follow-up ("no, even later", "what was it about") pass back the `previous` it returned. Cite the [id]s it gives; follow up with get_record for more of one record.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in their words."},previous:{type:"object",description:"The `previous` value the last research call returned, to continue that question (a follow-up)."}},required:["question"]}},{name:"search_history",description:'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Content keywords (topics, names, decisions) — not the meeting title."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".'},before:{type:"string",description:"Latest date: a date or relative window like `since`."},limit:{type:"number",description:"Max results (default 10)."},offset:{type:"number",description:"Skip N results for paging (default 0)."}},required:["query"]}},{name:"get_record",description:"Fetch one history record's full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Record id such as chat:abc, meeting:imp_123, or note:xyz."},maxChars:{type:"number",description:"Return at most this many characters (token management for long transcripts)."},offset:{type:"number",description:"Start at this character offset — page through with the offset the previous call reports."}},required:["id"]}},{name:"find_related",description:"Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The record id to find neighbours of."},limit:{type:"number",description:"Max related records (default 5)."}},required:["id"]}},{name:"list_history",description:"List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max items (default 50)."},offset:{type:"number",description:"Skip N items for paging (default 0)."}}}},{name:"list_briefs",description:`The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user's corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).`,inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max briefs (default 50)."},offset:{type:"number",description:"Skip N for paging (default 0)."}}}},{name:"get_brief",description:"One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.",inputSchema:{type:"object",properties:{id:{type:"string",description:"A brief id (brief:…) from list_briefs or search results."}},required:["id"]}},{name:"recall",description:"What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",inputSchema:{type:"object",properties:{text:{type:"string",description:"What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones."}}}},{name:"remember",description:`Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference ("always use pnpm"), an identity fact ("call me Alex") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.`,inputSchema:{type:"object",properties:{text:{type:"string",description:'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.'},kind:{type:"string",enum:_,description:_.map(t=>`${t}: ${R[t].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}}],N={[I]:" The gateway decides in-process unless it was turned off: ChatPanel › Settings › Runtime › Decide (or the OpenDecision container, or a server that provides `decide` under Models).",[L]:" The gateway reranks in-process unless it was turned off: ChatPanel › Settings › Runtime › Rerank (or the Reranker container, or a server that provides `rerank` under Models)."};function q(){const t=f(),e=c=>[{id:"gateway",name:"the gateway",url:`${t}${c}`,where:"this device"}],i=A({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(c,r)=>fetch(c,r)}),a=M({search:async c=>{const r=await l("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:c,limit:8,read:D.aliasRead})});return{query:c,engines:r.engines||[],results:(r.results||[]).map((n,o)=>({rank:o+1,title:n.title||n.url,url:n.url,engine:n.engine||"",text:n.read?.markdown||n.read?.text||n.snippet||""}))}}});return[i,a]}const V=q().flatMap(t=>t.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function K(t,e){const i=q().find(r=>r.specs.some(n=>n.name===t));if(!i)return null;const a=await i.execute(t,e);let c=typeof a=="string"?a:String(a?.text??a);return N[t]&&/^No (decision model|reranker) answered/.test(c)&&(c+=N[t]),c}function w(t,e){if(!t)return`Index: ${e} records (warm copy synced from ChatPanel).`;const i=new Date(t),a=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")} ${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${a} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function j(){try{const t=k();return t?{Authorization:`Bearer ${t}`}:{}}catch{return{}}}async function l(t,e){let i;try{i=await fetch(f()+t,e)}catch(c){throw new Error(`the ChatPanel gateway is not running at ${f()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${c.message}]`)}const a=await i.json().catch(()=>({}));if(!i.ok)throw new Error(a?.error?.message||`the gateway returned HTTP ${i.status} for ${t}`);return a}function g(t){if(t==null||t==="")return null;if(typeof t=="number")return t;const e=String(t).trim().toLowerCase(),i=864e5;if(e==="today")return Date.now()-i;if(e==="yesterday")return Date.now()-2*i;const a=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(a){const r=Number(a[1]),n=a[2][0],o=n==="d"?i:n==="w"?7*i:n==="m"?30*i:365*i;return Date.now()-r*o}const c=Date.parse(e);return Number.isNaN(c)?null:c}const v=(t,e)=>`${e+1}. [${t.id}] ${t.title||"(untitled)"} · ${t.type}${t.date?" · "+new Date(t.date).toISOString().slice(0,10):""}${t.snippet?`
|
|
4
|
-
${
|
|
1
|
+
import{loadConfig as y}from"./config.js";import{VERSION as b}from"./version.js";import{readBridgeToken as x}from"./bridge.js";import{ensureGatewayToken as k}from"./gateway-token.js";import{MEMORY_KINDS as P,MEMORY_KIND_NAMES as _}from"./memory.js";import{parseBriefText as E}from"./knowledge.js";import{capabilityToolsProvider as A,DECIDE_TOOL_NAME as I,RERANK_TOOL_NAME as L}from"./capability-tools.js";import{renderSearch as M,renderOutline as U,renderGraph as D,renderStatus as H}from"@chatpanel/events/kb-tool.js";import{webSearchToolProvider as B}from"./web-search-tool.js";import{SEARCH_DEFAULTS as W}from"./retrieval/search.js";import{askToolsFor as T,callAsk as F}from"./mcp-ask.js";import{CAPABILITY_TOOLS as Y,callCapability as z}from"./mcp-capabilities.js";const J="2024-11-05",G={name:"chatpanel-history",version:b},K=["ChatPanel holds the USER'S OWN meetings, notes and past chats — transcripts, decisions,","action items, summaries — which usually are NOT in the working directory.","","Keep using all your normal tools. ADDITIONALLY, whenever the user's question touches a",'meeting, call, demo, note, or past conversation ("outcome of the meeting", "what did we','decide", "action items", "notes from yesterday", a person/day/topic in their history),',"ALSO consult ChatPanel — it is the source of truth for that personal history:",' • research — for "when was my last…", "how many…", "who do I meet with most", "what was',' that meeting about": it searches the WHOLE store as the question frames it (dates, counts,'," people), reads the top records in full and returns the evidence with ids to cite."," • smart_search — START HERE: give it the question plus 2-4 of your own keyword"," phrasings; it runs them all and fuses the rankings, finding what one query misses."," • search_history — one exact keyword query, when you already know the terms. Search by"," CONTENT (not the generic meeting title). Supports filters:",' type (chat|meeting|note), since/before (dates or relative like "7d", "yesterday"),'," and limit/offset paging. Returns compact snippets, not full bodies."," • get_record — the full text of one result id; use maxChars/offset to page a long"," transcript instead of pulling it all into context."," • find_related — follow the graph: given a record id, the records most connected to it.","","ChatPanel also holds the user's MEMORY — a short list of durable facts about them (their","name, how they want answers written, what they are working on) that applies to EVERY task,","not just ones about their history:"," • recall — call it EARLY in a session, and whenever the user states a preference, to see"," what is already known. Then simply follow it; do not tell them you looked.",' • remember — save a new durable fact when they state one ("call me Alex", "always use',' pnpm"). One short sentence. Not for task details or anything true only today.'," • forget — remove one when they say it no longer holds.","Prefer these for the user's history and combine them with your other tools as you see fit.","Every result states how fresh the local copy is; if something recent is missing it may not","have synced yet — say so rather than concluding it does not exist.","","ChatPanel also runs SMALL LOCAL MODELS and a private web search on this machine:"," • decide — a sentiment, tone, urgency, spam/complaint, yes/no or pick-one judgement over"," text you already hold, answered with a probability per option in milliseconds. Call it"," instead of judging the text yourself."," • rerank — order many candidates (search hits, comments, sections) by relevance to a"," question, best first with a score, instead of reading them all."," • web_search — the user's own search (their SearXNG when one runs here), results with"," the top pages already read. Nothing leaves this machine but the query."," • redact_check — what is personal or secret in a piece of text, found by the detector on"," THIS machine. Call it before you put someone else's data into your own context, a"," commit message, an issue or a message to a third party — and whenever the user asks"," what is sensitive in something. It tells you what it could not see, so read that line."," • read_document — a URL as clean markdown through the user's own reader and cache,"," for a fraction of the context raw HTML would cost.","","ChatPanel can also hand a question to ANOTHER MODEL on this machine and give you its answer:"," • list_models — what can answer, and WHERE each one runs (on this device / a cloud)."," • ask_model — ask one. Use it for a second opinion on your own reasoning, for a model",' stronger in some domain, when the user names a model ("ask Claude what it thinks"), or'," when they want a question kept on-device — pick a `device` model and nothing leaves the"," machine. The model you ask sees your prompt and NOTHING else: no files, no shell, no web."," So paste in the code or context it needs. A slow answer returns a job id for ask_status."].join(`
|
|
2
|
+
`);async function V(){try{const n=await fetch(`${f()}/health`,{signal:AbortSignal.timeout(600)}),e=String((await n.json())?.version||"");return!e||e===b?"":["",`IMPORTANT — VERSION MISMATCH. This MCP server is ChatPanel ${b}, but the gateway`,`running on this machine is ${e}. They are different installs: your client launched`,"whichever `chatpanel-gateway` is on its PATH, and it is not the one the user is running.","The practical effect is that TOOLS MAY BE MISSING here — a newer gateway has tools this","server does not advertise. If a ChatPanel tool the user expects is not in your list, this","is why. Tell them, and tell them the fix: point the MCP config at the newer executable","(or update the older install so both are the same version)."].join(`
|
|
3
|
+
`)}catch{return""}}function S(){try{return y().mcp?.ask||{}}catch{return{}}}let m="unknown";function O(n){try{const e=k();fetch(`${f()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function f(){const n=process.env.CHATPANEL_GATEWAY_URL;if(n)return n.replace(/\/+$/,"");let e=4320;try{e=y().port||4320}catch{}return`http://127.0.0.1:${e}`}function C(){try{return String(y().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function X(){try{return x(y().bridge?.token||"")}catch{return x("")}}async function $(n){const e=X(),a=await fetch(C()+n,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),i=await a.json().catch(()=>({}));if(!a.ok||i.ok===!1)throw new Error(i?.error||`bridge ${a.status}`);return i}const Q=[{name:"smart_search",description:'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in natural language."},queries:{type:"array",items:{type:"string"},description:"Your own 2-4 keyword formulations of it — these lead the search."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".'},before:{type:"string",description:"Latest date: a date or window like `since`."},limit:{type:"number",description:"Max fused results (default 10)."}},required:["question"]}},{name:"research",description:'Research a question about the user\'s OWN meetings, notes and past chats from the WHOLE ChatPanel store, not a few snippets: it frames the question (which kind of record, which people, which dates, the latest or the first, a count, counts per person or per month), queries every record that matches — sorted by date when the question asks for the last one, counted when it asks how many — reads the top records in full, and returns what it searched, what it found (with record ids and dates) and what those records say. Use it for "when was my last meeting with Alex", "how many calls did I have in August", "who do I meet with most", "what did we decide about pricing". For a follow-up ("no, even later", "what was it about") pass back the `previous` it returned. Cite the [id]s it gives; follow up with get_record for more of one record.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in their words."},previous:{type:"object",description:"The `previous` value the last research call returned, to continue that question (a follow-up)."}},required:["question"]}},{name:"search_history",description:'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Content keywords (topics, names, decisions) — not the meeting title."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".'},before:{type:"string",description:"Latest date: a date or relative window like `since`."},limit:{type:"number",description:"Max results (default 10)."},offset:{type:"number",description:"Skip N results for paging (default 0)."}},required:["query"]}},{name:"get_record",description:"Fetch one history record's full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Record id such as chat:abc, meeting:imp_123, or note:xyz."},maxChars:{type:"number",description:"Return at most this many characters (token management for long transcripts)."},offset:{type:"number",description:"Start at this character offset — page through with the offset the previous call reports."}},required:["id"]}},{name:"find_related",description:"Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The record id to find neighbours of."},limit:{type:"number",description:"Max related records (default 5)."}},required:["id"]}},{name:"list_history",description:"List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max items (default 50)."},offset:{type:"number",description:"Skip N items for paging (default 0)."}}}},{name:"list_briefs",description:`The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user's corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).`,inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max briefs (default 50)."},offset:{type:"number",description:"Skip N for paging (default 0)."}}}},{name:"get_brief",description:"One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.",inputSchema:{type:"object",properties:{id:{type:"string",description:"A brief id (brief:…) from list_briefs or search results."}},required:["id"]}},{name:"recall",description:"What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",inputSchema:{type:"object",properties:{text:{type:"string",description:"What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones."}}}},{name:"remember",description:`Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference ("always use pnpm"), an identity fact ("call me Alex") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.`,inputSchema:{type:"object",properties:{text:{type:"string",description:'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.'},kind:{type:"string",enum:_,description:_.map(n=>`${n}: ${P[n].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}},{name:"kb_list",description:"The knowledge bases on this machine — the user's indexed documents (PDFs, office files, folders, web pages), each with its id, name and size. START HERE for any question about a document the user has, then kb_search that base. Read a base's REPORT with kb_report before reading pages: it is the map (documents, outlines, the names that bind them).",inputSchema:{type:"object",properties:{}}},{name:"kb_search",description:"Search one knowledge base for the passages that answer a question — the words (several query shapes), the meaning (vectors) and the graph (passages sharing a name with a hit) fused, a reranker on top, best first, each with its citation like [report.pdf p.12] and its passage id. Search BEFORE paging a document; pass 1–3 of your own phrasings in `queries` when you know the domain.",inputSchema:{type:"object",properties:{kb:{type:"string",description:"The base id (from kb_list)."},query:{type:"string",description:"The question, or key words."},queries:{type:"array",items:{type:"string"},description:"Your own phrasings, searched too and fused."},limit:{type:"integer",minimum:1,maximum:30,description:"How many passages (default 8)."},doc:{type:"string",description:"Only this document id."}},required:["kb","query"]}},{name:"kb_read",description:"Read one passage by its id (from kb_search), or one page of a document by document id and page number. A page call says which page is next.",inputSchema:{type:"object",properties:{kb:{type:"string",description:"The base id."},id:{type:"string",description:'A passage id like "d3f2a1b4c5d6#12".'},doc:{type:"string",description:"A document id (with page)."},page:{type:"integer",minimum:1,description:"The page (with doc)."}},required:["kb"]}},{name:"kb_outline",description:"The table of contents of a document in a base (its sections, with the page each starts on and the first passage id), or of every document when none is named.",inputSchema:{type:"object",properties:{kb:{type:"string"},doc:{type:"string",description:"A document id; omit for all."}},required:["kb"]}},{name:"kb_graph",description:'What connects to a name, a section or a topic in a base — its neighbours in the graph, or the path between two nodes ("what connects Atlas to the refund clause").',inputSchema:{type:"object",properties:{kb:{type:"string"},node:{type:"string",description:"An entity, section or topic by name."},to:{type:"string",description:"A second node: the path from node to it."},hops:{type:"integer",minimum:1,maximum:3}},required:["kb","node"]}},{name:"kb_status",description:"What one base holds: its documents (ids, titles, pages, passages), notes, entities, connections, and whether it has vectors.",inputSchema:{type:"object",properties:{kb:{type:"string"}},required:["kb"]}},{name:"kb_report",description:"The base's graph report as Markdown: every document with its outline, the most-mentioned entities, the communities of names that keep appearing together, the notes filed so far. Read it once before searching a base you have not seen.",inputSchema:{type:"object",properties:{kb:{type:"string"}},required:["kb"]}},{name:"kb_note",description:"File a note into a base — a fact you established, a summary, a correction — citing the passage ids it rests on. It is PROPOSED until the user accepts it in ChatPanel; proposed notes are searched and shown as proposed. Use it when the user asks to remember or record something about these documents, or when you resolved something that took work to find.",inputSchema:{type:"object",properties:{kb:{type:"string"},text:{type:"string",description:"One to three sentences."},cites:{type:"array",items:{type:"string"},description:"Passage ids the note stands on."}},required:["kb","text"]}}],q={[I]:" The gateway decides in-process unless it was turned off: ChatPanel › Settings › Runtime › Decide (or the OpenDecision container, or a server that provides `decide` under Models).",[L]:" The gateway reranks in-process unless it was turned off: ChatPanel › Settings › Runtime › Rerank (or the Reranker container, or a server that provides `rerank` under Models)."};function N(){const n=f(),e=c=>[{id:"gateway",name:"the gateway",url:`${n}${c}`,where:"this device"}],a=A({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(c,o)=>fetch(c,o)}),i=B({search:async c=>{const o=await d("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:c,limit:8,read:W.aliasRead})});return{query:c,engines:o.engines||[],results:(o.results||[]).map((t,r)=>({rank:r+1,title:t.title||t.url,url:t.url,engine:t.engine||"",text:t.read?.markdown||t.read?.text||t.snippet||""}))}}});return[a,i]}const Z=N().flatMap(n=>n.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function ee(n,e){const a=N().find(o=>o.specs.some(t=>t.name===n));if(!a)return null;const i=await a.execute(n,e);let c=typeof i=="string"?i:String(i?.text??i);return q[n]&&/^No (decision model|reranker) answered/.test(c)&&(c+=q[n]),c}function w(n,e){if(!n)return`Index: ${e} records (warm copy synced from ChatPanel).`;const a=new Date(n),i=`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}-${String(a.getDate()).padStart(2,"0")} ${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${i} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function R(){try{const n=k();return n?{Authorization:`Bearer ${n}`}:{}}catch{return{}}}async function d(n,e){let a;try{a=await fetch(f()+n,e)}catch(c){throw new Error(`the ChatPanel gateway is not running at ${f()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${c.message}]`)}const i=await a.json().catch(()=>({}));if(!a.ok)throw new Error(i?.error?.message||`the gateway returned HTTP ${a.status} for ${n}`);return i}function g(n){if(n==null||n==="")return null;if(typeof n=="number")return n;const e=String(n).trim().toLowerCase(),a=864e5;if(e==="today")return Date.now()-a;if(e==="yesterday")return Date.now()-2*a;const i=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(i){const o=Number(i[1]),t=i[2][0],r=t==="d"?a:t==="w"?7*a:t==="m"?30*a:365*a;return Date.now()-o*r}const c=Date.parse(e);return Number.isNaN(c)?null:c}const v=(n,e)=>`${e+1}. [${n.id}] ${n.title||"(untitled)"} · ${n.type}${n.date?" · "+new Date(n.date).toISOString().slice(0,10):""}${n.snippet?`
|
|
4
|
+
${n.snippet}`:""}`;async function te(n,e={}){const a=await ee(n,e);if(a!=null)return a;const i=await z(n,e,{gatewayJson:d});if(i!=null)return i;const c=await F(n,e,{baseUrl:f,gatewayJson:d,token:()=>{try{return k()}catch{return""}},client:()=>m,askConfig:S});if(c!=null)return c;if(n==="research"){const o={question:String(e.question||"")};e.previous&&typeof e.previous=="object"&&(o.previous=e.previous);const t=await d("/v1/research",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),r=w(t.newest,t.size),s=t.attachment?.text||`Searched ${t.how||"the store"} — nothing found in the user's data.`;return`${r}
|
|
5
5
|
|
|
6
6
|
${s}
|
|
7
7
|
|
|
8
|
-
previous (pass back for a follow-up): ${JSON.stringify(
|
|
8
|
+
previous (pass back for a follow-up): ${JSON.stringify(t.next||null)}`}if(n==="smart_search"){const o={question:String(e.question||""),queries:Array.isArray(e.queries)?e.queries.map(String):[],limit:Number(e.limit)||10};e.type&&(o.type=String(e.type));const t=g(e.since);t!=null&&(o.since=t);const r=g(e.before);r!=null&&(o.before=r);const s=await d("/v1/history/smart-search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=s.results||[],l=w(s.newest,s.size),u=(s.queries||[]).map(p=>`"${p}"`).join(", ");return h.length?[l,"",`${h.length} result(s) for "${e.question}" — searched ${s.queries.length} way(s): ${u}`,...h.map((p,j)=>`${v(p,j)}${p.foundBy?.length>1?`
|
|
9
9
|
(matched ${p.foundBy.length} of the queries)`:""}`)].join(`
|
|
10
10
|
`)+`
|
|
11
11
|
|
|
12
12
|
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.question}".
|
|
13
13
|
Searched ${s.queries?.length||0} way(s): ${u}.
|
|
14
|
-
${
|
|
15
|
-
If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(
|
|
14
|
+
${l}
|
|
15
|
+
If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(n==="search_history"){const o={query:String(e.query||""),limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0)};e.type&&(o.type=String(e.type));const t=g(e.since);t!=null&&(o.since=t);const r=g(e.before);r!=null&&(o.before=r);const s=await d("/v1/history/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=s.results||[],l=w(s.newest,s.size),u=[e.type&&`type=${e.type}`,e.since&&`since=${e.since}`,e.before&&`before=${e.before}`].filter(Boolean).join(", "),p=u?` (${u})`:"";return h.length?[l,"",`${h.length} result(s) for "${e.query}"${p}:`,...h.map(v)].join(`
|
|
16
16
|
`)+`
|
|
17
17
|
|
|
18
18
|
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.query}"${p}.
|
|
19
|
-
${
|
|
20
|
-
If you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`}if(
|
|
19
|
+
${l}
|
|
20
|
+
If you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`}if(n==="get_record"){const o=new URLSearchParams({id:String(e.id||"")});e.maxChars!=null&&o.set("maxChars",String(Math.max(1,Number(e.maxChars)||0))),e.offset!=null&&o.set("offset",String(Math.max(0,Number(e.offset)||0)));const r=(await d(`/v1/history/get?${o}`)).record,s=`[${r.id}] ${r.title||"(untitled)"} · ${r.type}${r.date?" · "+new Date(r.date).toISOString().slice(0,10):""}`,h=r.truncated?`
|
|
21
21
|
|
|
22
|
-
[showing ${
|
|
22
|
+
[showing ${r.text.length} of ${r.totalChars} chars (from offset ${r.offset}). For the next part call get_record again with offset=${r.offset+r.text.length}.]`:"";return`${s}
|
|
23
23
|
|
|
24
|
-
${
|
|
24
|
+
${r.text||"(empty)"}${h}`}if(n==="find_related"){const t=(await d(`/v1/history/related?id=${encodeURIComponent(String(e.id||""))}&limit=${Number(e.limit)||5}`)).results||[];return t.length?[`Records related to ${e.id}:`,...t.map(v)].join(`
|
|
25
25
|
`)+`
|
|
26
26
|
|
|
27
|
-
get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(
|
|
28
|
-
`)}if(
|
|
27
|
+
get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(n==="list_history"){const o=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0)}),t=await d(`/v1/history/list?${o}`),r=t.items||[];if(!r.length)return"History is empty (or the gateway has not been seeded yet — open ChatPanel with warm sync enabled).";const s=r[0]?.date||null;return[w(s,t.total),"",`${r.length} of ${t.total} records:`,...r.map(h=>`[${h.id}] ${h.title||"(untitled)"} · ${h.type}${h.date?" · "+new Date(h.date).toISOString().slice(0,10):""} · ${h.chars} chars`)].join(`
|
|
28
|
+
`)}if(n==="list_briefs"){const o=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0),type:"brief"}),t=await d(`/v1/history/list?${o}`),r=t.items||[];return r.length?[`${r.length} of ${t.total} briefs (each is a page about one subject, with every claim cited):`,...r.map(s=>`[${s.id}] ${s.title||"(untitled)"}${s.date?" · rebuilt "+new Date(s.date).toISOString().slice(0,10):""}`)].join(`
|
|
29
29
|
`)+`
|
|
30
30
|
|
|
31
|
-
get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(
|
|
32
|
-
`)}if(
|
|
31
|
+
get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(n==="get_brief"){const o=String(e.id||""),r=(await d(`/v1/history/get?${new URLSearchParams({id:o})}`)).record,s=E(r?.text);if(!s)return`${o} is not a brief (type ${r?.type||"unknown"}). Use get_record for it, or list_briefs for the brief ids.`;const h=[`BRIEF ${o} — ${s.name} (${s.kind})${s.aliases.length?` · also known as ${s.aliases.join(", ")}`:""}`,""];h.push(`${s.claims.length} claim(s), each with the records it cites:`);for(const l of s.claims)h.push(`• ${l.text}`),l.refs.length&&h.push(` cites: ${l.refs.map(u=>`${u.kind}:${u.id}`).join(", ")}`);return s.records.length&&h.push("",`Built from ${s.records.length} record(s) (most recent first): ${s.records.slice(0,12).map(l=>l.title).join(" · ")}${s.records.length>12?" …":""}`),h.push("","get_record <kind:id> opens a cited record; find_related <id> follows its connections."),h.join(`
|
|
32
|
+
`)}if(n==="recall"){const o=await d("/v1/memory/recall",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:String(e.text||"")})});return o.memories?.length?o.block:o.size?"Nothing in ChatPanel memory applies here.":"ChatPanel memory is empty — nothing is known about this user yet. Use `remember` when they state something durable about themselves or how they want to work."}if(n==="remember"){const o=String(e.text||"").trim();if(!o)return"remember needs `text` — one short sentence about the user.";const t=await d("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...R()},body:JSON.stringify({text:o,kind:e.kind?String(e.kind):"fact",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:"mcp",surface:"mcp",agent:m}})});return t.action==="duplicate"?`Already known: "${t.record.text}" — nothing changed.`:t.action==="update"?`Updated memory to "${t.record.text}" (was "${t.replaced?.text}"). It applies to every future session.`:`Remembered: "${t.record.text}". It applies to every future ChatPanel session, on every model.`}if(n==="forget"){const o=String(e.query||"").trim();if(!o)return"forget needs `query` — the memory to remove.";const t=await d("/v1/memory/forget",{method:"POST",headers:{"content-type":"application/json",...R()},body:JSON.stringify({query:o})});return t.removed?.length?`Forgot: ${t.removed.map(r=>`"${r.text}"`).join(", ")}.`:`No memory matches "${o}". Call recall to see what is stored.`}if(n==="list_skills"){let o;try{o=await $("/skills")}catch(r){return`Installed skills are unavailable because the ChatPanel bridge is not running at ${C()}. Install/start it with:
|
|
33
33
|
curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash
|
|
34
|
-
Then retry. History tools work without the bridge. [${
|
|
34
|
+
Then retry. History tools work without the bridge. [${r.message}]`}const t=o.skills||[];return t.length?[`${t.length} skill(s) installed:`,...t.map(r=>`- ${r.command||r.id}: ${r.description||r.name}${r.origin?.source?` (from ${r.origin.source})`:""}`)].join(`
|
|
35
35
|
`)+`
|
|
36
36
|
|
|
37
|
-
Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(
|
|
37
|
+
Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(n==="open_skill"){let o;try{o=await $(`/skills/${encodeURIComponent(String(e.name||"").trim())}`)}catch(t){return`Could not open "${e.name}": ${t.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return o.skill?.prompt||"(this skill has no extra instructions — just apply it.)"}if(n==="read_skill_file"){const o=encodeURIComponent(String(e.name||"").trim()),t=String(e.path||"").trim().split("/").map(encodeURIComponent).join("/");let r;try{r=await $(`/skills/${o}/file/${t}`)}catch(s){return`Could not read ${e.path}: ${s.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return r.text||"(empty)"}if(n.startsWith("kb_"))return ne(n,e);throw new Error(`unknown tool: ${n}`)}async function ne(n,e={}){const a=String(e.kb||"").trim(),i=a?`/v1/kb/${encodeURIComponent(a)}`:"",c={"x-chatpanel-agent":String(m||"unknown").toLowerCase()},o=(t,r)=>d(t,{method:"POST",headers:{"content-type":"application/json",...c},body:JSON.stringify(r)});if(n==="kb_list"){const r=(await d("/v1/kb",{headers:c})).kbs||[];return r.length?[`${r.length} knowledge base${r.length===1?"":"s"}:`,...r.map(s=>`- ${s.id}: ${s.name} — ${s.docs} document${s.docs===1?"":"s"}${s.vectors?`, ${s.vectors} vectors`:""}`),"","kb_report <id> for the map, kb_search <id> for a question."].join(`
|
|
38
|
+
`):"No knowledge bases on this machine yet. The user builds one in ChatPanel (attach a folder or a document) or with `chatpanel kb build <path>`."}if(!a)return"Which knowledge base? kb_list gives the ids.";if(n==="kb_search"){const t=await o(`${i}/search`,{query:String(e.query||""),limit:Math.max(1,Math.min(30,Number(e.limit)||8)),...e.doc?{docs:[String(e.doc)]}:{},...Array.isArray(e.queries)?{queries:e.queries.map(String)}:{}});return M(t)}if(n==="kb_read"){if(e.id)try{const t=await d(`${i}/passages/${encodeURIComponent(String(e.id))}`,{headers:c});return`${t.cite||t.id}${t.section?` §${t.section}`:""}
|
|
39
|
+
${t.text}`}catch(t){return`No passage ${e.id}: ${t.message}. Search first; passage ids look like "d3f2a1b4c5d6#12".`}if(e.doc)try{const t=await d(`${i}/documents/${encodeURIComponent(String(e.doc))}?page=${Number(e.page)||1}`,{headers:c});return`${t.title} — page ${t.page} of ${t.pages}${t.page<t.pages?` (next: ${t.page+1})`:" (last page)"}
|
|
40
|
+
${t.text||"(no text on this page — an image or a scan)"}`}catch(t){return`No document ${e.doc}: ${t.message}. kb_status lists the ids.`}return"kb_read needs a passage id, or a document id with a page."}if(n==="kb_outline"){const[t,r]=await Promise.all([d(`${i}/outline${e.doc?`?doc=${encodeURIComponent(String(e.doc))}`:""}`,{headers:c}),d(i,{headers:c})]);return U(t.outline||[],r.kb)}if(n==="kb_graph")return D(await o(`${i}/graph`,{node:String(e.node||""),hops:Math.max(1,Math.min(3,Number(e.hops)||1)),...e.to?{to:String(e.to)}:{}}));if(n==="kb_status")return H((await d(i,{headers:c})).kb);if(n==="kb_report"){const t=await fetch(`${f()}${i}/report`,{headers:c});if(!t.ok)throw new Error(`the gateway returned HTTP ${t.status} for the report`);return t.text()}if(n==="kb_note"){const r=(await o(`${i}/notes`,{text:String(e.text||""),cites:Array.isArray(e.cites)?e.cites.map(String):[]})).note||{};return`Noted (${r.status||"proposed"} — the user can accept it in ChatPanel): ${r.text}${r.cites?.length?` — cites ${r.cites.join(", ")}`:""}`}throw new Error(`unknown tool: ${n}`)}async function re(n){const{id:e,method:a,params:i}=n||{},c=t=>({jsonrpc:"2.0",id:e,result:t}),o=(t,r)=>({jsonrpc:"2.0",id:e,error:{code:t,message:r}});try{switch(a){case"initialize":{m=i?.clientInfo?.name||m;const t=await V(),r=T(S()).some(s=>s.name==="delegate_task")?`
|
|
38
41
|
|
|
39
42
|
ChatPanel can also DELEGATE a whole piece of work to one of the user's coding agents,
|
|
40
43
|
running here with its own tools in a directory they have allowed:
|
|
41
44
|
• delegate_task — a refactor across many files, a test suite to run and fix, a build to
|
|
42
45
|
diagnose. Unlike ask_model it reads and EDITS files and runs commands, so use it for work
|
|
43
46
|
that belongs on this machine, tell the user what you delegated and where, and expect
|
|
44
|
-
minutes — it returns a job id for ask_status.`:"";return c({protocolVersion:
|
|
45
|
-
`);for await(const
|
|
46
|
-
`))>=0;){const c=
|
|
47
|
+
minutes — it returns a job id for ask_status.`:"";return c({protocolVersion:J,capabilities:{tools:{}},serverInfo:G,instructions:K+r+t})}case"tools/list":return c({tools:[...Q,...Z,...Y,...T(S())]});case"tools/call":{const t=Date.now();try{const r=await te(i?.name,i?.arguments||{});return O({client:m,tool:i?.name,ok:!0,ms:Date.now()-t,args:i?.arguments||{}}),c({content:[{type:"text",text:r}]})}catch(r){throw O({client:m,tool:i?.name,ok:!1,ms:Date.now()-t,args:i?.arguments||{},error:r.message}),r}}case"ping":return c({});default:return typeof a=="string"&&a.startsWith("notifications/")||e===void 0?null:o(-32601,`method not found: ${a}`)}}catch(t){return a==="tools/call"?c({content:[{type:"text",text:`Error: ${t.message}`}],isError:!0}):o(-32603,t.message)}}async function we(){let n="";process.stdin.setEncoding("utf8");const e=a=>process.stdout.write(JSON.stringify(a)+`
|
|
48
|
+
`);for await(const a of process.stdin){n+=a;let i;for(;(i=n.indexOf(`
|
|
49
|
+
`))>=0;){const c=n.slice(0,i).trim();if(n=n.slice(i+1),!c)continue;let o;try{o=JSON.parse(c)}catch{continue}const t=await re(o);t&&e(t)}}}export{re as handleRpc,we as runMcpServer};
|
package/src/memory.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
`)}function re(e,o,{now:s=0}={}){const r=new Set(o||[]);return(e||[]).map(n=>r.has(n.id)?{...n,usedAt:Number(s)||n.usedAt,useCount:n.useCount+1}:n)}function oe(e,{now:o=0,max:s=B}={}){const r=(e||[]).filter(Boolean),n=o?r.filter(i=>i.expiresAt&&i.expiresAt<=o):[];let a=n.length?r.filter(i=>!n.includes(i)):r;const t=[...n];if(a.length>s){const i=l=>(l.pinned?3:0)+(b[l.kind]?.ambient?1:0),f=[...a].sort((l,d)=>i(d)-i(l)||d.useCount-l.useCount||(d.usedAt||d.updatedAt)-(l.usedAt||l.updatedAt));t.push(...f.slice(s)),a=f.slice(0,s)}return{kept:a,dropped:t}}const se=Object.freeze({name:"memory",description:'Save, update or remove a durable fact about the USER in ChatPanel — carried into every future conversation, on every model and agent. Use it the moment they state a standing preference ("always be terse"), an identity fact ("call me Alex"), or a constraint about their work that will still be true next week. Do NOT use it for one-off task details, anything already obvious from the conversation, or content that belongs in a note. Keep each memory one short self-contained sentence. Use `forget` when the user says something is no longer true, and `list` to see what is already stored before adding.',parameters:{type:"object",properties:{action:{type:"string",enum:["remember","forget","list"],description:"What to do."},text:{type:"string",description:`The fact, as one short sentence written in the third person ("Prefers terse answers"). Max ${y} characters. Required for remember; for forget, the memory to drop (its text or id).`},kind:{type:"string",enum:M,description:M.map(e=>`${e}: ${b[e].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["action"]}});function ie(){return["You can give the user a memory that survives this conversation, this model and this device — call the `memory` tool.","Save when they say something durable about themselves, how they want to be helped, or their ongoing work. Do not save task details, transient state, or anything they would not want repeated back to them in a month.","Saving is a change to the user's own data: say in one short clause what you saved."].join(" ")}const H=Object.freeze({});function ae(e){let o=e;for(let s=Number(o?.v)||1;s<1;s+=1){const r=H[s];if(!r)throw new v(`no upcaster from memory v${s}`);o=r(o)}return o}const u=e=>String(e??"").replace(/\s+/g," ").trim(),W=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):1,w=e=>u(e).replace(/[.,;:!]+$/,""),E=e=>e.length>y?`${e.slice(0,y-1).trimEnd()}…`:e,O=e=>{const o=w(e);return o&&o[0].toUpperCase()+o.slice(1)};function q(e){return String(e||"").split(/\n+/).flatMap(o=>u(o).replace(/^[-*+•]\s*|^\d+[.)]\s*/,"").split(/(?<=[.!?])\s+(?=[A-Z"'])/)).map(u).filter(Boolean)}export{X as AMBIENT_KINDS,$ as DEFAULT_BLOCK_CHARS,B as DEFAULT_MAX_MEMORIES,y as MAX_MEMORY_CHARS,b as MEMORY_KINDS,M as MEMORY_KIND_NAMES,se as MEMORY_TOOL_SPEC,H as MEMORY_UPCASTERS,G as MEMORY_VERSION,S as MIN_MEMORY_CHARS,v as MemoryError,Y as SAME_FACT,J as candidatesFrom,I as containment,Z as isValidMemory,re as markUsed,ee as matchForForget,ne as memoryBlock,g as memoryKey,ie as memoryToolSystem,C as normalizeMemory,oe as pruneMemories,te as recall,Q as reconcile,_ as similarity,T as slotOf,ae as upcastMemory};
|
|
1
|
+
export*from"@chatpanel/events/memory.js";
|
package/src/model-ledger.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export*from"@chatpanel/events/model-ledger.js";
|
package/src/ner-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import q from"node:os";import{join as O}from"node:path";import{existsSync as Q,mkdirSync as ct,readdirSync as K,readFileSync as ut}from"node:fs";import{DEFAULT_MODEL as V,isMirroredModel as ft}from"./models.js";import{isLoopbackHost as pt,isPrivateHost as dt,isMetadataHost as ht}from"@chatpanel/pii";import{recaseForDetection as mt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as gt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as yt}from"./model-integrity.js";import{runtimeName as wt}from"./model-runtime.js";import{nativeOrtFailure as _t}from"./ort.js";import{makeWarmTimer as X}from"./warm-timer.js";import{makeModelFileCache as xt}from"./model-file-cache.js";const C="https://dl.chatpanel.net/models/";function Mt(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return C;const n=c=>(console.warn(`[models] ignoring ${e} (${r}): ${c} — using ${C}`),C);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(ht(o.hostname))return n("points at cloud metadata");const s=pt(o.hostname)||dt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${C}`),r.replace(/\/*$/,"/"))}const bt=Mt();let h="off",y=null,w=null,b=null,T=null,E=null,L=null,m=null,x=null,P=0,N=null;const g=new Map;function H(){return process.env.CHATPANEL_MODELS_DIR||O(q.homedir(),".chatpanel","models")}function R(t=y||V){const e=O(H(),...t.split("/"));return Q(O(e,"onnx","model_quantized.onnx"))||Q(O(e,"onnx","model.onnx"))}function Zt(){const t=H(),e=[];try{for(const r of K(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of K(O(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;R(o)&&Lt(O(t,r.name,n.name))&&e.push(o)}}catch{}return e}function Lt(t){try{return(JSON.parse(ut(O(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function It(){return h}function A(){return h==="ready"&&!!w}function te(){return{configured:h!=="off",ok:A(),state:h,model:y,error:b,runtime:wt(),dtype:w?"q8":null,stats:Pt(),companions:$t(),warmMs:x?.warmMs??null}}async function Tt(t,{signal:e,strict:r=!1}={}){if(!A())return[];if(e?.aborted)return[];const n=String(t||""),o=await Z(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(I(f,r))continue;let i=String(f.word??"");const u=f.entity_group??f.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===u){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:u})}const c=new Set,l=[];for(const f of s){const i=Rt(n,Ht(n,f.value.trim()));if(i.length<=1)continue;const u=`${f.type}:${i.toLowerCase()}`;c.has(u)||(c.add(u),l.push({value:i,type:f.type}))}return l}async function Z(t,e){P++;try{return await St(t,e)}finally{P--,v()||x?.arm()}}async function St(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(D){const s=mt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:c}of nt())for(const l of o){let f=0;for(const i of Et(l.text,c.tokenizer)){if(e?.aborted)return null;const u=l.text.indexOf(i,f),d=await c(i,{aggregation_strategy:"simple"});for(const a of d||[])n.push({...a,_win:u<0?f:u,_winText:i,_model:s,_pass:l.key,_passText:l.text});u>=0&&(f=Math.max(f,u+1))}}return Ct(performance.now()-r,t.length,n.length),n}let D=!0;function ee(t){D=t!==!1}const I=(t,e)=>!e&&t._pass==="recased"&&!gt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function ne(t,{signal:e,strict:r=!1}={}){if(!A())return[];const n=String(t||""),o=await Z(n,e);if(!o)return[];const s=[],c=new Set;let l=-1,f=-1,i=null,u=null;for(const a of o){if(I(a,r))continue;const p=String(a.word??"").replace(/##/g,"").trim();if(!p)continue;(a._win!==f||a._model!==i||a._pass!==u)&&(f=a._win,i=a._model,u=a._pass,l=a._win);const k=a._passText||n;let M=k.indexOf(p,l);if(M<0&&(M=k.indexOf(p,a._win)),M<0)continue;let S=M+p.length;l=S;const z=G=>!!G&&/[\p{L}\p{N}'’-]/u.test(G);for(;M>0&&z(n[M-1]);)M--;for(;S<n.length&&z(n[S]);)S++;const Y=String(a.entity_group??a.entity??"ENTITY"),B=`${M}:${S}:${Y}`;if(c.has(B))continue;c.add(B);const J=Number(a.score);s.push({value:n.slice(M,S),type:Y,start:M,end:S,score:Number.isFinite(J)?Math.max(0,Math.min(1,J)):1,model:a._model})}s.sort((a,p)=>a.start-p.start||a.end-p.end);const d=[];for(const a of s){const p=d[d.length-1];if(p&&p.type===a.type&&p.end===a.start){p.end=a.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,a.score);continue}d.push({...a})}return g.size||D?kt(d):d}const tt=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function Ot(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function F(t){const e=tt.indexOf(Ot(t.type));return e<0?tt.length:e}let $=[];function At(t){$=Array.isArray(t)?t.slice():[],m&&(m={...m,union:$.slice()})}function W(t){if(t.model===y)return-1;const e=$.indexOf(t.model);return e<0?$.length:e}function kt(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=l=>l.end-l.start;(F(n)<F(o)||F(n)===F(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function oe(){const t=w?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function re(){const t=Number(w?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function $t(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function et(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===y)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:o}=await st(t,{log:e,allowDownload:r});return g.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return g.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function se(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function nt(){const t=w?[{model:y,pipe:w}]:[];for(const[e,r]of g)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const vt=160,ot=256;function Et(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(ot,Number.isFinite(r)&&r>0?r:ot)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const c=[];let l=0,f=Math.max(64,Math.floor(o*3));for(;l<t.length;){let i=Math.min(t.length,l+f);if(i<t.length){const p=t.lastIndexOf(" ",i);p>l+f/2&&(i=p)}let u=t.slice(l,i);for(;s(u)>o&&u.length>32;){f=Math.max(32,Math.floor(u.length/2)),i=l+f;const p=t.lastIndexOf(" ",i);p>l+f/2&&(i=p),u=t.slice(l,i)}if(c.push(u),i>=t.length)break;const d=Math.max(l+1,i-vt),a=t.indexOf(" ",d);l=a>0&&a<i?a+1:i}return c}const Nt=200,_=[];function Ct(t,e,r){_.push({ms:t,chars:e,spans:r}),_.length>Nt&&_.shift()}function Pt(){if(!_.length)return{calls:0};const t=_.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=_.reduce((o,s)=>o+s.chars,0),n=_.reduce((o,s)=>o+s.ms,0);return{calls:_.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(_[_.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Ht(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function Rt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=c=>!!c&&/[\p{L}\p{N}'’-]/u.test(c);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function ie(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await Tt(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function ae(){return L}async function rt(){if(E)return E;const t=H();try{ct(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(a){throw e?a:new Error(_t(a))}const{env:n,pipeline:o,Tensor:s,AutoModel:c,AutoProcessor:l,AutoTokenizer:f,AutoModelForSequenceClassification:i,LogLevel:u}=r;if(n.cacheDir=t,e&&u)try{n.logLevel=u.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=xt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=bt}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return E={env:n,pipeline:(a,p,k={})=>o(a,p,k.progress_callback&&n.allowRemoteModels===!1?{...k,progress_callback:void 0}:k),Tensor:s,AutoModel:c,AutoProcessor:l,AutoTokenizer:f,AutoModelForSequenceClassification:i},E}function Dt({cores:t=q.availableParallelism?.()??q.cpus().length,wasm:e=!!globalThis.__CHATPANEL_WASM_PATHS__,env:r=process.env}={}){const n=Number(r.CHATPANEL_NER_THREADS);return{intraOpNumThreads:e?1:Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(8,t-1)),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}async function st(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await rt(),s=R(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const c=o.env.remoteHost,l=!ft(t);if(!s&&l)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${l?", from Hugging Face":""})…`);try{const i={dtype:"q8",progress_callback:d=>{d&&(d.status==="progress"||d.status==="download"||d.status==="initiate"?n(d):d.status==="done"&&d.file&&e(`[ner] fetched ${d.file}`))},session_options:Dt()};let u;try{u=await o.pipeline("token-classification",t,i)}catch(d){if(s||l||!r)throw d;e(`[ner] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,u=await o.pipeline("token-classification",t,i)}if(!s)try{yt(t,{modelsDir:H(),log:e})}catch(d){try{await u.dispose?.()}catch{}throw d}return{pipe:u,haveLocal:s}}finally{try{o.env.remoteHost=c}catch{}}}async function it(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=w,o=y;try{await rt()}catch(c){return h="error",b=`engine load failed: ${c.message}`,e(`[ner] transformers.js not available (${c.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return h="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;h=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:c}=await st(t,{log:e,allowDownload:r,onProgress:l=>{L={model:t,file:l.file||L?.file||null,pct:typeof l.progress=="number"?Math.round(l.progress):L?.pct??0}}});if(w=c,y=t,h="ready",b=null,L=null,m&&(m={...m,model:t}),n&&n!==c)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),v()||x?.arm(),!0}catch(c){return b=c.message,L=null,n?(w=n,y=o,h="ready"):h="error",e(`[ner] model load failed (${c.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function Ft(t={}){if(T)return T;const e=typeof t.onLog=="function"?t.onLog:()=>{};m=t,y=t.model||V,h="loading";const r=t.allowDownload!==!1;return x=X({warmMs:t.warmMs,busy:v,log:e,unload:()=>at({log:e})}),T=it(y,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];At(o);for(const s of o)await et(s,{log:e,allowDownload:r});return A()&&!v()&&x?.arm(),n}),T}function v(){if(P>0||h==="loading"||h==="downloading")return!0;for(const t of g.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function at({log:t=()=>{}}={}){if(v())return!1;x?.disarm();const e=nt().map(r=>r.pipe);w=null,T=null,L=null,b=null,g.clear(),h=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((x?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function Wt(){try{h==="idle"&&(N||m)?await(N?N():Ft(m)):T&&await T,A()&&await lt()}catch{}return A()}let U=null;function lt(){const t=$.filter(e=>e&&e!==y&&!g.has(e));return t.length?(U||=(async()=>{const e=typeof m?.onLog=="function"?m.onLog:()=>{};for(const r of t)g.has(r)||(j?await j(r):await et(r,{log:e,allowDownload:m?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function le(t){j=t}async function ce(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===y&&A())return!0;if(t===y&&h==="idle")return Wt();const o=g.get(t);if(o?.pipe){const c=w;if(w=o.pipe,y=t,h="ready",b=null,g.delete(t),c)try{await c.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),m&&(m={...m,model:t}),!0}const s=await it(t,{log:r,allowDownload:n});return s&&(m&&(m={...m,model:t}),await lt()),s}function ue(){h="off",y=null,w=null,b=null,T=null,E=null,L=null,_.length=0,g.clear(),D=!0,$=[],x?.disarm(),x=null,m=null,P=0,N=null,j=null,U=null}function fe(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function pe(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){w=t,y=e,h="ready",b=null,_.length=0,n&&(N=n),r!==null&&(x=X({warmMs:r,busy:v,unload:()=>at()}),t&&x.arm())}export{ue as _reset,fe as _setCompanionForTest,le as _setCompanionLoaderForTest,pe as _setForTest,et as addCompanion,$t as companions,Tt as detect,ne as detectSpans,Wt as ensure,rt as ensureLib,ie as fetchAdapter,te as health,Ft as init,A as isReady,oe as labels,re as maxTokens,R as modelOnDisk,H as modelRoot,Zt as modelsOnDisk,ae as progress,se as removeCompanion,Mt as resolveModelHost,Dt as sessionOptionsFor,ee as setCaseRecovery,ce as setModel,At as setUnionOrder,It as state,Pt as stats,kt as unionSpans,at as unload,Et as windowsFor};
|
|
1
|
+
import q from"node:os";import{join as S}from"node:path";import{existsSync as K,mkdirSync as ut,readdirSync as V,readFileSync as ft}from"node:fs";import{DEFAULT_MODEL as X,isMirroredModel as pt}from"./models.js";import{isLoopbackHost as dt,isPrivateHost as mt,isMetadataHost as ht}from"@chatpanel/pii";import{recaseForDetection as gt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as yt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as wt}from"./model-integrity.js";import{runtimeName as _t}from"./model-runtime.js";import{nativeOrtFailure as Mt}from"./ort.js";import{makeWarmTimer as Z}from"./warm-timer.js";import{makeModelFileCache as xt}from"./model-file-cache.js";import{onLane as bt}from"./inference-lane.js";const H="https://dl.chatpanel.net/models/";function Lt(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return H;const n=a=>(console.warn(`[models] ignoring ${e} (${r}): ${a} — using ${H}`),H);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(ht(o.hostname))return n("points at cloud metadata");const s=dt(o.hostname)||mt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${H}`),r.replace(/\/*$/,"/"))}const Tt=Lt();let m="off",y=null,w=null,b=null,T=null,C=null,L=null,h=null,M=null,N=0,E=null;const g=new Map;let I=Promise.resolve();function ee({host:t=null,allowRemote:e=!1}={},r){const n=I.then(async()=>{const o=await z(),s=o.env.remoteHost,a=o.env.allowRemoteModels;try{o.env.allowRemoteModels=e,t&&(o.env.remoteHost=t)}catch{}try{return await r(o)}finally{try{o.env.remoteHost=s,o.env.allowRemoteModels=a}catch{}}});return I=n.catch(()=>{}),n}function P(){return process.env.CHATPANEL_MODELS_DIR||S(q.homedir(),".chatpanel","models")}function R(t=y||X){const e=S(P(),...t.split("/"));return K(S(e,"onnx","model_quantized.onnx"))||K(S(e,"onnx","model.onnx"))}function ne(){const t=P(),e=[];try{for(const r of V(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of V(S(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;R(o)&&At(S(t,r.name,n.name))&&e.push(o)}}catch{}return e}function At(t){try{return(JSON.parse(ft(S(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function oe(){return m}function O(){return m==="ready"&&!!w}function re(){return{configured:m!=="off",ok:O(),state:m,model:y,error:b,runtime:_t(),dtype:w?"q8":null,stats:Rt(),companions:Ct(),warmMs:M?.warmMs??null}}async function St(t,{signal:e,strict:r=!1}={}){if(!O())return[];if(e?.aborted)return[];const n=String(t||""),o=await tt(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(et(f,r))continue;let i=String(f.word??"");const u=f.entity_group??f.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===u){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:u})}const a=new Set,c=[];for(const f of s){const i=Dt(n,Ft(n,f.value.trim()));if(i.length<=1)continue;const u=`${f.type}:${i.toLowerCase()}`;a.has(u)||(a.add(u),c.push({value:i,type:f.type}))}return c}async function tt(t,e){N++;try{return await Ot(t,e)}finally{N--,$()||M?.arm()}}async function Ot(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(F){const s=gt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:a}of rt())for(const c of o){let f=0;for(const i of Ht(c.text,a.tokenizer)){if(e?.aborted)return null;const u=c.text.indexOf(i,f),d=await bt(()=>a(i,{aggregation_strategy:"simple"}));for(const l of d||[])n.push({...l,_win:u<0?f:u,_winText:i,_model:s,_pass:c.key,_passText:c.text});u>=0&&(f=Math.max(f,u+1))}}return Pt(performance.now()-r,t.length,n.length),n}let F=!0;function se(t){F=t!==!1}const et=(t,e)=>!e&&t._pass==="recased"&&!yt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function ie(t,{signal:e,strict:r=!1}={}){if(!O())return[];const n=String(t||""),o=await tt(n,e);if(!o)return[];const s=[],a=new Set;let c=-1,f=-1,i=null,u=null;for(const l of o){if(et(l,r))continue;const p=String(l.word??"").replace(/##/g,"").trim();if(!p)continue;(l._win!==f||l._model!==i||l._pass!==u)&&(f=l._win,i=l._model,u=l._pass,c=l._win);const v=l._passText||n;let x=v.indexOf(p,c);if(x<0&&(x=v.indexOf(p,l._win)),x<0)continue;let A=x+p.length;c=A;const Y=Q=>!!Q&&/[\p{L}\p{N}'’-]/u.test(Q);for(;x>0&&Y(n[x-1]);)x--;for(;A<n.length&&Y(n[A]);)A++;const B=String(l.entity_group??l.entity??"ENTITY"),J=`${x}:${A}:${B}`;if(a.has(J))continue;a.add(J);const G=Number(l.score);s.push({value:n.slice(x,A),type:B,start:x,end:A,score:Number.isFinite(G)?Math.max(0,Math.min(1,G)):1,model:l._model})}s.sort((l,p)=>l.start-p.start||l.end-p.end);const d=[];for(const l of s){const p=d[d.length-1];if(p&&p.type===l.type&&p.end===l.start){p.end=l.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,l.score);continue}d.push({...l})}return g.size||F?$t(d):d}const nt=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function vt(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function D(t){const e=nt.indexOf(vt(t.type));return e<0?nt.length:e}let k=[];function kt(t){k=Array.isArray(t)?t.slice():[],h&&(h={...h,union:k.slice()})}function W(t){if(t.model===y)return-1;const e=k.indexOf(t.model);return e<0?k.length:e}function $t(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=c=>c.end-c.start;(D(n)<D(o)||D(n)===D(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function ae(){const t=w?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function le(){const t=Number(w?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function Ct(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function ot(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===y)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:o}=await it(t,{log:e,allowDownload:r});return g.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return g.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function ce(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function rt(){const t=w?[{model:y,pipe:w}]:[];for(const[e,r]of g)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const Et=160,st=256;function Ht(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(st,Number.isFinite(r)&&r>0?r:st)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const a=[];let c=0,f=Math.max(64,Math.floor(o*3));for(;c<t.length;){let i=Math.min(t.length,c+f);if(i<t.length){const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p)}let u=t.slice(c,i);for(;s(u)>o&&u.length>32;){f=Math.max(32,Math.floor(u.length/2)),i=c+f;const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p),u=t.slice(c,i)}if(a.push(u),i>=t.length)break;const d=Math.max(c+1,i-Et),l=t.indexOf(" ",d);c=l>0&&l<i?l+1:i}return a}const Nt=200,_=[];function Pt(t,e,r){_.push({ms:t,chars:e,spans:r}),_.length>Nt&&_.shift()}function Rt(){if(!_.length)return{calls:0};const t=_.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=_.reduce((o,s)=>o+s.chars,0),n=_.reduce((o,s)=>o+s.ms,0);return{calls:_.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(_[_.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Ft(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function Dt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=a=>!!a&&/[\p{L}\p{N}'’-]/u.test(a);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function ue(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await St(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function fe(){return L}async function z(){if(C)return C;const t=P();try{ut(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(l){throw e?l:new Error(Mt(l))}const{env:n,pipeline:o,Tensor:s,AutoModel:a,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i,LogLevel:u}=r;if(n.cacheDir=t,e&&u)try{n.logLevel=u.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=xt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=Tt}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return C={env:n,pipeline:(l,p,v={})=>o(l,p,v.progress_callback&&n.allowRemoteModels===!1?{...v,progress_callback:void 0}:v),Tensor:s,AutoModel:a,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i,AutoModelForAudioFrameClassification:r.AutoModelForAudioFrameClassification},C}function Wt({cores:t=q.availableParallelism?.()??q.cpus().length,wasm:e=!!globalThis.__CHATPANEL_WASM_PATHS__,env:r=process.env}={}){const n=Number(r.CHATPANEL_NER_THREADS);return{intraOpNumThreads:e?1:Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(t/4))),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}async function it(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await z(),s=R(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const a=o.env.remoteHost,c=!pt(t);if(!s&&c)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${c?", from Hugging Face":""})…`);try{const i={dtype:"q8",progress_callback:d=>{d&&(d.status==="progress"||d.status==="download"||d.status==="initiate"?n(d):d.status==="done"&&d.file&&e(`[ner] fetched ${d.file}`))},session_options:Wt()};let u;try{u=await o.pipeline("token-classification",t,i)}catch(d){if(s||c||!r)throw d;e(`[ner] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,u=await o.pipeline("token-classification",t,i)}if(!s)try{wt(t,{modelsDir:P(),log:e})}catch(d){try{await u.dispose?.()}catch{}throw d}return{pipe:u,haveLocal:s}}finally{try{o.env.remoteHost=a}catch{}}}async function at(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=w,o=y;try{await z()}catch(a){return m="error",b=`engine load failed: ${a.message}`,e(`[ner] transformers.js not available (${a.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return m="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;m=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:a}=await it(t,{log:e,allowDownload:r,onProgress:c=>{L={model:t,file:c.file||L?.file||null,pct:typeof c.progress=="number"?Math.round(c.progress):L?.pct??0}}});if(w=a,y=t,m="ready",b=null,L=null,h&&(h={...h,model:t}),n&&n!==a)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||M?.arm(),!0}catch(a){return b=a.message,L=null,n?(w=n,y=o,m="ready"):m="error",e(`[ner] model load failed (${a.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function Ut(t={}){if(T)return T;const e=typeof t.onLog=="function"?t.onLog:()=>{};h=t,y=t.model||X,m="loading";const r=t.allowDownload!==!1;return M=Z({warmMs:t.warmMs,busy:$,log:e,unload:()=>lt({log:e})}),T=at(y,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];kt(o);for(const s of o)await ot(s,{log:e,allowDownload:r});return O()&&!$()&&M?.arm(),n}),T}function $(){if(N>0||m==="loading"||m==="downloading")return!0;for(const t of g.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function lt({log:t=()=>{}}={}){if($())return!1;M?.disarm();const e=rt().map(r=>r.pipe);w=null,T=null,L=null,b=null,g.clear(),m=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((M?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function jt(){try{m==="idle"&&(E||h)?await(E?E():Ut(h)):T&&await T,O()&&await ct()}catch{}return O()}let U=null;function ct(){const t=k.filter(e=>e&&e!==y&&!g.has(e));return t.length?(U||=(async()=>{const e=typeof h?.onLog=="function"?h.onLog:()=>{};for(const r of t)g.has(r)||(j?await j(r):await ot(r,{log:e,allowDownload:h?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function pe(t){j=t}async function de(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===y&&O())return!0;if(t===y&&m==="idle")return jt();const o=g.get(t);if(o?.pipe){const a=w;if(w=o.pipe,y=t,m="ready",b=null,g.delete(t),a)try{await a.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),h&&(h={...h,model:t}),!0}const s=await at(t,{log:r,allowDownload:n});return s&&(h&&(h={...h,model:t}),await ct()),s}function me(){m="off",y=null,w=null,b=null,T=null,C=null,L=null,_.length=0,g.clear(),F=!0,k=[],M?.disarm(),M=null,h=null,N=0,E=null,j=null,U=null}function he(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function ge(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){w=t,y=e,m="ready",b=null,_.length=0,n&&(E=n),r!==null&&(M=Z({warmMs:r,busy:$,unload:()=>lt()}),t&&M.arm())}export{me as _reset,he as _setCompanionForTest,pe as _setCompanionLoaderForTest,ge as _setForTest,ot as addCompanion,Ct as companions,St as detect,ie as detectSpans,jt as ensure,z as ensureLib,ue as fetchAdapter,re as health,Ut as init,O as isReady,ae as labels,le as maxTokens,R as modelOnDisk,P as modelRoot,ne as modelsOnDisk,fe as progress,ce as removeCompanion,Lt as resolveModelHost,Wt as sessionOptionsFor,se as setCaseRecovery,de as setModel,kt as setUnionOrder,oe as state,Rt as stats,$t as unionSpans,lt as unload,Ht as windowsFor,ee as withModelSource};
|
package/src/observability.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export*from"@chatpanel/events/observability.js";
|
package/src/openai.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{restoreText as
|
|
1
|
+
import{restoreText as a}from"@chatpanel/pii";import{segment as i}from"./redact.js";import{restoreDeepAliases as l}from"./stream.js";function p(t){return/\/chat\/completions$/.test(t)||/\/completions$/.test(t)}function y(t,n){if(!n||!t||!Array.isArray(t.messages))return t;const e=t.messages.find(s=>s&&s.role==="system");return e&&typeof e.content=="string"?e.content+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${n}`:t.messages.unshift({role:"system",content:n}),t}function x(t,n,{skipPublic:e=!1}={}){const s=[],c=Array.isArray(t?.messages)?t.messages:[];for(const o of c)if(o&&!(o.role==="system"&&n.redactSystem===!1)){if(typeof o.content=="string")s.push(i(()=>o.content,r=>{o.content=r}));else if(Array.isArray(o.content)){for(const r of o.content)if(r&&r.type==="text"&&typeof r.text=="string"){if(e&&r.chatpanel_public===!0)continue;s.push(i(()=>r.text,f=>{r.text=f}))}}}return s}function A(t){for(const n of Array.isArray(t?.messages)?t.messages:[])if(!(!Array.isArray(n?.content)||!n.content.some(e=>e&&"chatpanel_public"in e)))if(n.content.every(e=>e?.type==="text"&&typeof e.text=="string"))n.content=n.content.map(e=>e.text).join("");else for(const e of n.content)e&&delete e.chatpanel_public;return t}function _(t){return{messages:Array.isArray(t?.messages)?t.messages:[],system:""}}function h(t){return Array.isArray(t?.tools)?t.tools:[]}function T(t){const n=Array.isArray(t?.messages)?t.messages:[];for(let e=n.length-1;e>=0;e--){const s=n[e];if(s?.role==="tool"&&s.tool_call_id)return{tool_call_id:s.tool_call_id,content:typeof s.content=="string"?s.content:JSON.stringify(s.content)}}return null}function S(t,n,e=null){for(const s of t?.choices||[]){const c=s?.message;if(c){typeof c.content=="string"&&(c.content=a(c.content,n));for(const o of c.tool_calls||[])o?.function&&typeof o.function.arguments=="string"&&(o.function.arguments=e?e.toTool(o.function.name,o.function.arguments):l(o.function.arguments,n))}}return t}export{x as collectSegments,T as extractLatestToolResult,h as extractTools,y as injectSystemNote,A as joinTextParts,p as matches,S as restoreResponse,_ as toTurn};
|
package/src/order.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export*from"@chatpanel/events/order.js";
|
package/src/project.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export*from"@chatpanel/events/project.js";
|
package/src/providers.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CAPABILITIES as m,CAPABILITY_ROUTES as b,PROVIDER_KINDS as k}from"./capability-endpoints.js";import{listDestinations as h}from"./router.js";import{defaultEmbeddedModel as c}from"./embedded-models.js";const g=/^(localhost|127\.|\[::1\]|0\.0\.0\.0)/,v=/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[?fe80:|.*\.local$)/i;function l(t){if(!t)return"none";let r="";try{r=new URL(t).hostname}catch{return"internet"}return g.test(r)?"loopback":v.test(r)?"lan":"internet"}const d=t=>typeof t=="string"&&t.trim()?t.trim():null;function f(t,r){const e=t?.capabilities?.[r];if(!e||typeof e!="object")return null;const a=d(e.url);let n=k.includes(e.provider)?e.provider:null;return n||(n=e.service?"container":a?"remote":"embedded"),n==="remote"&&!/^https?:\/\//.test(a||"")?null:{kind:n,...a?{url:a}:{},...d(e.adapter)?{adapter:d(e.adapter)}:{},...d(e.model)?{model:d(e.model)}:n==="embedded"&&c(r)?{model:c(r)}:{},...d(e.service)?{service:d(e.service)}:{},...d(e.token)?{token:d(e.token)}:{},...typeof e.calibrated=="boolean"?{calibrated:e.calibrated}:{},...typeof e.redact=="boolean"?{redact:e.redact}:{},egress:n==="embedded"?"none":n==="container"?"loopback":l(a)}}function y(t,r,e={}){if(!m.includes(r))throw new Error(`providerOf: unknown capability ${r}`);const a=f(t,r);if(a)return o(r,a,e);switch(r){case"chat":{const n=h(t),s=n.filter(u=>u.type==="agent").length,i=n.filter(u=>u.type!=="agent");if(!n.length)return o(r,{kind:"none",egress:"none"},e);if(!i.length)return o(r,{kind:"harness",egress:"internet",destinations:n.length,harnesses:s},e);const p=i.some(u=>l(u.baseUrl)==="internet")?"internet":i.some(u=>l(u.baseUrl)==="lan")?"lan":"loopback";return o(r,{kind:"router",egress:p,destinations:n.length,harnesses:s,apis:i.length},e)}case"detect":{const n=t?.redaction?.detection;return n?.backend==="endpoint"&&d(n.url)?o(r,{kind:"remote",url:n.url,adapter:"detect",egress:l(n.url)},e):n?.backend&&n.backend!=="off"&&n.backend!=="endpoint"?o(r,{kind:"embedded",egress:"none",model:e.nerModel||t?.ner?.model},e):o(r,{kind:"embedded",egress:"none",model:e.nerModel||t?.ner?.model},e)}case"stt":return t?.stt?.enabled===!1?o(r,{kind:"none",egress:"none"},e):o(r,{kind:"embedded",egress:"none",model:e.sttModel||t?.stt?.model},e);case"tts":{const n=t?.tts?.provider;if(t?.tts?.enabled===!1)return o(r,{kind:"none",egress:"none"},e);if(n&&n!=="local"){const s=t?.tts?.remote||{},i=d(s.baseUrl)||(n==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1");return o(r,{kind:"remote",url:i,adapter:n,model:d(s.model)||void 0,egress:l(i),redact:s.redact!==!1},e)}return o(r,{kind:"embedded",egress:"none",model:e.ttsModel||t?.tts?.model},e)}case"search":{const n=t?.search?.provider||"auto",s=d(t?.search?.searxng?.url);return n==="searxng"||n==="auto"&&s?o(r,{kind:l(s)==="loopback"?"container":"remote",url:s,adapter:"searxng",egress:l(s)},e):o(r,{kind:"embedded",adapter:"serp",egress:"internet"},e)}case"read":{const n=t?.read?.provider||"defuddle",s=d(t?.read?.remote?.url);return n==="remote"&&s?o(r,{kind:"remote",url:s,adapter:"remote",egress:l(s)},e):o(r,{kind:"embedded",adapter:n,egress:"internet"},e)}case"extract":return o(r,{kind:"embedded",egress:"none"},e);case"rerank":case"decide":return o(r,{kind:"embedded",model:c(r),egress:"none"},e);default:return o(r,{kind:"none",egress:"none"},e)}}const w={embedded:"this device",container:"a container on this device",remote:"a server",harness:"coding agents, each at its own vendor",router:"the model router",none:"nobody yet"};function o(t,r,e){const a=r.kind==="remote"?(()=>{try{return new URL(r.url).host}catch{return r.url}})():w[r.kind],n=r.model||r.adapter||r.service||"";return{...r,label:n?`${n} — ${a}`:a,route:b[t]}}function x(t,r={}){return Object.fromEntries(m.map(e=>[e,y(t,e,r)]))}function E(t,r={}){const e=[];for(const[a,n]of Object.entries(x(t,r))){if(n.kind!=="remote"||!n.url)continue;let s=n.url;try{s=new URL(n.url).host}catch{}e.push({id:a,host:s,adapter:n.adapter||"",token:!!n.token,egress:n.egress,route:n.route})}return e}export{E as declaredProviderHosts,l as egressOf,y as providerOf,x as providerTable};
|
|
1
|
+
import{CAPABILITIES as m,CAPABILITY_ROUTES as b,PROVIDER_KINDS as k}from"./capability-endpoints.js";import{listDestinations as h}from"./router.js";import{defaultEmbeddedModel as c}from"./embedded-models.js";const g=/^(localhost|127\.|\[::1\]|0\.0\.0\.0)/,v=/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[?fe80:|.*\.local$)/i;function l(t){if(!t)return"none";let r="";try{r=new URL(t).hostname}catch{return"internet"}return g.test(r)?"loopback":v.test(r)?"lan":"internet"}const d=t=>typeof t=="string"&&t.trim()?t.trim():null;function f(t,r){const e=t?.capabilities?.[r];if(!e||typeof e!="object")return null;const a=d(e.url);let n=k.includes(e.provider)?e.provider:null;return n||(n=e.service?"container":a?"remote":"embedded"),n==="remote"&&!/^https?:\/\//.test(a||"")?null:{kind:n,...a?{url:a}:{},...d(e.adapter)?{adapter:d(e.adapter)}:{},...d(e.model)?{model:d(e.model)}:n==="embedded"&&c(r)?{model:c(r)}:{},...d(e.service)?{service:d(e.service)}:{},...d(e.token)?{token:d(e.token)}:{},...typeof e.calibrated=="boolean"?{calibrated:e.calibrated}:{},...typeof e.redact=="boolean"?{redact:e.redact}:{},egress:n==="embedded"?"none":n==="container"?"loopback":l(a)}}function y(t,r,e={}){if(!m.includes(r))throw new Error(`providerOf: unknown capability ${r}`);const a=f(t,r);if(a)return o(r,a,e);switch(r){case"chat":{const n=h(t),s=n.filter(u=>u.type==="agent").length,i=n.filter(u=>u.type!=="agent");if(!n.length)return o(r,{kind:"none",egress:"none"},e);if(!i.length)return o(r,{kind:"harness",egress:"internet",destinations:n.length,harnesses:s},e);const p=i.some(u=>l(u.baseUrl)==="internet")?"internet":i.some(u=>l(u.baseUrl)==="lan")?"lan":"loopback";return o(r,{kind:"router",egress:p,destinations:n.length,harnesses:s,apis:i.length},e)}case"detect":{const n=t?.redaction?.detection;return n?.backend==="endpoint"&&d(n.url)?o(r,{kind:"remote",url:n.url,adapter:"detect",egress:l(n.url)},e):n?.backend&&n.backend!=="off"&&n.backend!=="endpoint"?o(r,{kind:"embedded",egress:"none",model:e.nerModel||t?.ner?.model},e):o(r,{kind:"embedded",egress:"none",model:e.nerModel||t?.ner?.model},e)}case"stt":return t?.stt?.enabled===!1?o(r,{kind:"none",egress:"none"},e):o(r,{kind:"embedded",egress:"none",model:e.sttModel||t?.stt?.model},e);case"tts":{const n=t?.tts?.provider;if(t?.tts?.enabled===!1)return o(r,{kind:"none",egress:"none"},e);if(n&&n!=="local"){const s=t?.tts?.remote||{},i=d(s.baseUrl)||(n==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1");return o(r,{kind:"remote",url:i,adapter:n,model:d(s.model)||void 0,egress:l(i),redact:s.redact!==!1},e)}return o(r,{kind:"embedded",egress:"none",model:e.ttsModel||t?.tts?.model},e)}case"search":{const n=t?.search?.provider||"auto",s=d(t?.search?.searxng?.url);return n==="searxng"||n==="auto"&&s?o(r,{kind:l(s)==="loopback"?"container":"remote",url:s,adapter:"searxng",egress:l(s)},e):o(r,{kind:"embedded",adapter:"serp",egress:"internet"},e)}case"read":{const n=t?.read?.provider||"defuddle",s=d(t?.read?.remote?.url);return n==="remote"&&s?o(r,{kind:"remote",url:s,adapter:"remote",egress:l(s)},e):o(r,{kind:"embedded",adapter:n,egress:"internet"},e)}case"extract":return o(r,{kind:"embedded",egress:"none"},e);case"rerank":case"decide":return o(r,{kind:"embedded",model:c(r),egress:"none"},e);case"embed":return o(r,{kind:"embedded",model:c(r),egress:"none"},e);default:return o(r,{kind:"none",egress:"none"},e)}}const w={embedded:"this device",container:"a container on this device",remote:"a server",harness:"coding agents, each at its own vendor",router:"the model router",none:"nobody yet"};function o(t,r,e){const a=r.kind==="remote"?(()=>{try{return new URL(r.url).host}catch{return r.url}})():w[r.kind],n=r.model||r.adapter||r.service||"";return{...r,label:n?`${n} — ${a}`:a,route:b[t]}}function x(t,r={}){return Object.fromEntries(m.map(e=>[e,y(t,e,r)]))}function E(t,r={}){const e=[];for(const[a,n]of Object.entries(x(t,r))){if(n.kind!=="remote"||!n.url)continue;let s=n.url;try{s=new URL(n.url).host}catch{}e.push({id:a,host:s,adapter:n.adapter||"",token:!!n.token,egress:n.egress,route:n.route})}return e}export{E as declaredProviderHosts,l as egressOf,y as providerOf,x as providerTable};
|
package/src/read-document.js
CHANGED
|
@@ -1,10 +1 @@
|
|
|
1
|
-
|
|
2
|
-
`)){const u=c;if(c+=l.length+1,/^\s*(```|~~~)/.test(l)){o=!o;continue}if(o)continue;r.lastIndex=0;const a=r.exec(l);if(!a)continue;const p=a[2].trim();let f=e.get(p)||h(p);const g=(n.get(f)||0)+1;n.set(f,g),g>1&&(f=`${f}-${g}`),s.push({id:f,heading:p,level:a[1].length,offset:u})}return s}function $(t,e,i=[]){const s=String(t||"");if(!(e>0)||s.length<=e)return{text:s,truncated:!1};const n=Math.floor(e*.8);let r=-1;for(const o of i)o.offset>=n&&o.offset<=e&&(r=o.offset);if(r<0){const o=s.lastIndexOf(`
|
|
3
|
-
|
|
4
|
-
`,e);o>=n&&(r=o)}if(r<0){const o=s.lastIndexOf(`
|
|
5
|
-
`,e);r=o>=n?o:e}return{text:s.slice(0,r).trimEnd(),truncated:!0}}function m(t){const e=[];t.title&&e.push(`Title: ${t.title}`),e.push(`URL Source: ${t.url}`),t.published&&e.push(`Published Time: ${t.published}`),t.author&&e.push(`Author: ${t.author}`);const i=t[t.format||"markdown"]||t.markdown||t.text||"";return`${e.join(`
|
|
6
|
-
`)}
|
|
7
|
-
|
|
8
|
-
${t.format==="text"?"Text Content:":"Markdown Content:"}
|
|
9
|
-
${i}
|
|
10
|
-
`}export{x as canonicalUrl,d as headingIds,S as sectionsOf,h as slugify,m as toJinaText,$ as truncateAtSection};
|
|
1
|
+
export*from"@chatpanel/events/read-document.js";
|
package/src/recruit.js
CHANGED
|
@@ -1,4 +1 @@
|
|
|
1
|
-
|
|
2
|
-
`)}function U(e,l=[]){const n=Z(e,A);if(!n)return null;const s=n.value,o=String(s.pick||"").trim(),a=o?(l||[]).find(i=>i.agentId===o):null,r=s.proposalName?{name:y(s.proposalName,60),purpose:y(s.proposalPurpose,300),skills:(s.proposalSkills||[]).map(i=>y(i,80)).filter(Boolean),grants:(s.proposalGrants||[]).map(i=>y(i,64)).filter(Boolean)}:null;return a&&a.engine?{pick:o,why:y(s.why,400)||"the evaluator's pick",confidence:B(s.confidence),proposal:null}:{pick:"",why:a?`the evaluator picked ${o}, which no engine can run right now`:y(s.why,400)||"none fits",confidence:B(s.confidence),proposal:r}}function ue(e,l,{evaluation:n=null,minFit:s=E}={}){const o=l||[];if(n&&n.pick){const i=o.find(c=>c.agentId===n.pick&&c.engine);if(i)return{kind:"recruit",agentId:i.agentId,engine:i.engine,fit:i.fit,why:n.why,by:"evaluator"}}if(n&&!n.pick)return{kind:"none",why:n.why,proposal:n.proposal||j(e),by:"evaluator"};const a=o.find(i=>i.engine&&i.covers!==!1);return a&&a.fit>=s?{kind:"recruit",agentId:a.agentId,engine:a.engine,fit:a.fit,why:`best fit (${Math.round(a.fit*100)}%): ${(a.reasons||[])[0]||"meets the needs"}`,by:"fit"}:{kind:"none",why:o.length?a?`the best fit is ${Math.round(a.fit*100)}%, under the ${Math.round(s*100)}% floor: ${(a.reasons||[]).find(i=>/missing/.test(i))||a.reasons?.[0]||""}`:o.some(i=>i.engine)?`no applicant has a skill the job names (${(e?.needs?.skills||[]).join(", ")})`:`${o.length} applied but no engine clears for any of them: ${(o[0].reasons||[]).find(i=>/engine|pinned|roster/.test(i))||"see the applications"}`:"no one in the pool applies to jobs",proposal:j(e),by:"fit"}}function j(e){const l=e?.needs||{};return{name:y(e?.title,60)||"New agent",purpose:`Does jobs like "${y(e?.title,80)}".`,skills:[...l.skills||[]],grants:(l.grants||[]).length?[...l.grants]:["none"]}}function xe(e,l,{by:n="evaluator"}={}){const s=e||j(l),o=new Set(["data","web","history","mcp",...T]),a=(s.grants||[]).map(r=>String(r).toLowerCase()).filter(r=>o.has(r)||/^mcp:/.test(r));return H({name:s.name,purpose:s.purpose,skills:s.skills,prompt:`You are ${s.name}. ${s.purpose||""}
|
|
3
|
-
|
|
4
|
-
You were proposed for the job "${y(l?.title,200)}" because no agent in the pool fit it. Do work like it well; ask on the thread when the brief is unclear.`,grants:a.length?a:["none"],engine:{kind:"auto",prefer:"balanced"},appliesTo:["jobs"],createdBy:n,origin:{kind:"proposal",projectId:l?.projectId,jobId:l?.id}})}function pe(e,l=null){if(e?.budget&&Object.keys(e.budget).length)return ee(e.budget);const n=l?.page?.budget||{},s=l?.spend||{},o=Math.max(1,(l?.jobs||[]).filter(r=>["open","evaluating"].includes(r.status)).length),a={};for(const r of["tokens","calls","ms","usd"]){if(!(Number(n[r])>0))continue;const i=Math.max(0,Number(n[r])-(Number(s[r])||0));i>0&&(a[r]=r==="usd"?Math.round(i/o*100)/100:Math.max(1,Math.floor(i/o)))}return Object.keys(a).length?a:null}function he(e,l,n,{by:s="evaluator",at:o=Date.now(),record:a=null}={}){const r=[{type:"job.updated",at:o,job:{id:e.id,status:"evaluating",applications:(l||[]).map(({covers:i,...c})=>c)},by:s}];if(n?.kind==="recruit"){const i=pe(e,a);r.push({type:"job.updated",at:o,job:{id:e.id,status:"recruited",recruited:{agentId:n.agentId,engine:n.engine,...i?{budget:i}:{},by:n.by||s,at:o,why:y(n.why,600)}},by:s})}else{r.push({type:"job.updated",at:o,job:{id:e.id,status:"open"},by:s});const i=n?.proposal;r.push({type:"project.decision",at:o,by:s,kind:"proposal",text:`No one in the pool fits "${y(e.title,120)}": ${y(n?.why,400)}${i?` Proposed: ${i.name}${i.skills?.length?` — skills ${i.skills.join(", ")}`:""}${i.grants?.length?`; grants ${i.grants.join(", ")}`:""}.`:""}`,refs:[`job:${e.id}`]})}return r}async function Me(e,l,{summaries:n={},rows:s=[],reach:o="any",chatModel:a=null,record:r=null,ask:i=null,minFit:c=E,by:t="evaluator",now:h=Date.now()}={}){const d=re(e,l,{summaries:n,rows:s,reach:o,chatModel:a,now:h}),u=ce(e,d,l,{rows:s});let m=null;if(i&&d.some(f=>f.engine))try{const f=await i(u,A);m=f==null?null:U(typeof f=="string"?f:JSON.stringify(f),d)}catch{m=null}const p=ue(e,d,{evaluation:m,minFit:c});return{applications:d,evaluation:m,decision:p,events:he(e,d,p,{by:p.by==="evaluator"?t:"fit",at:h,record:r}),prompt:u}}export{te as MAX_BRIEF_IN_PROMPT,E as MIN_FIT,A as RECRUIT_SCHEMA,ne as TOP_APPLICANTS,re as applications,pe as carveBudget,ue as decide,_ as engineRow,ve as engineRows,le as engineWorth,ce as evaluatorPrompt,F as needForJob,U as parseEvaluation,j as proposalFromNeeds,xe as proposalToAgent,he as recruitEvents,Me as recruitJob,ae as routeFor};
|
|
1
|
+
export*from"@chatpanel/events/recruit.js";
|
package/src/ref.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export*from"@chatpanel/events/ref.js";
|
package/src/rrf.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export*from"@chatpanel/events/rrf.js";
|
package/src/scorecard.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const E=Object.freeze(["task.done","task.failed","rating","created","interaction","role"]),T=Object.freeze(["ic","orchestrator","manager","manager-of-managers"]),H=1,_=Object.freeze(["model","harness"]);function A(e){if(!e)return null;const s=typeof e=="string"?{id:e}:e,t=String(s.id||s.harnessId||s.model||"").trim();if(!t)return null;const r=_.includes(s.kind)?s.kind:s.harnessId?"harness":"model",d=s.model!=null&&String(s.model).trim()&&String(s.model)!==t?String(s.model).trim():void 0;return{kind:r,id:t,...d?{model:d}:{},...s.label&&String(s.label)!==t?{label:String(s.label).slice(0,120)}:{}}}function O(e){const s=A(e);return s?`${s.kind}:${s.id}${s.model?`/${s.model}`:""}`:null}function K(e){if(!e||typeof e!="object")return null;const s=(r,d=200)=>r==null||r===""?void 0:String(r).slice(0,d),t={repo:s(e.repo,300),remote:s(e.remote,300),base:s(e.base,120),branch:s(e.branch,120),head:s(e.head,64),headAfter:s(e.headAfter,64),commits:e.commits!=null?Math.max(0,Math.round(Number(e.commits)||0)):void 0,pr:s(e.pr,300),merged:e.merged===!0?!0:e.merged===!1?!1:void 0,dirty:e.dirty===!0?!0:e.dirty===!1?!1:void 0};for(const r of Object.keys(t))t[r]===void 0&&delete t[r];return Object.keys(t).length?t:null}const N=new TextEncoder,C=e=>[...new Uint8Array(e)].map(s=>s.toString(16).padStart(2,"0")).join("");function q(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(q).join(",")}]`:`{${Object.keys(e).sort().map(s=>e[s]===void 0?null:`${JSON.stringify(s)}:${q(e[s])}`).filter(Boolean).join(",")}}`}async function D(e,{subtle:s=globalThis.crypto?.subtle}={}){if(!s)throw new Error("scorecard: no crypto.subtle — pass one");return C(await s.digest("SHA-256",N.encode(String(e))))}function R(e){const{hash:s,sig:t,...r}=e;return r}async function G(e,s,{now:t=()=>Date.now(),subtle:r}={}){if(!e||typeof e!="object")throw new Error("scorecard: an entry needs a fact");if(!E.includes(e.kind))throw new Error(`scorecard: kind must be one of ${E.join(", ")}`);if(!e.agentId)throw new Error("scorecard: agentId required");const d={v:H,seq:s?s.seq+1:0,agentId:String(e.agentId),kind:e.kind,at:Number(e.at)||t(),...e.projectId?{projectId:String(e.projectId)}:{},...e.jobId?{jobId:String(e.jobId)}:{},...e.runId?{runId:String(e.runId)}:{},...e.taskId?{taskId:String(e.taskId)}:{},...e.model?{model:String(e.model)}:{},...A(e.engine)?{engine:A(e.engine)}:{},...K(e.scm)?{scm:K(e.scm)}:{},...e.size?{size:B(e.size)}:{},...e.roleKind?{roleKind:T.includes(e.roleKind)?e.roleKind:"ic"}:{},...Array.isArray(e.tools)&&e.tools.length?{tools:[...new Set(e.tools.map(String))].sort()}:{},...Array.isArray(e.with)&&e.with.length?{with:[...new Set(e.with.map(String))].sort()}:{},...Array.isArray(e.created)&&e.created.length?{created:[...new Set(e.created.map(String))]}:{},...e.rating?{rating:{by:String(e.rating.by||"person"),score:F(e.rating.score),...e.rating.note?{note:String(e.rating.note).slice(0,500)}:{},...e.rating.about!=null?{about:Number(e.rating.about)}:{}}}:{},...Array.isArray(e.refs)&&e.refs.length?{refs:e.refs.map(String).slice(0,12)}:{},...e.error?{error:String(e.error).slice(0,300)}:{},prev:s?s.hash:null};return d.hash=await D(q(R(d)),{subtle:r}),d}const F=e=>Math.max(0,Math.min(1,Number(e)||0)),v=e=>e==null?null:Math.round(e*1e3)/1e3,B=e=>({ms:Math.max(0,Math.round(Number(e.ms)||0)),steps:Math.max(0,Math.round(Number(e.steps)||0)),tools:Math.max(0,Math.round(Number(e.tools)||0)),findings:Math.max(0,Math.round(Number(e.findings)||0)),tokens:Math.max(0,Math.round(Number(e.tokens)||0))});async function J(e,{subtle:s}={}){let t=null;for(const r of e||[]){if(!r||typeof r!="object")return{ok:!1,at:t?t.seq+1:0,why:"not an entry"};if((t?t.seq+1:0)!==r.seq)return{ok:!1,at:r.seq,why:"seq"};if((t?t.hash:null)!==r.prev)return{ok:!1,at:r.seq,why:"prev"};if(await D(q(R(r)),{subtle:s})!==r.hash)return{ok:!1,at:r.seq,why:"hash"};t=r}return{ok:!0,at:null,length:(e||[]).length}}async function U(e,s,{subtle:t=globalThis.crypto?.subtle}={}){const r=await t.importKey("raw",s,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return{...e,sig:C(await t.sign("HMAC",r,N.encode(e.hash)))}}async function P(e,s,{subtle:t=globalThis.crypto?.subtle}={}){const r=await t.importKey("raw",s,{name:"HMAC",hash:"SHA-256"},!1,["verify"]),d=[];for(const h of e||[]){const c=h?.sig?new Uint8Array(h.sig.match(/../g).map(j=>parseInt(j,16))):null;d.push(!!c&&await t.verify("HMAC",r,c,N.encode(h.hash)))}return{ok:d.every(Boolean),attested:d.filter(Boolean).length,of:d.length}}function V(e,{recent:s=5}={}){const t=(e||[]).filter(n=>n&&n.kind),r=t.filter(n=>n.kind==="task.done"),d=t.filter(n=>n.kind==="task.failed"),h=n=>r.reduce((i,g)=>i+(g.size?.[n]||0),0),c=r.reduce((n,i)=>Math.max(n,i.size?.steps||0),0),j=new Set,k=new Set,M=new Set,b={ic:0,orchestrator:0,manager:0,"manager-of-managers":0},u=new Map,p=new Map,w=new Map,$=new Map,y=new Map,f={tasks:0,commits:0,prs:0,merged:0};for(const n of t){for(const i of n.tools||[])j.add(i);for(const i of n.with||[])k.add(i);for(const i of n.created||[])M.add(i);if(n.roleKind&&(n.kind==="task.done"||n.kind==="task.failed"||n.kind==="role")&&(b[n.roleKind]=(b[n.roleKind]||0)+1),n.model&&u.set(n.model,(u.get(n.model)||0)+1),n.kind==="task.done"||n.kind==="task.failed"){const i=O(n.engine);if(i){const g=p.get(i)||{engine:A(n.engine),tasks:0,done:0,failed:0,tokens:0,ratings:[]};g.tasks+=1,g[n.kind==="task.done"?"done":"failed"]+=1,g.tokens+=n.size?.tokens||0,p.set(i,g),w.set(n.seq,i),n.taskId&&$.set(`${n.runId||""}/${n.taskId}`,n.seq),n.runId&&y.set(n.runId,[...y.get(n.runId)||[],n.seq])}n.scm&&(f.tasks+=1,f.commits+=n.scm.commits||0,n.scm.pr&&(f.prs+=1),n.scm.merged&&(f.merged+=1))}}for(const n of t){if(n.kind!=="rating"||!n.rating)continue;const i=n.rating.about!=null?n.rating.about:n.taskId&&$.has(`${n.runId||""}/${n.taskId}`)?$.get(`${n.runId||""}/${n.taskId}`):n.runId&&(y.get(n.runId)||[]).length===1?y.get(n.runId)[0]:null,g=i!=null?w.get(i):null;g&&p.get(g).ratings.push(n.rating.score)}const S=n=>n.length?n.reduce((i,g)=>i+g,0)/n.length:null,a=[...p.values()].sort((n,i)=>i.tasks-n.tasks).map(n=>({key:O(n.engine),...n.engine,tasks:n.tasks,done:n.done,failed:n.failed,failRate:n.tasks?Math.round(n.failed/n.tasks*1e3)/1e3:0,tokens:n.tasks?Math.round(n.tokens/n.tasks):0,rating:{avg:S(n.ratings),count:n.ratings.length}})),m=a.filter(n=>n.rating.avg!=null).map(n=>n.rating.avg),o=m.length>=2?Math.round((1-(Math.max(...m)-Math.min(...m)))*1e3)/1e3:null,l=t.filter(n=>n.kind==="rating"&&n.rating).map(n=>n.rating.score),x=l.length?l.reduce((n,i)=>n+i,0)/l.length:null,I=l.slice(-s),z=[...new Set(t.flatMap(n=>n.refs||[]))].slice(-s);return{agentId:t[0]?.agentId||null,entries:t.length,jobsDone:r.length,jobsFailed:d.length,size:{ms:h("ms"),steps:h("steps"),tools:h("tools"),findings:h("findings"),tokens:h("tokens"),largestSteps:c},tools:[...j].sort(),workedWith:[...k].sort(),created:[...M],roles:b,models:[...u.entries()].sort((n,i)=>i[1]-n[1]).map(([n,i])=>({model:n,tasks:i})),byEngine:a,engineIndependence:o,scm:f,rating:{avg:x,count:l.length,recent:I.length?I.reduce((n,i)=>n+i,0)/I.length:null},refs:z,since:t[0]?.at||null,last:t.at(-1)?.at||null,head:t.at(-1)?.hash||null}}function W(e,s,t=null,{qualityOf:r=null,costOf:d=null,adjust:h=!0}={}){const c=e?.needs||{},j=x=>new Set((x||[]).map(I=>String(I).toLowerCase())),k=j(s?.skills),M=j(s?.tools),b=j(s?.grants),u=[],p=(x,I,z)=>{const n=(x||[]).map(g=>String(g).toLowerCase());if(!n.length)return 1;const i=n.filter(g=>I.has(g));return i.length<n.length&&u.push(`missing ${z}: ${n.filter(g=>!I.has(g)).join(", ")}`),i.length/n.length},w=p(c.skills,k,"skills"),$=p(c.tools,M,"tools"),y=p(c.grants,b,"grants"),f=w*.5+$*.3+y*.2;f===1&&u.push("has every skill, tool and grant the job names");let S=.5,a=null;if(t&&t.entries){const x=t.jobsDone+t.jobsFailed?t.jobsDone/(t.jobsDone+t.jobsFailed):.5;a=h&&r&&t.rating.avg!=null?L(t,{qualityOf:r,costOf:d||void 0}):null;const I=t.rating.avg==null?.5:a?.adjusted??t.rating.avg;S=x*.5+I*.5,u.push(`${t.jobsDone} done, ${t.jobsFailed} failed${t.rating.avg!=null?a&&a.adjusted!==a.raw?`, rated ${Math.round(a.raw*100)}% raw, ${Math.round(a.adjusted*100)}% adjusted — ${a.basis[0]||"engine-corrected"}`:`, rated ${Math.round(t.rating.avg*100)}%`:""}`),a?.leverage!=null&&a.leverage>.05&&u.push(`adds ${a.leverage} over its engines' own quality`),a?.efficiency&&u.push(`cleared the bar cheapest on ${a.efficiency.engine}`),t.roles.orchestrator+t.roles.manager+t.roles["manager-of-managers"]>0&&u.push(`has led: ${t.roles.orchestrator} as orchestrator, ${t.roles.manager} as manager`)}else u.push("no record yet");const m=Number(e?.size?.steps)||0,o=m?Math.min(1,(t?.size?.largestSteps||0)/m)*.5+.5:1;return m&&(t?.size?.largestSteps||0)<m&&u.push(`largest task so far ${t?.size?.largestSteps||0} steps; this one is ~${m}`),{score:Math.round((f*.6+S*.3+o*.1)*1e3)/1e3,reasons:u,parts:{needs:f,record:S,size:o},...a?{adjusted:a}:{}}}function L(e,{qualityOf:s=()=>null,costOf:t=()=>null,reference:r=.6,k:d=.3,bar:h=.5}={}){const c=e?.rating?.avg??null,k=(e?.byEngine||[]).filter(o=>o.key).map(o=>({...o,quality:s(o.key)})).filter(o=>Number.isFinite(o.quality)),M=k.reduce((o,l)=>o+l.tasks,0),b=[];if(c==null||!k.length||!M)return{raw:c,adjusted:c,leverage:null,efficiency:null,basis:c==null?["not rated yet"]:["engines not rated yet — raw rating used"]};const u=d*k.reduce((o,l)=>o+l.tasks/M*(r-l.quality),0),p=Math.max(0,Math.min(1,c+u)),w=k.filter(o=>o.quality<r);w.length&&b.push(`${Math.round(w.reduce((o,l)=>o+l.tasks,0)/M*100)} % of its tasks ran on ${w.length===1?`a ${w[0].quality}-quality engine`:"engines below the reference"}`);const $=k.filter(o=>o.quality>r);$.length&&!w.length&&b.push(`ran on engines above the reference (${$.map(o=>o.quality).join(", ")})`);const y=k.filter(o=>o.rating?.avg!=null),f=y.reduce((o,l)=>o+l.rating.count,0),S=f?v(y.reduce((o,l)=>o+l.rating.count/f*(l.rating.avg-l.quality),0)):null;S!=null&&b.push(`${S>=0?"+":""}${S} over its engines' own quality`);const a=y.filter(o=>o.rating.avg>=h).map(o=>({...o,cost:t(o.key)??(o.tokens||null)})).filter(o=>o.cost!=null&&o.cost>0).sort((o,l)=>o.cost-l.cost),m=a.length?{value:v(p/a[0].cost),engine:a[0].key,costPerTask:a[0].cost}:null;return{raw:v(c),adjusted:v(p),leverage:S,efficiency:m,basis:b}}export{_ as ENGINE_KINDS,T as ROLE_KINDS,E as SCORECARD_ENTRY_KINDS,H as SCORECARD_VERSION,L as adjustSummary,U as attest,q as canonical,O as engineKey,W as fit,G as makeEntry,A as normalizeEngine,K as normalizeScm,D as sha256,V as summarize,P as verifyAttested,J as verifyChain};
|
|
1
|
+
export*from"@chatpanel/events/scorecard.js";
|