@anmol-srv/sigil 0.14.0 → 0.15.3
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/dist/cli.js +395 -335
- package/dist/daemon.js +165 -131
- package/dist/hooks/post-tool-use.js +23 -23
- package/dist/hooks/session-end.js +67 -67
- package/dist/hooks/stop.js +70 -70
- package/dist/hooks/user-prompt-submit.js +45 -45
- package/dist/server.js +48 -44
- package/package.json +4 -3
- package/src/db/drivers/index.js +41 -0
- package/src/db/drivers/local-postgres.js +23 -0
- package/src/db/drivers/url.js +155 -0
- package/src/db/drivers/url.test.js +94 -0
- package/src/db/migrations/20260601000006_add-entity-name-trigram-index.cjs +25 -0
- package/src/gui/web/app.css +160 -18
- package/src/gui/web/app.js +36 -8
- package/src/gui/web/design/colors_and_type.css +2 -2
- package/src/gui/web/index.html +27 -4
- package/src/gui/web/setup.js +2 -2
|
@@ -1,67 +1,67 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __sigilCreateRequire } from 'node:module'; const require = __sigilCreateRequire(import.meta.url);
|
|
3
|
-
var
|
|
4
|
-
`,{mode:384}),
|
|
5
|
-
`)){let r=n.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);if(!r)continue;let o=r[2].trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),t[r[1]]=o}return t}function
|
|
3
|
+
var Qr=Object.defineProperty;var h=(e,t)=>()=>(e&&(t=e(e=0)),t);var D=(e,t)=>{for(var n in t)Qr(e,n,{get:t[n],enumerable:!0})};function F(e){if(!e||typeof e!="string")return e;let t=e;for(let n of eo)t=t.replace(n,te);return t=t.replace(to,(n,r)=>`${r}=${te}`),t=t.replace(no,(n,r)=>`${r}${te}:${te}@`),t=t.replace(oo,(n,r)=>`${r}=${te}`),t}var te,eo,to,no,ro,oo,me=h(()=>{te="***MASKED***",eo=[/\b(sk-(?:proj-|ant-)?[A-Za-z0-9_\-]{20,})\b/g,/\b(ghp_[A-Za-z0-9]{36,})\b/g,/\b(github_pat_[A-Za-z0-9_]{20,})\b/g,/\b(gho_[A-Za-z0-9]{36,})\b/g,/\b(glpat-[A-Za-z0-9_\-]{20,})\b/g,/\b(xox[baprs]-[A-Za-z0-9\-]{10,})\b/g,/\b(whsec_[A-Za-z0-9]{20,})\b/g,/\b(rk_(?:live|test)_[A-Za-z0-9]{20,})\b/g,/\b(AKIA[A-Z0-9]{16})\b/g,/\b(ASIA[A-Z0-9]{16})\b/g,/\b(eyJ[A-Za-z0-9_\-]{20,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,})\b/g,/\b([A-Za-z0-9]{24}\.[A-Za-z0-9_\-]{6}\.[A-Za-z0-9_\-]{27})\b/g,/\b(\d{8,12}:[A-Za-z0-9_\-]{35})\b/g],to=new RegExp(`\\b(api[_-]?key|api[_-]?secret|secret[_-]?key|secret|token|password|passwd|pwd|auth[_-]?token|access[_-]?token|refresh[_-]?token|bearer|private[_-]?key|client[_-]?secret)\\s*[=:]\\s*["']?([^\\s"']{8,})["']?`,"gi"),no=/(\w+:\/\/)([^:/\s]+):([^@\s]{3,})@/g,ro=["DATABASE_URL","REDIS_URL","MONGODB_URI","MONGO_URI","POSTGRES_URL","DSN","CONNECTION_STRING","ENCRYPTION_KEY","JWT_SECRET","SIGIL_ENCRYPTION_KEY","SESSION_SECRET","WEBHOOK_SECRET"],oo=new RegExp(`\\b(${ro.join("|")})\\s*[=:]\\s*["']?([^\\s"']+)["']?`,"gi")});import{fileURLToPath as io}from"node:url";import{dirname as It,join as A}from"node:path";import{existsSync as bt}from"node:fs";import{homedir as ao}from"node:os";function so(){let e=It(io(import.meta.url));for(let t=0;t<10;t++){if(bt(A(e,"package.json"))&&bt(A(e,"prompts")))return e;let n=It(e);if(n===e)break;e=n}return process.cwd()}var fe,he,Ss,Ot,N,x,k,As,Is,co,Tt,lo,Dt,bs,Os,Ts,Ds,Ns,Rs,Ls,vs,Cs,Ms,Ps,Nt,xs,ks,B=h(()=>{fe=so(),he=A(fe,"prompts"),Ss=A(fe,"src","db","migrations"),Ot=ao(),N=A(Ot,".sigil"),x=A(N,".env"),k=A(N,"config.json"),As=A(N,"db"),Is=A(N,"CLAUDE.md"),co=A(N,"schemas"),Tt=A(N,".hook-errors.log"),lo=A(N,".last-clean-doctor"),Dt=A(N,".active-session.json"),bs=A(N,".stop-cursor.json"),Os=A(N,".hook-dedup.json"),Ts=A(N,"sock"),Ds=A(N,"sigild.pid"),Ns=A(N,"sigild.log"),Rs=A(N,"heartbeat.json"),Ls=A(N,"gui.token"),vs=A(fe,"dist","gui"),Cs=A(fe,"src","gui","web"),Ms=A(N,"iroh"),Ps=A(N,"identity.key"),Nt=A(Ot,".claude"),xs=A(Nt,"settings.json"),ks=A(Nt,"CLAUDE.md")});var Be=h(()=>{});import{existsSync as $e,readFileSync as Ct,writeFileSync as uo,renameSync as Mt,mkdirSync as po,chmodSync as mo,unlinkSync as Us}from"node:fs";import{dirname as fo}from"node:path";function ne(){return{schemaVersion:_e,device:{id:null},database:{mode:null,url:null,host:"localhost",port:5432,name:"sigil",user:"sigil_app",password:null},llm:{provider:null,model:null,apiKey:null,host:null},embedding:{provider:null,model:null,apiKey:null,host:null},identity:{name:null},setup:{complete:!1,steps:{}}}}function W(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ee(e,t){if(!W(t))return t;let n=Array.isArray(e)?[...e]:{...e};for(let[r,o]of Object.entries(t))n[r]=W(o)&&W(n[r])?Ee(n[r],o):o;return n}function re(){if(!$e(k))return{};try{return JSON.parse(Ct(k,"utf8"))||{}}catch{return{}}}function _o(e){let t=e,n=Number(t.schemaVersion)||1;for(;n<_e;){let r=n+1,o=ho[r];t=o?o(t):{...t,schemaVersion:r},n=r}return t}function Y(e){let t=ne(),n={};for(let r of Object.keys(t)){if(!(r in e))continue;if(!W(t[r])){n[r]=e[r];continue}let o={};for(let i of Object.keys(t[r]))e[r]&&i in e[r]&&(o[i]=e[r][i]);r==="setup"&&W(e.setup?.steps)&&(o.steps=e.setup.steps),n[r]=o}return n}function Fe(e){po(fo(k),{recursive:!0});let t=`${k}.tmp`;uo(t,`${JSON.stringify(e,null,2)}
|
|
4
|
+
`,{mode:384}),Mt(t,k);try{mo(k,384)}catch{}}function Eo(e,t){let n={};if(!W(t))throw new Error(`config patch for "${e}" must be an object`);if(e==="database"&&("mode"in t&&t.mode!==null&&!Rt.includes(t.mode)&&(n.mode=`must be one of ${Rt.join(", ")}`),"port"in t&&t.port!=null&&!Number.isInteger(Number(t.port))&&(n.port="must be an integer"),"url"in t&&t.url!=null&&typeof t.url!="string"&&(n.url="must be a string")),Object.keys(n).length){let r=new Error(`invalid config for "${e}": ${JSON.stringify(n)}`);throw r.code="invalid_config",r.errors=n,r}}function yo(e){if(!$e(e))return null;let t={};for(let n of Ct(e,"utf8").split(`
|
|
5
|
+
`)){let r=n.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);if(!r)continue;let o=r[2].trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),t[r[1]]=o}return t}function go(e){let t={},n={};if(e.SIGIL_DATABASE_URL||e.DATABASE_URL?(n.mode="url",n.url=e.SIGIL_DATABASE_URL||e.DATABASE_URL):(e.SIGIL_DB_HOST||e.SIGIL_DB_NAME||e.SIGIL_DB_PASSWORD)&&(n.mode="local",e.SIGIL_DB_HOST&&(n.host=e.SIGIL_DB_HOST),e.SIGIL_DB_PORT&&(n.port=Number(e.SIGIL_DB_PORT)||5432),e.SIGIL_DB_NAME&&(n.name=e.SIGIL_DB_NAME),e.SIGIL_DB_USER&&(n.user=e.SIGIL_DB_USER),e.SIGIL_DB_PASSWORD&&(n.password=e.SIGIL_DB_PASSWORD)),Object.keys(n).length&&(t.database=n),e.LLM_PROVIDER){let r={provider:e.LLM_PROVIDER},o={anthropic:e.ANTHROPIC_API_KEY,openai:e.OPENAI_API_KEY,openrouter:e.OPENROUTER_API_KEY}[e.LLM_PROVIDER];o&&(r.apiKey=o);let i={openai:e.LLM_OPENAI_MODEL,openrouter:e.LLM_OPENROUTER_MODEL,ollama:e.LLM_OLLAMA_MODEL,"claude-cli":e.LLM_CLI_MODEL}[e.LLM_PROVIDER];i&&(r.model=i),e.LLM_PROVIDER==="ollama"&&(e.LLM_OLLAMA_HOST||e.OLLAMA_HOST)&&(r.host=e.LLM_OLLAMA_HOST||e.OLLAMA_HOST),t.llm=r}if(e.EMBEDDING_PROVIDER){let r={provider:e.EMBEDDING_PROVIDER};e.EMBEDDING_MODEL&&(r.model=e.EMBEDDING_MODEL);let o={openai:e.OPENAI_API_KEY,voyage:e.VOYAGE_API_KEY,openrouter:e.OPENROUTER_API_KEY}[e.EMBEDDING_PROVIDER];o&&(r.apiKey=o),e.EMBEDDING_PROVIDER==="ollama"&&e.OLLAMA_HOST&&(r.host=e.OLLAMA_HOST),t.embedding=r}return e.SIGIL_SETUP_COMPLETE==="true"&&(t.setup={complete:!0}),t}function wo(){if(!Lt){Lt=!0;try{let e=yo(x);if(!e)return;let t=go(e),n=Y(re()),r={database:!!n.database?.mode,llm:!!n.llm?.provider,embedding:!!n.embedding?.provider,setup:!!n.setup?.complete};for(let[o,i]of Object.entries(t))if(!r[o])try{Io(o,i)}catch{}try{Mt(x,`${x}.migrated`)}catch{}}catch{}}}function So(){wo();let e=re(),t=_o(e);return $e(k)&&t.schemaVersion!==e.schemaVersion&&Fe(Y(t)),U=Ee(ne(),Y(t)),Ao(),U}function Ao(){let e=U?.setup?.steps;if(!e)return;let t=Object.entries(e).filter(([,o])=>o==="active").map(([o])=>o);if(!t.length)return;let n=Y(re()),r={...n.setup?.steps||{}};for(let o of t)r[o]="pending";Fe({...n,schemaVersion:_e,setup:{...n.setup||{},steps:r}}),U=Ee(ne(),Y(re()))}function Pt(){return U||So()}function Io(e,t){if(!(e in ne()))throw new Error(`unknown config section: ${e}`);Eo(e,t);let n=Y(re());return n.schemaVersion=_e,n[e]={...n[e]||{},...t},Fe(n),U=Ee(ne(),n),U}var _e,Rt,ho,U,Lt,xt=h(()=>{B();Be();_e=1,Rt=["local","docker","url"];ho={},U=null;Lt=!1});var Bt={};D(Bt,{default:()=>l});var O,T,Ue,ye,He,kt,bo,l,S=h(()=>{xt();Be();O=(e,t)=>process.env[e]??t,T=()=>Pt(),Ue=e=>T().llm.provider===e&&T().llm.apiKey||"",ye=e=>T().llm.provider===e&&T().llm.model||"",He=e=>T().embedding.provider===e&&T().embedding.apiKey||"",kt=O("SIGIL_DB_TYPE","postgres");if(kt!=="postgres")throw new Error(`SIGIL_DB_TYPE=${kt} is no longer supported. Sigil 0.10.0+ is Postgres-only.
|
|
6
6
|
PGlite was deprecated; existing PGlite data at ~/.sigil/db is preserved but unreachable from this version.
|
|
7
7
|
Set SIGIL_DB_TYPE=postgres in ~/.sigil/.env and configure SIGIL_DB_HOST / PORT / NAME / USER / PASSWORD.
|
|
8
|
-
Run \`sigil init\` for an interactive setup.`);
|
|
9
|
-
`)[0]}`,fix:"Start Postgres (e.g. `docker start sigil-pg` or your equivalent) and verify SIGIL_DB_HOST/PORT/NAME/USER/PASSWORD in ~/.sigil/.env"})}return e}function
|
|
8
|
+
Run \`sigil init\` for an interactive setup.`);bo={db:{type:"postgres",get url(){return process.env.SIGIL_DATABASE_URL||process.env.DATABASE_URL||T().database.url||null},get host(){return process.env.SIGIL_DB_HOST||T().database.host||"localhost"},get port(){return Number(process.env.SIGIL_DB_PORT||T().database.port||5432)},get database(){return process.env.SIGIL_DB_NAME||T().database.name||"sigil"},get user(){return process.env.SIGIL_DB_USER||T().database.user||"sigil_app"},get password(){return process.env.SIGIL_DB_PASSWORD||T().database.password||""}},embedding:{get provider(){return process.env.EMBEDDING_PROVIDER||T().embedding.provider||""},get model(){return process.env.EMBEDDING_MODEL||T().embedding.model||"mxbai-embed-large"},get dimensions(){return 1024},get ollamaHost(){return process.env.OLLAMA_HOST||(T().embedding.provider==="ollama"?T().embedding.host:"")||"http://localhost:11434"},get openaiApiKey(){return process.env.OPENAI_API_KEY||He("openai")},get voyageApiKey(){return process.env.VOYAGE_API_KEY||He("voyage")},get openrouterApiKey(){return process.env.OPENROUTER_API_KEY||He("openrouter")},openrouterBaseUrl:process.env.EMBEDDING_OPENROUTER_BASE_URL||process.env.LLM_OPENROUTER_BASE_URL||"",openrouterReferer:process.env.EMBEDDING_OPENROUTER_REFERER||process.env.LLM_OPENROUTER_REFERER||"https://github.com/Anmol-Srv/sigil",openrouterTitle:process.env.EMBEDDING_OPENROUTER_TITLE||process.env.LLM_OPENROUTER_TITLE||"Sigil"},llm:{get provider(){return process.env.LLM_PROVIDER||T().llm.provider||""},get openaiApiKey(){return process.env.OPENAI_API_KEY||Ue("openai")},get openaiModel(){return process.env.LLM_OPENAI_MODEL||ye("openai")||"gpt-4o-mini"},get ollamaHost(){return process.env.LLM_OLLAMA_HOST||process.env.OLLAMA_HOST||(T().llm.provider==="ollama"?T().llm.host:"")||"http://localhost:11434"},get ollamaModel(){return process.env.LLM_OLLAMA_MODEL||ye("ollama")||"qwen2.5:7b"},get cliModel(){return process.env.LLM_CLI_MODEL||ye("claude-cli")||"haiku"},get cliPath(){return process.env.LLM_CLI_PATH||""},get apiKey(){return process.env.ANTHROPIC_API_KEY||Ue("anthropic")},get openrouterApiKey(){return process.env.OPENROUTER_API_KEY||Ue("openrouter")},get openrouterModel(){return process.env.LLM_OPENROUTER_MODEL||ye("openrouter")||"google/gemini-flash-latest"},get openrouterBaseUrl(){return process.env.LLM_OPENROUTER_BASE_URL||""},get openrouterReferer(){return process.env.LLM_OPENROUTER_REFERER||"https://github.com/Anmol-Srv/sigil"},get openrouterTitle(){return process.env.LLM_OPENROUTER_TITLE||"Sigil"},get extractionModel(){return process.env.LLM_EXTRACTION_MODEL||""},get decisionModel(){return process.env.LLM_DECISION_MODEL||""},get entityModel(){return process.env.LLM_ENTITY_MODEL||""},get maxRetries(){return Number(process.env.LLM_MAX_RETRIES)||3},get cliTimeout(){return Number(process.env.LLM_CLI_TIMEOUT)||12e4},get requestTimeout(){return Number(process.env.LLM_REQUEST_TIMEOUT)||6e4}},output:{storage:process.env.OUTPUT_STORAGE||"local",dir:process.env.OUTPUT_DIR||"./output",s3:{endpoint:process.env.S3_ENDPOINT||"",bucket:process.env.S3_BUCKET||"",region:process.env.S3_REGION||"us-east-1",accessKey:process.env.S3_ACCESS_KEY||"",secretKey:process.env.S3_SECRET_KEY||"",publicUrl:process.env.S3_PUBLIC_URL||""}},server:{port:Number(process.env.PORT)||4e3,host:process.env.HOST||"0.0.0.0",logLevel:process.env.LOG_LEVEL||"info"},http:{enabled:O("SIGIL_HTTP_ENABLED","true")!=="false",host:O("SIGIL_HTTP_HOST","127.0.0.1"),port:Number(O("SIGIL_HTTP_PORT",7777))},network:{mode:O("SIGIL_MODE","solo"),enabled:O("SIGIL_NETWORK_ENABLED",null)===null?O("SIGIL_MODE","solo")!=="solo":O("SIGIL_NETWORK_ENABLED","false")!=="false",masterNodeId:O("SIGIL_MASTER_NODE_ID","")||null},defaults:{namespace:process.env.DEFAULT_NAMESPACE||"default"},memory:{skipThreshold:Number(process.env.MEMORY_SKIP_THRESHOLD)||.88,ambiguousThreshold:Number(process.env.MEMORY_AMBIGUOUS_THRESHOLD)||.78,minFactSimilarity:Number(process.env.MEMORY_MIN_FACT_SIMILARITY)||.45,injectionFloor:Number(process.env.MEMORY_INJECTION_FLOOR)||.6},search:{synthesize:O("SIGIL_SYNTHESIZE","true")!=="false",synthesizeModel:O("SIGIL_SYNTH_MODEL","")},ingest:{eagerExtract:O("SIGIL_EAGER_EXTRACT","true")!=="false"},hebbian:{entity:{enabled:O("SIGIL_HEBBIAN_ENTITY_ENABLED",null,"true")!=="false",eta:Number(O("SIGIL_HEBBIAN_ENTITY_ETA",null,1)),cap:Number(O("SIGIL_HEBBIAN_ENTITY_CAP",null,50)),halfLifeDays:Number(O("SIGIL_HEBBIAN_ENTITY_HALF_LIFE_DAYS",null,30)),minEffective:Number(O("SIGIL_HEBBIAN_ENTITY_MIN_EFFECTIVE",null,.5)),rrfWeight:Number(O("SIGIL_HEBBIAN_ENTITY_RRF_WEIGHT",null,.3)),maxWriteEntities:Number(O("SIGIL_HEBBIAN_ENTITY_MAX_WRITE",null,12)),expandPerSeed:Number(O("SIGIL_HEBBIAN_ENTITY_EXPAND_PER_SEED",null,3))}}},l=bo});function $t(e){return{host:e.db.host,port:e.db.port,database:e.db.database,user:e.db.user,password:e.db.password}}var Ft=h(()=>{});function Ht(e){if(!e)throw new Error("url driver: SIGIL_DATABASE_URL is empty");let t;try{t=new URL(e)}catch(i){throw new Error(`url driver: invalid URL \u2014 ${i.message}`)}if(!/^postgres(ql)?:$/i.test(t.protocol))throw new Error(`url driver: expected postgres:// or postgresql:// scheme, got ${t.protocol}`);let n=t.searchParams.get("sslmode"),r=To(t.hostname,n),o={host:t.hostname,port:t.port?Number(t.port):5432,database:t.pathname.replace(/^\//,"")||"postgres",user:decodeURIComponent(t.username),password:decodeURIComponent(t.password)};return r!==void 0&&(o.ssl=r),t.searchParams.get("application_name")||(o.application_name="sigil"),o}function To(e,t){if(t==="disable")return!1;if(t==="require"||t==="verify-full"||t==="verify-ca")return{rejectUnauthorized:!0};if(t==="no-verify"||t==="prefer")return{rejectUnauthorized:!1};if(!Ut.some(n=>n.test(e)))return Oo.some(n=>n.test(e))?{rejectUnauthorized:!0}:{rejectUnauthorized:!1}}function Gt(e){try{let t=new URL(e).hostname;return/\.neon\.tech$/i.test(t)?"neon":/\.pooler\.supabase\.com$/i.test(t)?"supabase-pooler":/\.supabase\.co$/i.test(t)||/\.supabase\.com$/i.test(t)?"supabase":/\.rds\.amazonaws\.com$/i.test(t)?"aws-rds":/\.render\.com$/i.test(t)?"render":/\.railway\.app$/i.test(t)?"railway":/\.cockroachlabs\.cloud$/i.test(t)?"cockroachdb":Ut.some(n=>n.test(t))?"local":"unknown"}catch{return"unknown"}}var Oo,Ut,Wt=h(()=>{Oo=[/\.neon\.tech$/i,/\.supabase\.co$/i,/\.supabase\.com$/i,/\.pooler\.supabase\.com$/i,/\.rds\.amazonaws\.com$/i,/\.render\.com$/i,/\.railway\.app$/i,/\.cockroachlabs\.cloud$/i],Ut=[/^localhost$/i,/^127\.0\.0\.1$/,/^::1$/,/\.local$/i]});function Kt(e){let t=e.db.url;return t?{kind:"url",provider:Gt(t),connection:Yt(Ht(t))}:{kind:"local",provider:"local",connection:Yt($t(e))}}function Yt(e){return e.password==null&&(e.password=""),e.user==null&&delete e.user,e}var jt=h(()=>{Ft();Wt()});var K={};D(K,{default:()=>d});import Do from"knex";function No(e){return Array.isArray(e)?e.map(Ge):e&&typeof e=="object"?Ge(e):e}function Ro(e,t){return t(Lo(e))}function Ge(e){if(!e||typeof e!="object"||e instanceof Date)return e;if(Array.isArray(e))return e.map(Ge);let t={};for(let[n,r]of Object.entries(e))t[n.replace(/_([a-z])/g,(o,i)=>i.toUpperCase())]=r;return t}function Lo(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}var Vt,qt,d,I=h(()=>{S();jt();Vt=Kt(l),qt=Do({client:"pg",connection:Vt.connection,pool:{min:0,max:10,acquireTimeoutMillis:1e4,createTimeoutMillis:1e4,idleTimeoutMillis:3e4},postProcessResponse:No,wrapIdentifier:Ro});qt.__sigilDriver=Vt;d=qt});var Qt={};D(Qt,{validateConfig:()=>Zt,validateConfigDeep:()=>vo});function Zt(){let e=[];return Co(e),Mo(e),Po(e),e}async function vo(){let e=Zt();if(l.db.type==="postgres"&&!e.some(t=>t.code.startsWith("DB_")))try{await(await Promise.resolve().then(()=>(I(),K))).default.raw("SELECT 1")}catch(t){e.push({level:"fail",code:"DB_UNREACHABLE",message:`Postgres at ${l.db.host}:${l.db.port}/${l.db.database} unreachable: ${t.message.split(`
|
|
9
|
+
`)[0]}`,fix:"Start Postgres (e.g. `docker start sigil-pg` or your equivalent) and verify SIGIL_DB_HOST/PORT/NAME/USER/PASSWORD in ~/.sigil/.env"})}return e}function Co(e){let{provider:t,model:n}=l.embedding;if(t&&n){let r=Object.keys(Jt).find(o=>Jt[o].some(i=>i.test(n)));r&&r!==t&&e.push({level:"fail",code:"EMBEDDING_PROVIDER_MODEL_MISMATCH",message:`EMBEDDING_PROVIDER=${t} but EMBEDDING_MODEL=${n} is a ${r} model.`,fix:xo(t,n,r)})}if(t&&Xt[t]){let r=Xt[t];l.embedding[r]||e.push({level:"fail",code:"EMBEDDING_PROVIDER_MISSING_KEY",message:`EMBEDDING_PROVIDER=${t} but no ${ge(r)} found.`,fix:`Set ${ge(r)} in ~/.sigil/.env, or run 'sigil init' to reconfigure.`})}}function Mo(e){let{provider:t}=l.llm;if(t&&zt[t]){let n=zt[t];l.llm[n]||e.push({level:"fail",code:"LLM_PROVIDER_MISSING_KEY",message:`LLM_PROVIDER=${t} but no ${ge(n)} found.`,fix:`Set ${ge(n)} in ~/.sigil/.env, or run 'sigil init' to reconfigure.`})}t==="openrouter"&&l.llm.openrouterModel&&(l.llm.openrouterModel.includes("/")||e.push({level:"warn",code:"OPENROUTER_MODEL_FORMAT",message:`LLM_OPENROUTER_MODEL=${l.llm.openrouterModel} doesn't look like vendor/model format.`,fix:'Use format like "anthropic/claude-haiku-4-5" or "google/gemini-2.5-flash".'}))}function Po(e){l.db.type==="postgres"&&(!l.db.host||!l.db.database||!l.db.user)&&e.push({level:"fail",code:"DB_CONFIG_INCOMPLETE",message:"SIGIL_DB_TYPE=postgres but host/database/user missing.",fix:"Set SIGIL_DB_HOST, SIGIL_DB_NAME, SIGIL_DB_USER, SIGIL_DB_PASSWORD in ~/.sigil/.env. Run `sigil init` for an interactive setup."})}function ge(e){return{openaiApiKey:"OPENAI_API_KEY",apiKey:"ANTHROPIC_API_KEY",openrouterApiKey:"OPENROUTER_API_KEY",voyageApiKey:"VOYAGE_API_KEY"}[e]||e}function xo(e,t,n){let r={voyage:"voyage-3.5, voyage-3-large, voyage-code-3.5",openai:"text-embedding-3-large, text-embedding-3-small",ollama:"nomic-embed-text, mxbai-embed-large"}[e]||"(see provider docs)";return`Either set EMBEDDING_PROVIDER=${n} (matches your current model), or change EMBEDDING_MODEL to one of: ${r}`}var Jt,zt,Xt,en=h(()=>{S();Jt={voyage:[/^voyage-/],openai:[/^text-embedding-/],ollama:[/^nomic-embed/,/^mxbai-embed/,/^all-minilm/,/^bge-/,/^snowflake-/,/^granite-embedding/]},zt={openai:"openaiApiKey",anthropic:"apiKey",openrouter:"openrouterApiKey"},Xt={openai:"openaiApiKey",voyage:"voyageApiKey",openrouter:"openrouterApiKey"}});function Ye(e,t){let n={};for(let r of e)n[r[t]]=r;return n}function we(e,t){if(t<1)return[];let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}var Se=h(()=>{});var an={};D(an,{chat:()=>Ho,meta:()=>Go,setup:()=>Wo});async function Ho(e,{model:t,jsonMode:n=!1}={}){let r=t||l.llm.openaiModel,o=[{role:"user",content:e}];n&&!e.toLowerCase().includes("json")&&o.unshift({role:"system",content:"Respond with valid JSON."});let i={model:r,messages:o};n&&(i.response_format={type:"json_object"});let s=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",signal:AbortSignal.timeout(l.llm.requestTimeout),headers:{"Content-Type":"application/json",Authorization:`Bearer ${l.llm.openaiApiKey}`},body:JSON.stringify(i)});if(!s.ok){let m=await s.text();throw new Error(`OpenAI error ${s.status}: ${m}`)}let a=await s.json(),c=a.choices[0].message.content.trim(),u=a.usage||{};return{text:c,inputTokens:u.prompt_tokens||0,outputTokens:u.completion_tokens||0,model:r}}async function Wo({existing:e,clack:t}){let n=e.OPENAI_API_KEY||"",r=await t.text({message:"OpenAI API key (paste, then Enter)",placeholder:n?"(keep existing \u2014 press Enter)":"sk-proj-...",validate:o=>{if(!o&&!n)return"API key is required";if(o&&!o.startsWith("sk-"))return'OpenAI keys start with "sk-" \u2014 check paste'}});return t.isCancel(r)?null:{env:{OPENAI_API_KEY:r||n}}}var Go,sn=h(()=>{S();Go={id:"openai",label:"OpenAI",hint:"gpt-4o-mini"}});function M(e){return Math.ceil((e||"").length/4)}function Ke(e,t,n){let r=Yo[e];return r?(t*r.input+n*r.output)/1e6:0}function oe({provider:e,model:t,caller:n,input:r,response:o,inputTokens:i,outputTokens:s,cost:a,durationMs:c,status:u,error:m}){d("llm_log").insert({provider:e,model:t,caller:n,input:r?.slice(0,1e4),response:o?.slice(0,1e4),inputTokens:i,outputTokens:s,cost:a,durationMs:c,status:u,error:m?.slice(0,2e3)}).catch(y=>console.error("[llm-log] Write failed:",y.message))}function Ko(e){if(typeof e?.status=="number")return e.status;let t=/error\s+(\d{3})\b/i.exec(e?.message||"");return t?Number(t[1]):null}function jo(e){let t=Ko(e);return t==null||t===408||t===429?!0:t>=500}async function je(e,t=3){for(let n=1;n<=t;n++)try{return await e()}catch(r){if(n===t||!jo(r))throw r;let o=Math.min(1e3*2**(n-1),1e4);await new Promise(i=>setTimeout(i,o))}}var Yo,ie=h(()=>{I();Yo={"gpt-4o-mini":{input:.15,output:.6},"gpt-4o":{input:2.5,output:10},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4.1-mini":{input:.4,output:1.6},"claude-haiku-4-5-20251001":{input:.8,output:4},"claude-sonnet-4-6":{input:3,output:15},"claude-opus-4-6":{input:15,output:75}}});var cn={};D(cn,{chat:()=>qo,meta:()=>Jo,setup:()=>zo});async function Vo(){if(!Ve){let{default:e}=await import("@anthropic-ai/sdk");Ve=new e({apiKey:l.llm.apiKey})}return Ve}async function qo(e,{model:t,jsonMode:n=!1}={}){let r=t||"claude-haiku-4-5-20251001",o=await Vo(),i=[{role:"user",content:e}],s=n?"Respond with valid JSON only. No explanation or wrapping.":void 0,a=await o.messages.create({model:r,max_tokens:4096,messages:i,...s&&{system:s}});return{text:a.content[0].text.trim(),inputTokens:a.usage?.input_tokens||M(e),outputTokens:a.usage?.output_tokens||M(a.content[0].text),model:r}}async function zo({existing:e,clack:t}){let n=e.ANTHROPIC_API_KEY||"",r=await t.text({message:"Anthropic API key (paste, then Enter)",placeholder:n?"(keep existing \u2014 press Enter)":"sk-ant-...",validate:o=>{if(!o&&!n)return"API key is required";if(o&&!o.startsWith("sk-ant-"))return'Anthropic keys start with "sk-ant-" \u2014 check paste'}});return t.isCancel(r)?null:{env:{ANTHROPIC_API_KEY:r||n}}}var Ve,Jo,ln=h(()=>{S();ie();Ve=null;Jo={id:"anthropic",label:"Anthropic",hint:"Claude Haiku \u2014 requires API key"}});var dn={};D(dn,{chat:()=>Zo,meta:()=>Qo,setup:()=>ei});async function Zo(e,{model:t,jsonMode:n=!1}={}){let r=t||l.llm.openrouterModel;if(!l.llm.openrouterApiKey)throw new Error("OPENROUTER_API_KEY is not set");if(!r)throw new Error("No OpenRouter model resolved. Set LLM_OPENROUTER_MODEL or pass `model`.");let o=[{role:"user",content:e}];n&&!e.toLowerCase().includes("json")&&o.unshift({role:"system",content:"Respond with valid JSON."});let i={model:r,messages:o};n&&(i.response_format={type:"json_object"});let s=(l.llm.openrouterBaseUrl||Xo).replace(/\/+$/,""),a={"Content-Type":"application/json",Authorization:`Bearer ${l.llm.openrouterApiKey}`};l.llm.openrouterReferer&&(a["HTTP-Referer"]=l.llm.openrouterReferer),l.llm.openrouterTitle&&(a["X-Title"]=l.llm.openrouterTitle);let c=await fetch(`${s}/chat/completions`,{method:"POST",signal:AbortSignal.timeout(l.llm.requestTimeout),headers:a,body:JSON.stringify(i)});if(!c.ok){let p=await c.text();throw new Error(`OpenRouter error ${c.status}: ${p}`)}let u=await c.json(),y=(u.choices?.[0]?.message?.content||"").trim(),f=u.usage||{};return{text:y,inputTokens:f.prompt_tokens||0,outputTokens:f.completion_tokens||0,model:u.model||r}}async function ei({existing:e,clack:t}){let n={},r=e.OPENROUTER_API_KEY||"",o=await t.text({message:"OpenRouter API key (paste, then Enter)",placeholder:r?"(keep existing \u2014 press Enter)":"sk-or-v1-...",validate:c=>{if(!c&&!r)return"API key is required";if(c&&!c.startsWith("sk-or-"))return'OpenRouter keys start with "sk-or-" \u2014 check paste'}});if(t.isCancel(o))return null;n.OPENROUTER_API_KEY=o||r;let i=e.LLM_OPENROUTER_MODEL||"",s=await t.text({message:"OpenRouter model (vendor/model)",placeholder:i||un,validate:c=>{if(c&&!c.includes("/"))return'OpenRouter models are "vendor/model" \u2014 e.g. google/gemini-flash-latest'}});if(t.isCancel(s))return null;n.LLM_OPENROUTER_MODEL=s||i||un;let a=await t.select({message:"Configure per-task model overrides? (advanced \u2014 better quality / cost)",options:[{value:"no",label:"No, use one model everywhere",hint:"simpler \u2014 debug one model"},{value:"yes",label:"Yes, configure smart split",hint:"~5\xD7 cheaper extraction + better AUDM/synthesis"}],initialValue:"no"});if(t.isCancel(a))return null;if(a==="yes"){let c=await t.text({message:"Extraction model (high-volume; cheap matters)",placeholder:e.LLM_EXTRACTION_MODEL||j.extraction});if(t.isCancel(c))return null;n.LLM_EXTRACTION_MODEL=c||e.LLM_EXTRACTION_MODEL||j.extraction;let u=await t.text({message:"Decision model (AUDM; smart matters)",placeholder:e.LLM_DECISION_MODEL||j.decision});if(t.isCancel(u))return null;n.LLM_DECISION_MODEL=u||e.LLM_DECISION_MODEL||j.decision;let m=await t.text({message:"Synthesis model (read-time answer composition)",placeholder:e.SIGIL_SYNTH_MODEL||j.synthesis});if(t.isCancel(m))return null;n.SIGIL_SYNTH_MODEL=m||e.SIGIL_SYNTH_MODEL||j.synthesis}return t.note(`OpenRouter can drive both LLM calls and embeddings.
|
|
10
10
|
You will pick an embedding provider in the next step \u2014 "openrouter" is an option,
|
|
11
|
-
or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"OpenRouter scope"),{env:n}}var
|
|
12
|
-
`).pop().trim();return r&&
|
|
11
|
+
or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"OpenRouter scope"),{env:n}}var Xo,Qo,un,j,pn=h(()=>{S();Xo="https://openrouter.ai/api/v1";Qo={id:"openrouter",label:"OpenRouter",hint:"one key, many models (Anthropic / OpenAI / Meta / ...)"},un="google/gemini-flash-latest",j={extraction:"openrouter:qwen/qwen3.5-flash",decision:"openrouter:anthropic/claude-sonnet-latest",synthesis:"openrouter:anthropic/claude-sonnet-latest"}});var fn={};D(fn,{chat:()=>li,meta:()=>ui,setup:()=>di});import{spawn as ti,spawnSync as ni}from"node:child_process";import{existsSync as mn}from"node:fs";import{homedir as ri}from"node:os";import{dirname as oi,join as qe}from"node:path";function ii(){if(V)return V;if(l.llm.cliPath)return V=l.llm.cliPath;let e=ri(),t=[qe(oi(process.execPath),"claude"),qe(e,".local","bin","claude"),qe(e,".claude","local","claude"),"/opt/homebrew/bin/claude","/usr/local/bin/claude","/usr/bin/claude"];for(let r of t)if(mn(r))return V=r;let n=ai("claude");return n?V=n:V="claude"}function ai(e){let t=process.env.SHELL||"/bin/sh";try{let r=(ni(t,["-lic",`command -v ${e}`],{encoding:"utf8",timeout:5e3}).stdout||"").trim().split(`
|
|
12
|
+
`).pop().trim();return r&&mn(r)?r:null}catch{return null}}function ci(e,t){let n=l.llm.cliTimeout||12e4,r=ii();return new Promise((o,i)=>{let s=ti(r,e,{stdio:["pipe","pipe","pipe"]}),a=setTimeout(()=>{s.kill("SIGTERM"),i(new Error(`claude CLI timed out after ${n}ms`))},n),c="",u="";s.stdout.on("data",m=>{c+=m}),s.stderr.on("data",m=>{u+=m}),s.on("error",m=>{if(clearTimeout(a),m.code==="ENOENT"){i(new Error(`Failed to spawn claude CLI: '${r}' not found. The Sigil daemon runs with a minimal PATH and can't see your \`claude\` install. Set LLM_CLI_PATH to its absolute path (find it with \`which claude\`) and restart the daemon \u2014 or pick an API-key provider (openrouter/openai/anthropic).`));return}i(new Error(`Failed to spawn claude CLI: ${m.message}`))}),s.on("close",m=>{clearTimeout(a),o({stdout:c,stderr:u,code:m})}),s.stdin.write(t),s.stdin.end()})}async function li(e,{model:t,jsonMode:n=!1}={}){let r=t||l.llm.cliModel||"haiku",o=si[r]||r,i=["-p","--model",o,"--output-format","json"],{stdout:s,stderr:a,code:c}=await ci(i,e);if(c!==0)throw new Error(`claude CLI exited ${c}: ${(a||s).slice(0,500)}`);let u;try{u=JSON.parse(s)}catch{return{text:s.trim(),inputTokens:M(e),outputTokens:M(s),model:o}}if(u.is_error)throw new Error(`claude CLI error: ${u.result||"unknown error"}`);let m=(u.result||"").trim(),y=u.usage||{};return{text:m,inputTokens:y.input_tokens||M(e),outputTokens:y.output_tokens||M(m),model:o,cost:u.total_cost_usd||0}}async function di(){return{env:{}}}var V,si,ui,hn=h(()=>{S();ie();V=null;si={"claude-haiku-4-5-20251001":"haiku","claude-sonnet-4-6":"sonnet","claude-opus-4-6":"opus"};ui={id:"claude-cli",label:"Claude Code",hint:"uses your existing subscription \u2014 no extra API key"}});var _n={};D(_n,{chat:()=>pi,meta:()=>mi,setup:()=>fi});async function pi(e,{model:t,jsonMode:n=!1}={}){let r=t||l.llm.ollamaModel,o=`${l.llm.ollamaHost}/api/chat`,i={model:r,messages:[{role:"user",content:e}],stream:!1};n&&(i.format="json");let s=await fetch(o,{method:"POST",signal:AbortSignal.timeout(l.llm.cliTimeout),headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!s.ok){let c=await s.text();throw new Error(`Ollama error ${s.status}: ${c}`)}let a=await s.json();return{text:a.message.content.trim(),inputTokens:a.prompt_eval_count||M(e),outputTokens:a.eval_count||M(a.message.content),model:r}}async function fi({existing:e,clack:t}){let n=e.OLLAMA_HOST||"http://localhost:11434",r=await t.text({message:"Ollama host",placeholder:n,initialValue:n,validate:o=>{if(o&&!/^https?:\/\//.test(o))return"Must start with http:// or https://"}});return t.isCancel(r)?null:{env:{OLLAMA_HOST:r||n}}}var mi,En=h(()=>{S();ie();mi={id:"ollama",label:"Ollama",hint:"local models \u2014 no API cost"}});var yn={};D(yn,{embedBatch:()=>_i});async function _i(e,{model:t,ollamaHost:n}){let r=we(e,hi),o=[];for(let i of r){let s=await fetch(`${n}/api/embed`,{method:"POST",signal:AbortSignal.timeout(l.llm.cliTimeout),headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t,input:i})});if(!s.ok)throw new Error(`Ollama embed failed: ${s.status} ${await s.text()}`);let a=await s.json();o.push(...a.embeddings)}return o}var hi,gn=h(()=>{Se();S();hi=50});var wn={};D(wn,{embedBatch:()=>Ei});async function Ei(e,{model:t,openaiApiKey:n,dimensions:r}={}){let o={model:t,input:e};r&&/^text-embedding-3/.test(t)&&(o.dimensions=r);let i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",signal:AbortSignal.timeout(l.llm.requestTimeout),headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(o)});if(!i.ok)throw new Error(`OpenAI embed failed: ${i.status} ${await i.text()}`);return(await i.json()).data.map(a=>a.embedding)}var Sn=h(()=>{S()});var An={};D(An,{embedBatch:()=>gi});async function gi(e,{model:t,voyageApiKey:n,inputType:r="document",dimensions:o}={}){if(!n)throw new Error("VOYAGE_API_KEY is not set. Get one at dashboard.voyageai.com.");let i=we(e,yi),s=[];for(let a of i){let c={input:a,model:t||"voyage-3-large",input_type:r==="query"?"query":"document"};o&&(c.output_dimension=o);let u=await fetch("https://api.voyageai.com/v1/embeddings",{method:"POST",signal:AbortSignal.timeout(l.llm.requestTimeout),headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(c)});if(!u.ok){let f=await u.text();throw new Error(`Voyage embed failed: ${u.status} ${f}`)}let y=[...(await u.json()).data].sort((f,p)=>f.index-p.index);s.push(...y.map(f=>f.embedding))}return s}var yi,In=h(()=>{Se();S();yi=50});var bn={};D(bn,{embedBatch:()=>Si});async function Si(e,{model:t,openrouterApiKey:n,openrouterBaseUrl:r,openrouterReferer:o,openrouterTitle:i,dimensions:s}={}){if(!n)throw new Error("OPENROUTER_API_KEY is not set");if(!t)throw new Error('No OpenRouter embedding model resolved. Set EMBEDDING_MODEL (e.g. "openai/text-embedding-3-large").');let a={model:t,input:e};s&&/(^|\/)text-embedding-3/.test(t)&&(a.dimensions=s);let c=(r||wi).replace(/\/+$/,""),u={"Content-Type":"application/json",Authorization:`Bearer ${n}`};o&&(u["HTTP-Referer"]=o),i&&(u["X-Title"]=i);let m=await fetch(`${c}/embeddings`,{method:"POST",signal:AbortSignal.timeout(l.llm.requestTimeout),headers:u,body:JSON.stringify(a)});if(!m.ok)throw new Error(`OpenRouter embed failed: ${m.status} ${await m.text()}`);return[...(await m.json()).data].sort((p,w)=>p.index-w.index).map(p=>p.embedding)}var wi,On=h(()=>{S();wi="https://openrouter.ai/api/v1"});import{spawn as Ai}from"node:child_process";async function Ze(e){if(!Je[e]){let t=Xe[e];if(!t)throw new Error(`Unknown LLM provider: "${e}". Available: ${Object.keys(Xe).join(", ")}`);let n=await t();Je[e]=n.chat}return Je[e]}async function Dn(e){if(!ze[e]){let t=Tn[e];if(!t)throw new Error(`Unknown embedding provider: "${e}". Available: ${Object.keys(Tn).join(", ")}`);let n=await t();ze[e]=n.embedBatch}return ze[e]}function Nn(e,t){if(!e)return{provider:t,model:null};let n=e.indexOf(":");return n>0&&Xe[e.slice(0,n)]?{provider:e.slice(0,n),model:e.slice(n+1)}:{provider:t,model:e}}async function Rn(){let e=l.llm.ollamaHost||l.embedding.ollamaHost||"http://localhost:11434";try{return(await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}function Ii(){return new Promise(e=>{let t=Ai("claude",["--version"],{stdio:"pipe"});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0)),setTimeout(()=>{t.kill(),e(!1)},3e3)})}async function Ln(){if(L)return L;if(l.llm.provider)return L=l.llm.provider,L;if(l.llm.openrouterApiKey)return L="openrouter",L;if(l.llm.apiKey)return L="anthropic",L;if(l.llm.openaiApiKey)return L="openai",L;if(await Rn())return L="ollama",L;if(await Ii())return L="claude-cli",L;throw new Error(`No LLM provider available. Either:
|
|
13
13
|
- Set LLM_PROVIDER (openai, anthropic, openrouter, ollama, claude-cli)
|
|
14
14
|
- Set ANTHROPIC_API_KEY, OPENAI_API_KEY, or OPENROUTER_API_KEY
|
|
15
15
|
- Start Ollama locally
|
|
16
|
-
- Install the Claude CLI (claude)`)}async function
|
|
16
|
+
- Install the Claude CLI (claude)`)}async function vn(){if(C)return C;if(l.embedding.provider)return C=l.embedding.provider,C;if(l.embedding.voyageApiKey)return C="voyage",C;if(await Rn())return C="ollama",C;if(l.embedding.openaiApiKey)return C="openai",C;if(l.embedding.openrouterApiKey)return C="openrouter",C;throw new Error(`No embedding provider available. Either:
|
|
17
17
|
- Set EMBEDDING_PROVIDER (voyage, ollama, openai, openrouter)
|
|
18
18
|
- Set VOYAGE_API_KEY (recommended \u2014 best quality)
|
|
19
19
|
- Start Ollama locally
|
|
20
20
|
- Set OPENAI_API_KEY
|
|
21
|
-
- Set OPENROUTER_API_KEY (and EMBEDDING_MODEL like "openai/text-embedding-3-large")`)}var
|
|
21
|
+
- Set OPENROUTER_API_KEY (and EMBEDDING_MODEL like "openai/text-embedding-3-large")`)}var Xe,Tn,Je,ze,L,C,Qe=h(()=>{S();Xe={openai:()=>Promise.resolve().then(()=>(sn(),an)),anthropic:()=>Promise.resolve().then(()=>(ln(),cn)),openrouter:()=>Promise.resolve().then(()=>(pn(),dn)),"claude-cli":()=>Promise.resolve().then(()=>(hn(),fn)),ollama:()=>Promise.resolve().then(()=>(En(),_n))},Tn={ollama:()=>Promise.resolve().then(()=>(gn(),yn)),openai:()=>Promise.resolve().then(()=>(Sn(),wn)),voyage:()=>Promise.resolve().then(()=>(In(),An)),openrouter:()=>Promise.resolve().then(()=>(On(),bn))},Je={},ze={};L=null,C=null});function $(e){return e?`[${e.join(",")}]`:null}function Cn(){let e=Number(l.embedding.dimensions)||768;if(!Number.isInteger(e)||e<=0)throw new Error(`Invalid EMBEDDING_DIMENSIONS: ${l.embedding.dimensions}`);return e}function q(e="embedding"){return`(${e}::halfvec(${Cn()}))`}function J(){return`?::halfvec(${Cn()})`}var z=h(()=>{S()});import{createHash as bi}from"node:crypto";function Ti(e,t,n,r="document"){let o=bi("sha256");return o.update(e),o.update("\0"),o.update(t),o.update("\0"),o.update(r),o.update("\0"),o.update(n),o.digest("hex")}async function Di(e){if(!e.length)return new Map;let t=await d("embedding_cache").whereIn("key",e).select("key","embedding");return new Map(t.map(n=>[n.key,Ni(n.embedding)]))}function Ni(e){return Array.isArray(e)||typeof e!="string"?e:(e.startsWith("[")?e.slice(1,-1):e).split(",").map(Number)}async function Ri(e){e.length&&await d("embedding_cache").whereIn("key",e).update({hits:d.raw("hits + 1"),lastUsedAt:d.fn.now()})}async function Li(e,t,n){if(e.length){for(let r=0;r<e.length;r+=Pn){let o=e.slice(r,r+Pn),i=o.map(()=>"(?, ?, ?, ?, 0, NOW(), NOW())").join(", "),s=[];for(let{key:a,embedding:c}of o)s.push(a,t,n,$(c));await d.raw(`
|
|
22
22
|
INSERT INTO embedding_cache (key, provider, model, embedding, hits, created_at, last_used_at)
|
|
23
|
-
VALUES
|
|
23
|
+
VALUES ${i}
|
|
24
24
|
ON CONFLICT (key) DO UPDATE
|
|
25
25
|
SET last_used_at = NOW(),
|
|
26
26
|
hits = embedding_cache.hits + 1
|
|
27
|
-
`,
|
|
27
|
+
`,s)}await Ci()}}async function Ci(){let e=Date.now();if(e-xn<vi)return;xn=e;let[{count:t}]=await d("embedding_cache").count("key as count"),n=Number(t);if(n<=Mn)return;let r=Math.min(n-Mn,Oi);await d.raw(`
|
|
28
28
|
DELETE FROM embedding_cache WHERE key IN (
|
|
29
29
|
SELECT key FROM embedding_cache ORDER BY last_used_at ASC LIMIT ?
|
|
30
30
|
)
|
|
31
|
-
`,[r])}async function
|
|
32
|
-
`)})}let f=a.filter(p=>c.has(p));return f.length&&
|
|
31
|
+
`,[r])}async function kn(e,t,n,r,o,i={}){if(!e.length)return[];let s=i.inputType||o?.inputType||"document",a=e.map(p=>Ti(t,n,p,s)),c=await Di(a),u=[],m=[],y=new Array(e.length);for(let p=0;p<e.length;p++){let w=c.get(a[p]);w?y[p]=w:(u.push(e[p]),m.push(p))}if(u.length){let p=await r(u,o),w=[];for(let _=0;_<u.length;_++){let b=m[_];y[b]=p[_],w.push({key:a[b],embedding:p[_]})}Li(w,t,n).catch(_=>{process.stderr.write(`[embedding-cache] store failed: ${_.message}
|
|
32
|
+
`)})}let f=a.filter(p=>c.has(p));return f.length&&Ri(f).catch(()=>{}),y}var Mn,Oi,Pn,xn,vi,Bn=h(()=>{z();I();Mn=1e4,Oi=500;Pn=500;xn=0,vi=6e4});async function et(e,t={}){let[n]=await Ae([e],t);return n}async function Ae(e,{inputType:t="document",cache:n=!0}={}){if(!e.length)return[];let r=await vn(),o=await Dn(r),i=l.embedding.model,s={...l.embedding,inputType:t};return n?kn(e,r,i,o,s,{inputType:t}):o(e,s)}var Jc,tt=h(()=>{S();Qe();Bn();({dimensions:Jc}=l.embedding)});var $n,Fn=h(()=>{$n="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"});import{webcrypto as Un}from"node:crypto";function Pi(e){if(e<0||e>1024)throw new RangeError("Wrong ID size");!H||H.length<e?(H=Buffer.allocUnsafe(e*Mi),Un.getRandomValues(H),X=0):X+e>H.length&&(Un.getRandomValues(H),X=0),X+=e}function Ie(e=21){Pi(e|=0);let t="";for(let n=X-e;n<X;n++)t+=$n[H[n]&63];return t}var Mi,H,X,nt=h(()=>{Fn();Mi=128});async function Hn(e,t){let n=t||l.defaults.namespace,r=e.toLowerCase();return d("entity").where({namespace:n}).whereNull("mergedWith").where(function(){this.whereRaw("LOWER(name) = ?",[r]).orWhereRaw("aliases @> ARRAY[?]::text[]",[r])}).first()||null}async function Gn(e,{entityType:t,namespace:n,limit:r=10}={}){let o=d("entity").whereRaw("LOWER(name) LIKE ?",[`%${e.toLowerCase()}%`]).whereNull("mergedWith").orderBy("mentionCount","desc").limit(r);return t&&o.where({entityType:t}),n&&o.where({namespace:n}),o}var Wn=h(()=>{I();z();S()});async function be({podType:e,externalId:t,name:n,namespace:r,attrs:o={},entityId:i=null,connectionId:s=null,startedAt:a=null}){if(!t)throw new Error("upsertPod requires externalId; use insertPod for custom pods");let c=`pod-${Ie(16)}`,u=r||l.defaults.namespace,{rows:[m]}=await d.raw(`
|
|
33
33
|
INSERT INTO pod (uid, pod_type, name, namespace, attrs, entity_id, connection_id, external_id, started_at, created_at, updated_at)
|
|
34
34
|
VALUES (?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, NOW(), NOW())
|
|
35
35
|
ON CONFLICT (pod_type, external_id, namespace) WHERE external_id IS NOT NULL DO UPDATE SET
|
|
36
36
|
attrs = pod.attrs || EXCLUDED.attrs,
|
|
37
37
|
updated_at = NOW()
|
|
38
38
|
RETURNING *, (xmax = 0) AS "isNew"
|
|
39
|
-
`,[c,e,n,u,JSON.stringify(o),i,s,t,a]);return{pod:m,isNew:m.isNew}}async function
|
|
39
|
+
`,[c,e,n,u,JSON.stringify(o),i,s,t,a]);return{pod:m,isNew:m.isNew}}async function rt(e){return d("pod").where({uid:e}).first()||null}async function Yn({podType:e,externalId:t,namespace:n}){return d("pod").where({podType:e,externalId:t,namespace:n||l.defaults.namespace}).first()||null}async function ot(e,t){await d.raw("UPDATE pod SET attrs = attrs || ?::jsonb, updated_at = NOW() WHERE id = ?",[JSON.stringify(t),e])}async function Kn(e,t=new Date){await d("pod").where({id:e}).update({endedAt:t,updatedAt:d.fn.now()})}async function ae(e,{docs:t=0,facts:n=0}){!t&&!n||await d.raw(`UPDATE pod
|
|
40
40
|
SET member_doc_count = member_doc_count + ?,
|
|
41
41
|
member_fact_count = member_fact_count + ?,
|
|
42
42
|
updated_at = NOW()
|
|
43
|
-
WHERE id = ?`,[t,n,e])}var
|
|
43
|
+
WHERE id = ?`,[t,n,e])}var Oe=h(()=>{nt();I();S()});var De={};D(De,{attach:()=>Te,attachDocument:()=>xi,attachEntity:()=>ki,attachFact:()=>Vn,detach:()=>Bi,factIdsInPod:()=>Ui,listMembers:()=>$i,listPodsForMember:()=>Fi});async function Te(e,t,n,r="primary"){let{rowCount:o}=await d.raw(`INSERT INTO pod_membership (pod_id, member_type, member_id, role)
|
|
44
44
|
VALUES (?, ?, ?, ?)
|
|
45
|
-
ON CONFLICT (pod_id, member_type, member_id) DO NOTHING`,[e,t,n,r]);return o>0&&(t==="fact"?await
|
|
45
|
+
ON CONFLICT (pod_id, member_type, member_id) DO NOTHING`,[e,t,n,r]);return o>0&&(t==="fact"?await ae(e,{facts:1}):t==="document"&&await ae(e,{docs:1})),{attached:o>0}}async function Bi(e,t,n){let r=await d("pod_membership").where({podId:e,memberType:t,memberId:n}).del();return r>0&&(t==="fact"?await ae(e,{facts:-1}):t==="document"&&await ae(e,{docs:-1})),{detached:r>0}}async function $i(e,{memberType:t,limit:n=20}={}){if(!t)throw new Error("listMembers requires a memberType filter");return d(`${t} as t`).join("pod_membership as pm",function(){this.on("pm.member_id","=","t.id").andOnVal("pm.member_type","=",t)}).where("pm.pod_id",e).orderBy("pm.createdAt","desc").limit(n).select("t.*","pm.role as podRole","pm.createdAt as attachedAt")}async function Fi(e,t){return d("pod as p").join("pod_membership as pm","pm.pod_id","p.id").where("pm.memberType",e).where("pm.memberId",t).select("p.*","pm.role as podRole")}async function Ui(e){return await d("pod_membership").where({podId:e,memberType:"fact"}).pluck("memberId")}var Vn,xi,ki,it=h(()=>{I();Oe();Vn=(e,t,n)=>Te(e,"fact",t,n),xi=(e,t,n)=>Te(e,"document",t,n),ki=(e,t,n)=>Te(e,"entity",t,n)});async function qn(e,{limit:t=50}={}){return d("fact").join("fact_entity","fact.id","fact_entity.fact_id").where("fact_entity.entity_id",e).where("fact.status","active").select("fact.*","fact_entity.mention_count as entityMentionCount").orderBy("fact_entity.mention_count","desc").limit(t)}async function se(e){if(!e.length)return new Map;let t=await d("fact_entity").whereIn("factId",e).select("factId","entityId"),n=new Map;for(let r of t)n.has(r.factId)||n.set(r.factId,[]),n.get(r.factId).push(r.entityId);return n}var Ne=h(()=>{I();it()});async function Jn(e){let t=await Ln();return Nn(e,t)}async function at(e,{model:t,caller:n}={}){let{provider:r,model:o}=await Jn(t),i=await Ze(r),s=Date.now();try{let a=await je(()=>i(e,{model:o,jsonMode:!1}),l.llm.maxRetries),c=a.cost||Ke(a.model,a.inputTokens,a.outputTokens);return oe({provider:r,model:a.model,caller:n,input:e,response:a.text,inputTokens:a.inputTokens,outputTokens:a.outputTokens,cost:c,durationMs:Date.now()-s,status:"success"}),a.text}catch(a){throw oe({provider:r,model:o,caller:n,input:e,response:null,inputTokens:0,outputTokens:0,cost:0,durationMs:Date.now()-s,status:"error",error:a.message}),a}}async function Re(e,{model:t,caller:n}={}){let{provider:r,model:o}=await Jn(t),i=await Ze(r),s=Date.now();try{let a=await je(()=>i(e,{model:o,jsonMode:!0}),l.llm.maxRetries),c=a.cost||Ke(a.model,a.inputTokens,a.outputTokens);return oe({provider:r,model:a.model,caller:n,input:e,response:a.text,inputTokens:a.inputTokens,outputTokens:a.outputTokens,cost:c,durationMs:Date.now()-s,status:"success"}),Hi(a.text)}catch(a){throw oe({provider:r,model:o,caller:n,input:e,response:null,inputTokens:0,outputTokens:0,cost:0,durationMs:Date.now()-s,status:"error",error:a.message}),a}}function Hi(e){try{return JSON.parse(e.trim())}catch{}let t=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(t)try{return JSON.parse(t[1].trim())}catch{}let n=e.match(/[\[{][\s\S]*[\]}]/);if(n)try{return JSON.parse(n[0])}catch{}return null}var ce=h(()=>{S();Qe();ie()});import Gi from"node:path";async function zn(e){e.length&&await d.raw(`UPDATE fact_lifecycle
|
|
46
46
|
SET access_count = access_count + 1,
|
|
47
47
|
last_accessed_at = NOW(),
|
|
48
48
|
stage = CASE WHEN stage = 'stable' THEN 'editing' ELSE stage END,
|
|
49
49
|
stage_entered_at = CASE WHEN stage = 'stable' THEN NOW() ELSE stage_entered_at END
|
|
50
|
-
WHERE fact_id = ANY(?)`,[e])}var
|
|
50
|
+
WHERE fact_id = ANY(?)`,[e])}var bl,Ol,Tl,Xn=h(()=>{I();tt();ce();z();me();S();B();bl=Gi.join(he,"audm-decision.md"),Ol=l.memory.skipThreshold,Tl=l.memory.ambiguousThreshold});async function Zn(e){if(!e||e.length<2)return;let t=[...new Set(e.filter(i=>Number.isInteger(i)))].sort((i,s)=>i-s);if(t.length<2)return;let n=[];for(let i=0;i<t.length;i++)for(let s=i+1;s<t.length;s++)n.push([t[i],t[s]]);let r=n.map(()=>"(?, ?, 1, NOW(), NOW())").join(", "),o=n.flat();await d.raw(`
|
|
51
51
|
INSERT INTO hebbian_edge (fact_a_id, fact_b_id, strength, first_seen_at, last_seen_at)
|
|
52
52
|
VALUES ${r}
|
|
53
53
|
ON CONFLICT (fact_a_id, fact_b_id)
|
|
54
54
|
DO UPDATE SET
|
|
55
55
|
strength = hebbian_edge.strength + 1,
|
|
56
56
|
last_seen_at = NOW()
|
|
57
|
-
`,o)}var
|
|
57
|
+
`,o)}var Qn=h(()=>{I()});var er={};D(er,{consolidateEntityCoRetrievalEdges:()=>Ki,getCoRetrievedEntities:()=>Yi,getEdgeStrengthsForRanking:()=>ct,getEntityHebbianStats:()=>ji,strengthenEntityEdges:()=>st});function Le(e){return Wi/Math.max(e,1)}async function st(e,t={}){if(!l.hebbian.entity.enabled||!e||e.length<2)return;let n=t.eta??l.hebbian.entity.eta,r=t.cap??l.hebbian.entity.cap,o=[...new Set(e.filter(c=>Number.isInteger(c)))].sort((c,u)=>c-u);if(o.length<2)return;let i=[];for(let c=0;c<o.length;c++)for(let u=c+1;u<o.length;u++)i.push([o[c],o[u]]);let s=i.map(()=>"(?, ?, ?, NOW(), NOW())").join(", "),a=i.flatMap(([c,u])=>[c,u,n]);await d.raw(`
|
|
58
58
|
INSERT INTO entity_hebbian_edge (entity_a_id, entity_b_id, strength, first_seen_at, last_seen_at)
|
|
59
59
|
VALUES ${s}
|
|
60
60
|
ON CONFLICT (entity_a_id, entity_b_id)
|
|
61
61
|
DO UPDATE SET
|
|
62
62
|
strength = LEAST(entity_hebbian_edge.strength + ?, ?),
|
|
63
63
|
last_seen_at = NOW()
|
|
64
|
-
`,[...a,n,r])}async function
|
|
64
|
+
`,[...a,n,r])}async function Yi(e,t={}){if(!l.hebbian.entity.enabled)return[];let n=t.limit??10,r=t.minEffectiveStrength??l.hebbian.entity.minEffective,o=Le(t.halfLifeDays??l.hebbian.entity.halfLifeDays),{rows:i}=await d.raw(`
|
|
65
65
|
SELECT
|
|
66
66
|
CASE WHEN entity_a_id = ? THEN entity_b_id ELSE entity_a_id END AS "partnerId",
|
|
67
67
|
(strength * EXP(-1.0 * ?::float8 * EXTRACT(EPOCH FROM (NOW() - last_seen_at)) / 86400.0))::float8 AS "effectiveStrength",
|
|
@@ -71,7 +71,7 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
71
71
|
WHERE entity_a_id = ? OR entity_b_id = ?
|
|
72
72
|
ORDER BY "effectiveStrength" DESC
|
|
73
73
|
LIMIT ?
|
|
74
|
-
`,[e,o,e,e,n*3]);return i.filter(s=>s.effectiveStrength>=r).slice(0,n)}async function
|
|
74
|
+
`,[e,o,e,e,n*3]);return i.filter(s=>s.effectiveStrength>=r).slice(0,n)}async function ct(e,t,n={}){if(!l.hebbian.entity.enabled)return new Map;if(!e.length||!t.length)return new Map;let r=Le(n.halfLifeDays??l.hebbian.entity.halfLifeDays),o=[...new Set(e)],i=[...new Set(t)].filter(c=>!o.includes(c));if(!i.length)return new Map;let{rows:s}=await d.raw(`
|
|
75
75
|
SELECT
|
|
76
76
|
CASE
|
|
77
77
|
WHEN entity_a_id = ANY(?::bigint[]) THEN entity_b_id
|
|
@@ -84,12 +84,12 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
84
84
|
OR
|
|
85
85
|
(entity_b_id = ANY(?::bigint[]) AND entity_a_id = ANY(?::bigint[]))
|
|
86
86
|
GROUP BY "candidateId"
|
|
87
|
-
`,[o,r,o,i,o,i]),a=new Map;for(let c of s)a.set(Number(c.candidateId),c.summedStrength);return a}async function
|
|
87
|
+
`,[o,r,o,i,o,i]),a=new Map;for(let c of s)a.set(Number(c.candidateId),c.summedStrength);return a}async function Ki({floor:e=.5,decayDays:t=90}={}){let n=Le(l.hebbian.entity.halfLifeDays),{rows:r}=await d.raw(`
|
|
88
88
|
DELETE FROM entity_hebbian_edge
|
|
89
89
|
WHERE (strength * EXP(-1.0 * ?::float8 * EXTRACT(EPOCH FROM (NOW() - last_seen_at)) / 86400.0)) <= ?
|
|
90
90
|
AND last_seen_at < NOW() - (INTERVAL '1 day' * ?)
|
|
91
91
|
RETURNING entity_a_id
|
|
92
|
-
`,[n,e,t]);return r.length}async function
|
|
92
|
+
`,[n,e,t]);return r.length}async function ji({topN:e=5}={}){let t=Le(l.hebbian.entity.halfLifeDays),n=await d.raw(`
|
|
93
93
|
SELECT
|
|
94
94
|
COUNT(*)::int AS "edgeCount",
|
|
95
95
|
COALESCE(AVG(strength)::float8, 0) AS "avgStrength",
|
|
@@ -106,7 +106,7 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
106
106
|
JOIN entity eb ON eb.id = entity_b_id
|
|
107
107
|
ORDER BY "decayed" DESC
|
|
108
108
|
LIMIT ?
|
|
109
|
-
`,[t,e]);return{edgeCount:n.rows[0]?.edgeCount??0,avgStrength:n.rows[0]?.avgStrength??0,maxStrength:n.rows[0]?.maxStrength??0,topPairs:r.rows??[]}}var
|
|
109
|
+
`,[t,e]);return{edgeCount:n.rows[0]?.edgeCount??0,avgStrength:n.rows[0]?.avgStrength??0,maxStrength:n.rows[0]?.maxStrength??0,topPairs:r.rows??[]}}var Wi,lt=h(()=>{I();S();Wi=Math.log(2)});async function tr(e,{direction:t="both",relationType:n,limit:r=50}={}){let o=a=>{let c=a==="outgoing"?"source_id":"target_id",u=a==="outgoing"?"target_id":"source_id";return d.raw(`
|
|
110
110
|
SELECT r.id AS "relationId", r.relation_type AS "relationType",
|
|
111
111
|
r.mention_count AS "mentionCount", r.valid_at AS "validAt",
|
|
112
112
|
e.id AS "entityId", e.uid, e.name, e.entity_type AS "entityType",
|
|
@@ -119,11 +119,11 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
119
119
|
${n?"AND r.relation_type = ?":""}
|
|
120
120
|
ORDER BY r.mention_count DESC
|
|
121
121
|
LIMIT ?
|
|
122
|
-
`,n?[e,n,r]:[e,r])};if(t==="outgoing"){let{rows:a}=await o("outgoing");return a}if(t==="incoming"){let{rows:a}=await o("incoming");return a}let[i,s]=await Promise.all([o("outgoing"),o("incoming")]);return[...i.rows,...s.rows]}var
|
|
122
|
+
`,n?[e,n,r]:[e,r])};if(t==="outgoing"){let{rows:a}=await o("outgoing");return a}if(t==="incoming"){let{rows:a}=await o("incoming");return a}let[i,s]=await Promise.all([o("outgoing"),o("incoming")]);return[...i.rows,...s.rows]}var nr=h(()=>{I()});function ve({minConfidence:e="medium",pointInTime:t,categories:n}){let r=Vi[e]??1,o=[r],i="",s="";return t&&(i="AND valid_from <= ? AND (valid_until IS NULL OR valid_until > ?)",o.push(t,t)),n?.length&&(s="AND category = ANY(?)",o.push(n)),{minRank:r,temporalClause:i,categoryClause:s,filterParams:o}}var Vi,le,Ce=h(()=>{Vi={low:0,medium:1,high:2},le=`CASE confidence
|
|
123
123
|
WHEN 'high' THEN 2
|
|
124
124
|
WHEN 'medium' THEN 1
|
|
125
125
|
ELSE 0
|
|
126
|
-
END`});async function
|
|
126
|
+
END`});async function rr(e,{namespaces:t,limit:n=20}){let r=$(e),o=`${q("embedding")} <=> ${J()}`,{rows:i}=await d.raw(`
|
|
127
127
|
SELECT id, document_id AS "documentId", chunk_index AS "chunkIndex",
|
|
128
128
|
content, section_heading AS "sectionHeading", namespace,
|
|
129
129
|
1 - (${o}) as similarity
|
|
@@ -132,7 +132,7 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
132
132
|
AND embedding IS NOT NULL
|
|
133
133
|
ORDER BY ${o}
|
|
134
134
|
LIMIT ?
|
|
135
|
-
`,[r,t,r,n]);return i}var
|
|
135
|
+
`,[r,t,r,n]);return i}var or=h(()=>{I();z();S();Ce()});async function ir(e,{namespaces:t,limit:n=20}){let{rows:r}=await d.raw(`
|
|
136
136
|
SELECT id, document_id AS "documentId", chunk_index AS "chunkIndex",
|
|
137
137
|
content, section_heading AS "sectionHeading", namespace,
|
|
138
138
|
ts_rank(search_vector, plainto_tsquery('english', ?)) as rank
|
|
@@ -141,10 +141,10 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
141
141
|
AND search_vector @@ plainto_tsquery('english', ?)
|
|
142
142
|
ORDER BY rank DESC
|
|
143
143
|
LIMIT ?
|
|
144
|
-
`,[e,t,e,n]);return r}var
|
|
144
|
+
`,[e,t,e,n]);return r}var ar=h(()=>{I();Ce()});async function cr(e,t,{namespaces:n,limit:r=5,minConfidence:o="medium",pointInTime:i,categories:s,podIds:a=null}){let c=$(t),u=`${q("embedding")} <=> ${J()}`,{temporalClause:m,categoryClause:y,filterParams:f}=ve({minConfidence:o,pointInTime:i,categories:s}),p=r*Zi,w=Array.isArray(a),_=w&&a.length===0,b=w?_?"AND FALSE":`AND id = ANY(
|
|
145
145
|
SELECT member_id FROM pod_membership
|
|
146
146
|
WHERE member_type = 'fact' AND pod_id = ANY(?::int[])
|
|
147
|
-
)`:"",v=w&&!_?[a]:[],[E,...R]=f,
|
|
147
|
+
)`:"",v=w&&!_?[a]:[],[E,...R]=f,P=[c,c,n,E,...R,...v,c,p],g=[e,e,n,E,e,...R,...v,p],ee=[p,p,r],ue=`
|
|
148
148
|
WITH semantic AS (
|
|
149
149
|
SELECT id,
|
|
150
150
|
uid,
|
|
@@ -160,7 +160,7 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
160
160
|
WHERE namespace = ANY(?)
|
|
161
161
|
AND status = 'active'
|
|
162
162
|
AND embedding IS NOT NULL
|
|
163
|
-
AND ${
|
|
163
|
+
AND ${le} >= ?
|
|
164
164
|
${m}
|
|
165
165
|
${y}
|
|
166
166
|
${b}
|
|
@@ -181,7 +181,7 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
181
181
|
FROM fact
|
|
182
182
|
WHERE namespace = ANY(?)
|
|
183
183
|
AND status = 'active'
|
|
184
|
-
AND ${
|
|
184
|
+
AND ${le} >= ?
|
|
185
185
|
AND search_vector @@ plainto_tsquery('english', ?)
|
|
186
186
|
${m}
|
|
187
187
|
${y}
|
|
@@ -205,8 +205,8 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
205
205
|
COALESCE(s.created_at, k.created_at) AS created_at,
|
|
206
206
|
COALESCE(s.similarity, 0) AS similarity,
|
|
207
207
|
(
|
|
208
|
-
${
|
|
209
|
-
+ ${
|
|
208
|
+
${zi} * (1.0 / (${sr} + COALESCE(s.rank_ix, ?)))
|
|
209
|
+
+ ${Xi} * (1.0 / (${sr} + COALESCE(k.rank_ix, ?)))
|
|
210
210
|
) AS rrf_raw
|
|
211
211
|
FROM semantic s
|
|
212
212
|
FULL OUTER JOIN keyword k ON s.id = k.id
|
|
@@ -226,11 +226,11 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
226
226
|
)
|
|
227
227
|
)
|
|
228
228
|
)) AS activation,
|
|
229
|
-
CASE f.importance WHEN 'vital' THEN ${
|
|
229
|
+
CASE f.importance WHEN 'vital' THEN ${Qi} ELSE 1.0 END AS importance_mult,
|
|
230
230
|
CASE f.confidence
|
|
231
|
-
WHEN 'high' THEN ${
|
|
232
|
-
WHEN 'medium' THEN ${
|
|
233
|
-
WHEN 'low' THEN ${
|
|
231
|
+
WHEN 'high' THEN ${ea}
|
|
232
|
+
WHEN 'medium' THEN ${ta}
|
|
233
|
+
WHEN 'low' THEN ${na}
|
|
234
234
|
ELSE 1.0
|
|
235
235
|
END AS confidence_mult
|
|
236
236
|
FROM fused f
|
|
@@ -247,7 +247,7 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
247
247
|
ORDER BY final_score DESC,
|
|
248
248
|
CASE WHEN importance = 'vital' THEN 0 ELSE 1 END
|
|
249
249
|
LIMIT ?
|
|
250
|
-
`,
|
|
250
|
+
`,de=[...P,...g,...ee],{rows:pe}=await d.raw(ue,de);if(!pe.length)return[];let Zr=pe[0].final_score||pe[0].rrf_raw||1;return pe.map(ke=>({...ke,rrfScore:Math.round(Number(ke.final_score||ke.rrf_raw)/Number(Zr)*100)/100}))}var sr,zi,Xi,Zi,Qi,ea,ta,na,lr=h(()=>{I();z();S();Ce();sr=20,zi=1,Xi=.7,Zi=3,Qi=1.5,ea=1,ta=.85,na=.7});async function ur(e){let t=e.map(o=>o.id),n=await se(t),r=new Set;for(let o of n.values())for(let i of o)r.add(i);return r.size?d("entity").whereIn("id",[...r]).whereNull("mergedWith").select("id","uid","name","entityType","description"):[]}async function dr(e,{limit:t=10}={}){if(!e.length)return[];let n=await d("relation").where(function(){this.whereIn("sourceId",e).orWhereIn("targetId",e)}).whereNull("invalidAt").select("*").limit(t*3),r=new Set(e),o=new Set,i=new Map;for(let y of n){let f=r.has(y.sourceId)?y.targetId:y.sourceId;o.add(f),i.has(f)||i.set(f,y)}if(!o.size)return[];let s=await d("entity").whereIn("id",[...o]).whereNull("mergedWith").select("id","name"),a=new Map(s.map(y=>[y.id,y.name])),c=await d("fact").join("fact_entity","fact.id","fact_entity.factId").whereIn("fact_entity.entityId",[...o]).where("fact.status","active").select("fact.*","fact_entity.entityId").orderBy("fact_entity.mentionCount","desc").limit(t*3),u=new Set,m=[];for(let y of c){if(u.has(y.id))continue;u.add(y.id);let f=i.get(y.entityId),p=a.get(y.entityId)||"unknown",w=f?.relationType||"related";if(m.push({...y,relationPath:`${p} (${w})`,graphDistance:1}),m.length>=t)break}return m}function pr(e,t,n,r){let o=new Set(n),i=e.map(a=>({...a,resultType:"direct"})),s=t.filter(a=>!e.some(c=>c.id===a.id)).map(a=>({...a,rrfScore:(a.rrfScore||.1)*.5,resultType:"related"}));return[...i,...s].slice(0,r)}var mr=h(()=>{I();Ne()});var Z,ut=h(()=>{Z=class{#e=new Map;#t;#n;constructor({maxSize:t=100,ttlMs:n=300*1e3}={}){this.#t=t,this.#n=n}get(t){let n=this.#e.get(t);if(n){if(Date.now()-n.timestamp>this.#n){this.#e.delete(t);return}return n.value}}set(t,n){if(this.#e.size>=this.#t){let r=this.#e.keys().next().value;this.#e.delete(r)}this.#e.set(t,{value:n,timestamp:Date.now()})}}});async function hr(e){let t=fr.get(e);if(t)return t;let n=`You are a search query expander for a personal knowledge base.
|
|
251
251
|
|
|
252
252
|
Given the user's query, generate 3-5 alternative search queries that would help find ALL relevant information \u2014 including facts that don't literally match the query but are semantically related.
|
|
253
253
|
|
|
@@ -259,7 +259,7 @@ Think about:
|
|
|
259
259
|
|
|
260
260
|
User query: "${e}"
|
|
261
261
|
|
|
262
|
-
Respond with ONLY a JSON array of strings. Do not include the original query.`;try{let r=await
|
|
262
|
+
Respond with ONLY a JSON array of strings. Do not include the original query.`;try{let r=await Re(n,{model:l.llm.extractionModel,caller:"query-expander"});if(!Array.isArray(r))return[e];let o=r.filter(s=>typeof s=="string"&&s.trim()).slice(0,ra),i=o.length?[e,...o]:[e];return fr.set(e,i),i}catch(r){return console.error("[query-expander] Failed:",r.message),[e]}}var ra,fr,_r=h(()=>{ce();ut();S();ra=5,fr=new Z({maxSize:100,ttlMs:300*1e3})});import{readFile as oa}from"node:fs/promises";import{join as ia}from"node:path";function la(e,t){let n,r=new Promise((o,i)=>{n=setTimeout(()=>i(new Error(`query-router timed out after ${t}ms`)),t),n.unref?.()});return Promise.race([e,r]).finally(()=>clearTimeout(n))}async function gr(e){let t=e.trim().toLowerCase(),n=dt.get(t);if(n)return n;let o=`${await oa(aa,"utf8")}
|
|
263
263
|
|
|
264
264
|
---
|
|
265
265
|
|
|
@@ -267,8 +267,8 @@ Query: ${e}
|
|
|
267
267
|
|
|
268
268
|
---
|
|
269
269
|
|
|
270
|
-
Respond with ONLY a JSON object: { "intent": "preference|factual|entity_lookup|exploratory|temporal", "categories": [...], "entities": [...], "expand": bool, "pointInTime": null or "YYYY-MM-DD", "reasoning": "..." }`;try{let i=await
|
|
271
|
-
`),Ea(n.name,r)}return t}function Ea(e,t){Promise.resolve().then(()=>(Or(),br)).then(({recordTrace:n})=>n({kind:"lifecycle",summary:`pod-resolution failed for kind "${e}"`,detail:{kind:e,error:t.message}})).catch(()=>{})}var pa,ma,fa,ha,Tr,pt=h(()=>{B();pa=["name"],ma=new Set(["private","shared","public"]),fa=new Set(["singleton-live","multi-active","rolling-window","always"]),ha=new Set(["origin-only","shared-allowlist","open"]),Tr=new Map});var ft={};D(ft,{CURSOR_PATH:()=>z,endActiveSession:()=>Da,ensureActiveSession:()=>ba,getActiveCursor:()=>Ta,getActiveSessionPodUid:()=>mt});import{writeFile as ya,readFile as ga,unlink as wa}from"node:fs/promises";import{existsSync as Sa,mkdirSync as Aa}from"node:fs";import{dirname as Rr}from"node:path";async function Le(){try{let e=await ga(z,"utf8");return JSON.parse(e)}catch{return null}}async function Lr(e){Sa(Rr(z))||Aa(Rr(z),{recursive:!0}),await ya(z,JSON.stringify(e,null,2),"utf8")}async function ba({sessionId:e,transcriptPath:t=null,cwd:n=null,model:r=null,namespace:o=null}){if(!e)throw new Error("ensureActiveSession requires sessionId from hook stdin");let i=o||l.defaults.namespace,s=await Le();if(s&&s.session_id===e&&s.namespace===i){let u=await nt(s.pod_uid);if(u)return await rt(u.id,{turn_count:(Na(u.attrs)||0)+1}),await Oa(s),u}let a=new Date,{pod:c}=await Se({podType:vr,externalId:e,name:Pr({sessionId:e,startedAt:a}),namespace:i,attrs:Cr({sessionId:e,transcriptPath:t,cwd:n,turnCount:1,model:r}),startedAt:a});return await Lr({session_id:e,pod_uid:c.uid,namespace:i,started_at:c.startedAt??a.toISOString(),last_seen_at:new Date().toISOString()}),c}async function Oa(e){await Lr({...e,last_seen_at:new Date().toISOString()})}async function mt({allowStale:e=!1}={}){let t=await Le();return!t||!t.pod_uid||!e&&t.started_at&&Date.now()-new Date(t.started_at).getTime()>Ia?null:t.pod_uid}async function Ta(){return Le()}async function Da({conclusion:e=null,summary:t=null}={}){let n=await Le();if(!n)return null;let r=await nt(n.pod_uid);if(r){if(e||t){let o={};e&&(o.conclusion=e),t&&(o.summary=t),await rt(r.id,o)}await Wn(r.id)}try{await wa(z)}catch{}return r}function Na(e){if(!e)return 0;if(typeof e=="object")return e.turn_count??0;try{return JSON.parse(e).turn_count??0}catch{return 0}}var z,Ia,ve=h(()=>{Ae();ht();A();B();z=Tt,Ia=360*60*1e3});function Cr({sessionId:e,transcriptPath:t=null,cwd:n=null,turnCount:r=0,model:o=null,conclusion:i=null,summary:s=null}){return{session_id:e,transcript_path:t,cwd:n,turn_count:r,model:o,conclusion:i,summary:s}}function Pr({sessionId:e,startedAt:t=new Date}={}){let r=(t instanceof Date?t:new Date(t)).toISOString().replace("T"," ").slice(0,16),o=e?e.slice(0,8):"unknown";return`claude-session ${r} (${o})`}var vr,Mr,ht=h(()=>{ve();vr="claude_session",Mr={name:"claude_session",description:"Claude Code session",identityField:"session_id",attrsSchema:{session_id:"string",transcript_path:"string",cwd:"string",turn_count:"number",model:"string",conclusion:"string",summary:"string"},visibility:"private",activeMode:"singleton-live",hotContextBudget:6,retrievalWeights:{recency:1,relevance:.7},importanceDefault:2,ttlDays:90,schemaDocPath:"kinds/claude_session.schema.md",writePolicy:"origin-only",resolveActiveScope:async()=>{try{let e=await mt();return e?[e]:[]}catch{return[]}}}});var La,xr,kr=h(()=>{I();A();La=1440*60*1e3,xr={name:"person",description:"A person you have a working relationship with",identityField:"primary_handle",attrsSchema:{platforms:"object",role:"string",relationship:"string",notes:"string"},visibility:"private",activeMode:"rolling-window",hotContextBudget:4,retrievalWeights:{recency:1,relevance:.8},importanceDefault:3,ttlDays:null,schemaDocPath:"kinds/person.schema.md",writePolicy:"origin-only",resolveActiveScope:async(e={})=>{let t=e.namespace||l.defaults.namespace;try{let n=new Date(Date.now()-La);return(await d("pod as p").join("pod_membership as pm","pm.pod_id","p.id").join("fact_lifecycle as fl","fl.fact_id","pm.member_id").where("pm.memberType","fact").where("p.podType","person").where("p.namespace",t).where("p.status","active").where("fl.lastAccessedAt",">=",n).distinct("p.uid")).map(o=>o.uid)}catch{return[]}}}});var $r={};D($r,{POD_TYPE:()=>Et,deriveProjectRoot:()=>gt,ensureProjectPod:()=>Ca,formatForDisplay:()=>Ma,membership:()=>be,projectKind:()=>yt});import{execFileSync as va}from"node:child_process";import{basename as Br}from"node:path";async function Ca({cwd:e,namespace:t=null}){if(!e)return null;let n=gt(e),r=t||l.defaults.namespace,i=(n!==e?!1:_t(e)===e)?n:_t(e),{pod:s}=await Se({podType:Et,externalId:n,name:Br(n)||n,namespace:r,attrs:{root_path:n,git_root:i||null,display_name:Br(n)||n,discovered_at:new Date().toISOString()},startedAt:new Date});return s}function gt(e){return _t(e)||e}function _t(e){try{return va("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}async function Pa(){try{let{getActiveCursor:e}=await Promise.resolve().then(()=>(ve(),ft));return(await e())?.cwd||null}catch{return null}}function Ma(e){let t=xa(e.attrs);return{uid:e.uid,name:e.name,rootPath:t.root_path,gitRoot:t.git_root,displayName:t.display_name,discoveredAt:t.discovered_at,memberFactCount:e.memberFactCount,memberDocCount:e.memberDocCount}}function xa(e){if(!e)return{};if(typeof e=="object")return e;try{return JSON.parse(e)}catch{return{}}}var Et,yt,wt=h(()=>{Ae();ot();A();Et="project",yt={name:"project",description:"Code project rooted at a git repo or directory",identityField:"root_path",attrsSchema:{root_path:"string",git_root:"string",display_name:"string",discovered_at:"string"},visibility:"shared",activeMode:"multi-active",hotContextBudget:4,retrievalWeights:{recency:.6,relevance:1},importanceDefault:3,ttlDays:null,schemaDocPath:"kinds/project.schema.md",writePolicy:"origin-only",resolveActiveScope:async(e={})=>{let t=e.cwd||await Pa();if(!t)return[];let n=e.namespace||l.defaults.namespace,r=gt(t),o=await Gn({podType:Et,externalId:r,namespace:n});return o?[o.uid]:[]}}});async function Ba(e){if(e.project)return e.project;if(!e.cwd)try{let{getActiveCursor:t}=await Promise.resolve().then(()=>(ve(),ft)),n=await t();e={...e,cwd:n?.cwd}}catch{return null}if(!e.cwd)return null;try{let{deriveProjectRoot:t}=await Promise.resolve().then(()=>(wt(),$r)),n=t(e.cwd);return n?n.split("/").pop():null}catch{return null}}function $a(e){if(!e)return{};if(typeof e=="object")return e;try{return JSON.parse(e)}catch{return{}}}var ka,Fr,Ur=h(()=>{I();A();ka="playbook",Fr={name:"playbook",description:"A reusable workflow or debug recipe (procedural memory)",identityField:"slug",attrsSchema:{slug:"string",project:"string",description:"string",tags:"array"},visibility:"shared",activeMode:"always",hotContextBudget:3,retrievalWeights:{recency:.3,relevance:1},importanceDefault:3,ttlDays:null,schemaDocPath:"kinds/playbook.schema.md",writePolicy:"origin-only",resolveActiveScope:async(e={})=>{let t=e.namespace||l.defaults.namespace,n=await Ba(e);try{let o=await d("pod").where({podType:ka,namespace:t,status:"active"}).select("uid","attrs");return n?o.filter(s=>{let a=$a(s.attrs);return!a.project||a.project===n}).map(s=>s.uid):o.map(s=>s.uid)}catch{return[]}}}});var Fa,Hr,Gr=h(()=>{I();A();Fa=["__virtual:vital__"],Hr={name:"vital",description:"Facts marked importance=5 (vital), surfaced globally",identityField:null,attrsSchema:{},visibility:"public",activeMode:"always",hotContextBudget:6,retrievalWeights:{recency:.5,relevance:1},importanceDefault:5,ttlDays:null,schemaDocPath:"kinds/vital.schema.md",writePolicy:"open",resolveActiveScope:async()=>Fa,fetchFacts:async(e={},{slots:t=8,namespace:n}={})=>{let r=n||e.namespace||l.defaults.namespace;return d("fact as f").leftJoin("fact_lifecycle as fl","fl.fact_id","f.id").where({"f.status":"active","f.namespace":r}).where(o=>{o.where("f.importance","vital").orWhere("f.importance_score",5)}).orderByRaw("COALESCE(fl.access_count, 0) DESC, f.created_at DESC").limit(t).pluck("f.content")}}});function Ha(){if(!Wr){for(let e of Ua)Dr(e);Wr=!0}}var Ua,Wr,Yr=h(()=>{pt();ht();kr();wt();Ur();Gr();Ua=[Mr,yt,xr,Fr,Hr],Wr=!1;Ha()});var Jr={};D(Jr,{isSearchableQuery:()=>Kr,search:()=>Ka});async function Ka(e,{namespaces:t,limit:n=5,minConfidence:r="medium",useGraph:o=!1,includeChunks:i=!1,pointInTime:s,expand:a=!1,route:c=!0,categories:u,synthesize:m=l.search.synthesize,podScope:y=null,applyFloor:f=!0,ctx:p={}}={}){let w=Date.now();if(!Kr(e)){let g=Va();return g._trace={query:e,searchable:!1,stages:[{stage:"guard",note:"query is not searchable (empty or wildcard-only)"}],durationMs:Date.now()-w},g}m&&(i=!0);let _=null;c&&(_=await Er(e),o=o||_.useGraph,a=a||_.expand,n=_.limit||n,s=s||_.pointInTime,u=u||(_.categories.length?_.categories:void 0));let b=await Xa(e,t),v=await za(y,{...p,namespace:t?.[0]}),E;b?E=await Za(b,e,{namespaces:t,limit:n,minConfidence:r,includeChunks:i,pointInTime:s,categories:u,podIds:v}):E=await ts(e,{namespaces:t,limit:n,minConfidence:r,useGraph:o,includeChunks:i,pointInTime:s,expand:a,categories:u,podIds:v});let R=null;if(f&&Array.isArray(E.facts)&&E.facts.length){let g=l.memory.injectionFloor,X=E.facts.length;E.facts=E.facts.filter(se=>{if(se.source==="entity")return!0;let ce=Number(se.similarity);return Number.isFinite(ce)?ce>=g:!0}),R={threshold:g,dropped:X-E.facts.length,kept:E.facts.length}}let M=E.facts.map(g=>g.id).filter(Boolean);if(Jn(M).catch(g=>console.error("[access-tracking]",g.message)),zn(M.slice(0,8)).catch(g=>console.error("[hebbian]",g.message)),l.hebbian.entity.enabled&&M.length>=2&&qa(M).catch(g=>console.error("[hebbian-entity]",g.message)),m)try{E.synthesized=await Ja(e,E)}catch(g){console.error("[synthesizer] failed:",g.message),E.synthesized=null}return E._trace=ja({query:e,namespaces:t,limit:n,minConfidence:r,useGraph:o,expand:a,route:c,routing:_,matchedEntity:b,podScope:y,podIds:v,result:E,factIds:M,floored:R,durationMs:Date.now()-w}),E}function ja({query:e,namespaces:t,limit:n,minConfidence:r,useGraph:o,expand:i,route:s,routing:a,matchedEntity:c,podScope:u,podIds:m,result:y,factIds:f,floored:p,durationMs:w}){let _=E=>{let R=Number(E);return Number.isFinite(R)?Math.round(R*1e4)/1e4:null},b=(y.facts||[]).map((E,R)=>({rank:R+1,id:E.id??null,content:String(E.content||"").slice(0,240),category:E.category??null,importance:E.importance??null,confidence:E.confidence??null,source:E.source??null,similarity:_(E.similarity),rrfRaw:_(E.rrf_raw),activation:_(E.activation),accessCount:E.access_count??null,lastAccessedAt:E.lastAccessedAt??null,finalScore:_(E.final_score),rrfScore:_(E.rrfScore),coRetrievalBoost:_(E.coRetrievalBoost)})),v=(y.chunks||[]).map((E,R)=>({rank:R+1,id:E.id??null,sectionHeading:E.sectionHeading??null,content:String(E.content||"").slice(0,200),similarity:_(E.similarity),rrfScore:_(E.rrfScore)}));return{query:e,namespaces:t,durationMs:w,params:{limit:n,minConfidence:r,useGraphRequested:o,expandRequested:i,routeEnabled:s},routing:a?{intent:a.intent??null,reasoning:a.reasoning??null,useGraph:a.useGraph??null,expand:a.expand??null,limit:a.limit??null,categories:a.categories??null,pointInTime:a.pointInTime??null}:null,strategy:c?"entity-first":"standard",matchedEntity:c?{id:c.id,name:c.name,type:c.entityType,aliases:c.aliases||[]}:null,podScope:{requested:u,resolvedIds:m},floor:p?{applied:!0,threshold:p.threshold,dropped:p.dropped,kept:p.kept,note:"precision-first: facts below cosine floor dropped from injection"}:{applied:!1},ranking:{model:"RRF(vector\xD71.0 + keyword\xD70.7) \xD7 softplus(ACT-R activation) \xD7 importance \xD7 confidence",facts:b,chunks:v},synthesized:y.synthesized||null,relatedEntities:y.relatedEntities||[],reinforced:{factIds:f,note:"access_count bumped + Hebbian co-retrieval edges strengthened (off hot path)"}}}function Kr(e){let t=String(e||"").trim();return t?!/^[*%_?\s]+$/.test(t):!1}function Va(){return{facts:[],chunks:[],matchedEntity:null,relatedEntities:[]}}async function Ja(e,{facts:t,chunks:n}){let r=[];if(t.slice(0,10).forEach((s,a)=>{r.push(`[F${a+1}] (${s.category}) ${s.content}`)}),n.length&&n.slice(0,15).forEach((s,a)=>{let c=(s.content||"").replace(/\s+/g," ").trim();c&&r.push(`[C${a+1}] ${c.slice(0,2e3)}`)}),!r.length)return"No retrieved evidence \u2014 nothing to synthesize.";let o=`You are answering a question from a personal-memory system.
|
|
270
|
+
Respond with ONLY a JSON object: { "intent": "preference|factual|entity_lookup|exploratory|temporal", "categories": [...], "entities": [...], "expand": bool, "pointInTime": null or "YYYY-MM-DD", "reasoning": "..." }`;try{let i=await la(Re(o,{model:l.llm.extractionModel,caller:"query-router"}),ca);if(!i||!sa.includes(i.intent)){let c=Er("factual",{});return dt.set(t,c),c}let s=yr[i.intent],a={intent:i.intent,categories:Array.isArray(i.categories)&&i.categories.length?i.categories:s.categories,entities:Array.isArray(i.entities)?i.entities:[],expand:typeof i.expand=="boolean"?i.expand:s.expand,useGraph:s.useGraph,limit:s.limit,pointInTime:i.pointInTime||null,reasoning:i.reasoning||""};return dt.set(t,a),a}catch(i){return console.error("[query-router] Failed:",i.message),Er("factual",{reasoning:`Fallback \u2014 ${i.message}`})}}function Er(e,t={}){let n=yr[e];return{intent:e,categories:n.categories,entities:[],expand:n.expand,useGraph:n.useGraph,limit:n.limit,pointInTime:null,reasoning:"",...t}}var aa,dt,sa,ca,yr,wr=h(()=>{ce();ut();S();B();aa=ia(he,"query-router.md"),dt=new Z({maxSize:200,ttlMs:600*1e3}),sa=["preference","factual","entity_lookup","exploratory","temporal"],ca=8e3;yr={preference:{categories:["preference","opinion","personal"],expand:!1,useGraph:!1,limit:null},factual:{categories:[],expand:!1,useGraph:!1,limit:null},entity_lookup:{categories:[],expand:!1,useGraph:!0,limit:null},exploratory:{categories:[],expand:!0,useGraph:!0,limit:15},temporal:{categories:[],expand:!1,useGraph:!1,limit:null}}});var pt,ua,Sr,Ar=h(()=>{pt=class{constructor(){this.buffer=[],this.subs=new Set}emit(t,n={}){let r={type:t,ts:new Date().toISOString(),...n};this.buffer.push(r),this.buffer.length>200&&this.buffer.shift();for(let o of this.subs)try{o(r)}catch{}return r}subscribe(t){return this.subs.add(t),()=>this.subs.delete(t)}recent(t=50){return t>=this.buffer.length?[...this.buffer]:this.buffer.slice(-t)}subscriberCount(){return this.subs.size}},ua=new pt,Sr=ua});import{AsyncLocalStorage as da}from"node:async_hooks";function Ir(){return pa.getStore()||null}var pa,br=h(()=>{pa=new da});var Tr={};D(Tr,{clearTraces:()=>ya,getTrace:()=>Ea,listTraces:()=>_a,recordTrace:()=>ha});function fa(){let e=Ir();return{deviceId:e?.device?.id??null,transport:e?.transport??null}}async function ha({kind:e,summary:t,detail:n={},namespace:r=null,durationMs:o=null}){let i=`trace-${Ie(16)}`,s=new Date().toISOString(),{deviceId:a,transport:c}=fa(),u=n;try{JSON.stringify(n).length>ma&&(u={truncated:!0,note:"trace detail exceeded size cap",summary:t})}catch{u={error:"detail not serializable"}}try{Sr.emit("trace",{uid:i,kind:e,summary:t,namespace:r,durationMs:o,deviceId:a,transport:c,detail:u})}catch{}try{return await d("trace_event").insert({uid:i,kind:e,ts:s,duration_ms:o,namespace:r,summary:t,device_id:a,transport:c,detail:JSON.stringify(u)}),i}catch(m){return console.error("[trace-store] persist failed:",m.message),null}}async function _a({kind:e=null,namespace:t=null,before:n=null,limit:r=50}={}){let o=d("trace_event").select("uid","kind","ts","duration_ms as durationMs","namespace","summary","device_id as deviceId","transport","detail").orderBy("ts","desc").limit(Math.min(Number(r)||50,200));return e&&(o=o.where({kind:e})),t&&(o=o.where({namespace:t})),n&&(o=o.where("ts","<",n)),(await o).map(s=>({...s,detail:typeof s.detail=="string"?Or(s.detail):s.detail}))}async function Ea(e){let t=await d("trace_event").select("uid","kind","ts","duration_ms as durationMs","namespace","summary","device_id as deviceId","transport","detail").where({uid:e}).first();return t?{...t,detail:typeof t.detail=="string"?Or(t.detail):t.detail}:null}async function ya(){return{cleared:await d("trace_event").del()}}function Or(e){try{return JSON.parse(e)}catch{return{}}}var ma,Dr=h(()=>{nt();I();Ar();br();ma=256*1024});function Rr(e){for(let t of ga)if(!e[t])throw new Error(`Pod kind missing required field: ${t}`);if(e.visibility&&!wa.has(e.visibility))throw new Error(`Pod kind ${e.name}: invalid visibility ${e.visibility}`);if(e.activeMode&&!Sa.has(e.activeMode))throw new Error(`Pod kind ${e.name}: invalid activeMode ${e.activeMode}`);if(e.writePolicy&&!Aa.has(e.writePolicy))throw new Error(`Pod kind ${e.name}: invalid writePolicy ${e.writePolicy}`);Nr.set(e.name,Ia(e))}function Ia(e){return{visibility:"private",activeMode:"multi-active",hotContextBudget:0,retrievalWeights:{recency:1,relevance:1},importanceDefault:2,ttlDays:null,writePolicy:"origin-only",lifecycle:{},...e}}async function Lr(e={}){let t=[];for(let n of Nr.values())if(typeof n.resolveActiveScope=="function")try{let r=await n.resolveActiveScope(e);Array.isArray(r)&&r.length>0&&t.push({kind:n,scope:r})}catch(r){process.stderr.write(`[sigil:pods] resolveActiveScope failed for kind "${n.name}": ${r.message}
|
|
271
|
+
`),ba(n.name,r)}return t}function ba(e,t){Promise.resolve().then(()=>(Dr(),Tr)).then(({recordTrace:n})=>n({kind:"lifecycle",summary:`pod-resolution failed for kind "${e}"`,detail:{kind:e,error:t.message}})).catch(()=>{})}var ga,wa,Sa,Aa,Nr,mt=h(()=>{B();ga=["name"],wa=new Set(["private","shared","public"]),Sa=new Set(["singleton-live","multi-active","rolling-window","always"]),Aa=new Set(["origin-only","shared-allowlist","open"]),Nr=new Map});var ht={};D(ht,{CURSOR_PATH:()=>Q,endActiveSession:()=>Pa,ensureActiveSession:()=>va,getActiveCursor:()=>Ma,getActiveSessionPodUid:()=>ft});import{writeFile as Oa,readFile as Ta,unlink as Da}from"node:fs/promises";import{existsSync as Na,mkdirSync as Ra}from"node:fs";import{dirname as vr}from"node:path";async function Me(){try{let e=await Ta(Q,"utf8");return JSON.parse(e)}catch{return null}}async function Cr(e){Na(vr(Q))||Ra(vr(Q),{recursive:!0}),await Oa(Q,JSON.stringify(e,null,2),"utf8")}async function va({sessionId:e,transcriptPath:t=null,cwd:n=null,model:r=null,namespace:o=null}){if(!e)throw new Error("ensureActiveSession requires sessionId from hook stdin");let i=o||l.defaults.namespace,s=await Me();if(s&&s.session_id===e&&s.namespace===i){let u=await rt(s.pod_uid);if(u)return await ot(u.id,{turn_count:(xa(u.attrs)||0)+1}),await Ca(s),u}let a=new Date,{pod:c}=await be({podType:Mr,externalId:e,name:xr({sessionId:e,startedAt:a}),namespace:i,attrs:Pr({sessionId:e,transcriptPath:t,cwd:n,turnCount:1,model:r}),startedAt:a});return await Cr({session_id:e,pod_uid:c.uid,namespace:i,started_at:c.startedAt??a.toISOString(),last_seen_at:new Date().toISOString()}),c}async function Ca(e){await Cr({...e,last_seen_at:new Date().toISOString()})}async function ft({allowStale:e=!1}={}){let t=await Me();return!t||!t.pod_uid||!e&&t.started_at&&Date.now()-new Date(t.started_at).getTime()>La?null:t.pod_uid}async function Ma(){return Me()}async function Pa({conclusion:e=null,summary:t=null}={}){let n=await Me();if(!n)return null;let r=await rt(n.pod_uid);if(r){if(e||t){let o={};e&&(o.conclusion=e),t&&(o.summary=t),await ot(r.id,o)}await Kn(r.id)}try{await Da(Q)}catch{}return r}function xa(e){if(!e)return 0;if(typeof e=="object")return e.turn_count??0;try{return JSON.parse(e).turn_count??0}catch{return 0}}var Q,La,Pe=h(()=>{Oe();_t();S();B();Q=Dt,La=360*60*1e3});function Pr({sessionId:e,transcriptPath:t=null,cwd:n=null,turnCount:r=0,model:o=null,conclusion:i=null,summary:s=null}){return{session_id:e,transcript_path:t,cwd:n,turn_count:r,model:o,conclusion:i,summary:s}}function xr({sessionId:e,startedAt:t=new Date}={}){let r=(t instanceof Date?t:new Date(t)).toISOString().replace("T"," ").slice(0,16),o=e?e.slice(0,8):"unknown";return`claude-session ${r} (${o})`}var Mr,kr,_t=h(()=>{Pe();Mr="claude_session",kr={name:"claude_session",description:"Claude Code session",identityField:"session_id",attrsSchema:{session_id:"string",transcript_path:"string",cwd:"string",turn_count:"number",model:"string",conclusion:"string",summary:"string"},visibility:"private",activeMode:"singleton-live",hotContextBudget:6,retrievalWeights:{recency:1,relevance:.7},importanceDefault:2,ttlDays:90,schemaDocPath:"kinds/claude_session.schema.md",writePolicy:"origin-only",resolveActiveScope:async()=>{try{let e=await ft();return e?[e]:[]}catch{return[]}}}});var Ba,Br,$r=h(()=>{I();S();Ba=1440*60*1e3,Br={name:"person",description:"A person you have a working relationship with",identityField:"primary_handle",attrsSchema:{platforms:"object",role:"string",relationship:"string",notes:"string"},visibility:"private",activeMode:"rolling-window",hotContextBudget:4,retrievalWeights:{recency:1,relevance:.8},importanceDefault:3,ttlDays:null,schemaDocPath:"kinds/person.schema.md",writePolicy:"origin-only",resolveActiveScope:async(e={})=>{let t=e.namespace||l.defaults.namespace;try{let n=new Date(Date.now()-Ba);return(await d("pod as p").join("pod_membership as pm","pm.pod_id","p.id").join("fact_lifecycle as fl","fl.fact_id","pm.member_id").where("pm.memberType","fact").where("p.podType","person").where("p.namespace",t).where("p.status","active").where("fl.lastAccessedAt",">=",n).distinct("p.uid")).map(o=>o.uid)}catch{return[]}}}});var Ur={};D(Ur,{POD_TYPE:()=>yt,deriveProjectRoot:()=>wt,ensureProjectPod:()=>Fa,formatForDisplay:()=>Ha,membership:()=>De,projectKind:()=>gt});import{execFileSync as $a}from"node:child_process";import{basename as Fr}from"node:path";async function Fa({cwd:e,namespace:t=null}){if(!e)return null;let n=wt(e),r=t||l.defaults.namespace,i=(n!==e?!1:Et(e)===e)?n:Et(e),{pod:s}=await be({podType:yt,externalId:n,name:Fr(n)||n,namespace:r,attrs:{root_path:n,git_root:i||null,display_name:Fr(n)||n,discovered_at:new Date().toISOString()},startedAt:new Date});return s}function wt(e){return Et(e)||e}function Et(e){try{return $a("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}async function Ua(){try{let{getActiveCursor:e}=await Promise.resolve().then(()=>(Pe(),ht));return(await e())?.cwd||null}catch{return null}}function Ha(e){let t=Ga(e.attrs);return{uid:e.uid,name:e.name,rootPath:t.root_path,gitRoot:t.git_root,displayName:t.display_name,discoveredAt:t.discovered_at,memberFactCount:e.memberFactCount,memberDocCount:e.memberDocCount}}function Ga(e){if(!e)return{};if(typeof e=="object")return e;try{return JSON.parse(e)}catch{return{}}}var yt,gt,St=h(()=>{Oe();it();S();yt="project",gt={name:"project",description:"Code project rooted at a git repo or directory",identityField:"root_path",attrsSchema:{root_path:"string",git_root:"string",display_name:"string",discovered_at:"string"},visibility:"shared",activeMode:"multi-active",hotContextBudget:4,retrievalWeights:{recency:.6,relevance:1},importanceDefault:3,ttlDays:null,schemaDocPath:"kinds/project.schema.md",writePolicy:"origin-only",resolveActiveScope:async(e={})=>{let t=e.cwd||await Ua();if(!t)return[];let n=e.namespace||l.defaults.namespace,r=wt(t),o=await Yn({podType:yt,externalId:r,namespace:n});return o?[o.uid]:[]}}});async function Ya(e){if(e.project)return e.project;if(!e.cwd)try{let{getActiveCursor:t}=await Promise.resolve().then(()=>(Pe(),ht)),n=await t();e={...e,cwd:n?.cwd}}catch{return null}if(!e.cwd)return null;try{let{deriveProjectRoot:t}=await Promise.resolve().then(()=>(St(),Ur)),n=t(e.cwd);return n?n.split("/").pop():null}catch{return null}}function Ka(e){if(!e)return{};if(typeof e=="object")return e;try{return JSON.parse(e)}catch{return{}}}var Wa,Hr,Gr=h(()=>{I();S();Wa="playbook",Hr={name:"playbook",description:"A reusable workflow or debug recipe (procedural memory)",identityField:"slug",attrsSchema:{slug:"string",project:"string",description:"string",tags:"array"},visibility:"shared",activeMode:"always",hotContextBudget:3,retrievalWeights:{recency:.3,relevance:1},importanceDefault:3,ttlDays:null,schemaDocPath:"kinds/playbook.schema.md",writePolicy:"origin-only",resolveActiveScope:async(e={})=>{let t=e.namespace||l.defaults.namespace,n=await Ya(e);try{let o=await d("pod").where({podType:Wa,namespace:t,status:"active"}).select("uid","attrs");return n?o.filter(s=>{let a=Ka(s.attrs);return!a.project||a.project===n}).map(s=>s.uid):o.map(s=>s.uid)}catch{return[]}}}});var ja,Wr,Yr=h(()=>{I();S();ja=["__virtual:vital__"],Wr={name:"vital",description:"Facts marked importance=5 (vital), surfaced globally",identityField:null,attrsSchema:{},visibility:"public",activeMode:"always",hotContextBudget:6,retrievalWeights:{recency:.5,relevance:1},importanceDefault:5,ttlDays:null,schemaDocPath:"kinds/vital.schema.md",writePolicy:"open",resolveActiveScope:async()=>ja,fetchFacts:async(e={},{slots:t=8,namespace:n}={})=>{let r=n||e.namespace||l.defaults.namespace;return d("fact as f").leftJoin("fact_lifecycle as fl","fl.fact_id","f.id").where({"f.status":"active","f.namespace":r}).where(o=>{o.where("f.importance","vital").orWhere("f.importance_score",5)}).orderByRaw("COALESCE(fl.access_count, 0) DESC, f.created_at DESC").limit(t).pluck("f.content")}}});function qa(){if(!Kr){for(let e of Va)Rr(e);Kr=!0}}var Va,Kr,jr=h(()=>{mt();_t();$r();St();Gr();Yr();Va=[kr,gt,Br,Hr,Wr],Kr=!1;qa()});var zr={};D(zr,{isSearchableQuery:()=>Vr,search:()=>Za});async function Za(e,{namespaces:t,limit:n=5,minConfidence:r="medium",useGraph:o=!1,includeChunks:i=!1,pointInTime:s,expand:a=!1,route:c=!0,categories:u,synthesize:m=l.search.synthesize,podScope:y=null,applyFloor:f=!0,ctx:p={}}={}){let w=Date.now();if(!Vr(e)){let g=es();return g._trace={query:e,searchable:!1,stages:[{stage:"guard",note:"query is not searchable (empty or wildcard-only)"}],durationMs:Date.now()-w},g}m&&(i=!0);let _=null;c&&(_=await gr(e),o=o||_.useGraph,a=a||_.expand,n=_.limit||n,s=s||_.pointInTime,u=u||(_.categories.length?_.categories:void 0));let b=await os(e,t),v=await rs(y,{...p,namespace:t?.[0]}),E;b?E=await is(b,e,{namespaces:t,limit:n,minConfidence:r,includeChunks:i,pointInTime:s,categories:u,podIds:v}):E=await cs(e,{namespaces:t,limit:n,minConfidence:r,useGraph:o,includeChunks:i,pointInTime:s,expand:a,categories:u,podIds:v});let R=null;if(f&&Array.isArray(E.facts)&&E.facts.length){let g=l.memory.injectionFloor,ee=E.facts.length;E.facts=E.facts.filter(ue=>{if(ue.source==="entity")return!0;let de=Number(ue.similarity);return Number.isFinite(de)?de>=g:!0}),R={threshold:g,dropped:ee-E.facts.length,kept:E.facts.length}}let P=E.facts.map(g=>g.id).filter(Boolean);if(zn(P).catch(g=>console.error("[access-tracking]",g.message)),Zn(P.slice(0,8)).catch(g=>console.error("[hebbian]",g.message)),l.hebbian.entity.enabled&&P.length>=2&&ns(P).catch(g=>console.error("[hebbian-entity]",g.message)),m)try{E.synthesized=await ts(e,E)}catch(g){console.error("[synthesizer] failed:",g.message),E.synthesized=null}return E._trace=Qa({query:e,namespaces:t,limit:n,minConfidence:r,useGraph:o,expand:a,route:c,routing:_,matchedEntity:b,podScope:y,podIds:v,result:E,factIds:P,floored:R,durationMs:Date.now()-w}),E}function Qa({query:e,namespaces:t,limit:n,minConfidence:r,useGraph:o,expand:i,route:s,routing:a,matchedEntity:c,podScope:u,podIds:m,result:y,factIds:f,floored:p,durationMs:w}){let _=E=>{let R=Number(E);return Number.isFinite(R)?Math.round(R*1e4)/1e4:null},b=(y.facts||[]).map((E,R)=>({rank:R+1,id:E.id??null,content:String(E.content||"").slice(0,240),category:E.category??null,importance:E.importance??null,confidence:E.confidence??null,source:E.source??null,similarity:_(E.similarity),rrfRaw:_(E.rrf_raw),activation:_(E.activation),accessCount:E.access_count??null,lastAccessedAt:E.lastAccessedAt??null,finalScore:_(E.final_score),rrfScore:_(E.rrfScore),coRetrievalBoost:_(E.coRetrievalBoost)})),v=(y.chunks||[]).map((E,R)=>({rank:R+1,id:E.id??null,sectionHeading:E.sectionHeading??null,content:String(E.content||"").slice(0,200),similarity:_(E.similarity),rrfScore:_(E.rrfScore)}));return{query:e,namespaces:t,durationMs:w,params:{limit:n,minConfidence:r,useGraphRequested:o,expandRequested:i,routeEnabled:s},routing:a?{intent:a.intent??null,reasoning:a.reasoning??null,useGraph:a.useGraph??null,expand:a.expand??null,limit:a.limit??null,categories:a.categories??null,pointInTime:a.pointInTime??null}:null,strategy:c?"entity-first":"standard",matchedEntity:c?{id:c.id,name:c.name,type:c.entityType,aliases:c.aliases||[]}:null,podScope:{requested:u,resolvedIds:m},floor:p?{applied:!0,threshold:p.threshold,dropped:p.dropped,kept:p.kept,note:"precision-first: facts below cosine floor dropped from injection"}:{applied:!1},ranking:{model:"RRF(vector\xD71.0 + keyword\xD70.7) \xD7 softplus(ACT-R activation) \xD7 importance \xD7 confidence",facts:b,chunks:v},synthesized:y.synthesized||null,relatedEntities:y.relatedEntities||[],reinforced:{factIds:f,note:"access_count bumped + Hebbian co-retrieval edges strengthened (off hot path)"}}}function Vr(e){let t=String(e||"").trim();return t?!/^[*%_?\s]+$/.test(t):!1}function es(){return{facts:[],chunks:[],matchedEntity:null,relatedEntities:[]}}async function ts(e,{facts:t,chunks:n}){let r=[];if(t.slice(0,10).forEach((s,a)=>{r.push(`[F${a+1}] (${s.category}) ${s.content}`)}),n.length&&n.slice(0,15).forEach((s,a)=>{let c=(s.content||"").replace(/\s+/g," ").trim();c&&r.push(`[C${a+1}] ${c.slice(0,2e3)}`)}),!r.length)return"No retrieved evidence \u2014 nothing to synthesize.";let o=`You are answering a question from a personal-memory system.
|
|
272
272
|
Each retrieved item is labeled [F#] (a stored fact) or [C#] (a raw conversation chunk
|
|
273
273
|
that may include user/assistant turns and dates).
|
|
274
274
|
|
|
@@ -283,8 +283,8 @@ Instructions:
|
|
|
283
283
|
- Reason step-by-step internally for temporal questions ("first", "before", "after", "how many days") \u2014 compare the dates explicitly.
|
|
284
284
|
- Cite items in square brackets where they directly support the answer, e.g. [C2].
|
|
285
285
|
- Only respond "Not in retrieved memory." if you genuinely cannot find the information after carefully reading every chunk. Prefer a careful answer with citation over refusal.
|
|
286
|
-
- Plain text only, no headers. Direct answer first, then a short justification if needed. 1-4 sentences total.`,i=l.search.synthesizeModel||l.llm.extractionModel||void 0;return
|
|
287
|
-
`,"utf8")}catch{}}async function
|
|
288
|
-
`),await(await Promise.resolve().then(()=>(I(),
|
|
289
|
-
`));return await(await Promise.resolve().then(()=>(I(),
|
|
290
|
-
`),await
|
|
286
|
+
- Plain text only, no headers. Direct answer first, then a short justification if needed. 1-4 sentences total.`,i=l.search.synthesizeModel||l.llm.extractionModel||void 0;return at(o,{model:i,caller:"synthesizer"})}async function ns(e){let t=await se(e.slice(0,8)),n=[];for(let o of t.values())for(let i of o)n.push(i);let r=[...new Set(n)].slice(0,l.hebbian.entity.maxWriteEntities);await st(r)}async function rs(e,t={}){if(e==null||e==="global")return null;if(e==="auto"){let r=(await Lr(t)).flatMap(i=>i.scope).filter(i=>typeof i=="string"&&!i.startsWith("__virtual:"));if(r.length===0){if(process.env.SIGIL_SCOPE_GRACE!=="false"){let i=d("pod");t.namespace&&(i=i.where({namespace:t.namespace}));let[{count:s}]=await i.count({count:"*"});if(Number(s)===0)return null}return[]}return(await d("pod").whereIn("uid",r).select("id")).map(i=>i.id)}if(Array.isArray(e)){if(e.length===0)return[];if(e.every(o=>typeof o=="number"))return e;let n=e.filter(o=>typeof o=="string");return n.length===0?[]:(await d("pod").where(function(){this.whereIn("uid",n).orWhereIn("name",n)}).select("id")).map(o=>o.id)}return null}async function os(e,t){if(e.length<2||e.length>Xa)return null;let n=t[0]||l.defaults.namespace,r=await Hn(e,n);return r||(await Gn(e,{namespace:n,limit:1}))[0]||null}async function is(e,t,{namespaces:n,limit:r,minConfidence:o,includeChunks:i,pointInTime:s,categories:a,podIds:c}){let u=as(t,e),m=await Ae(u,{inputType:"query"}),[y,f,...p]=await Promise.all([qn(e.id,{limit:r}),tr(e.id,{limit:15}),...u.map((g,ee)=>Jr(g,{queryEmbedding:m[ee],namespaces:n,limit:r,minConfidence:o,includeChunks:i,pointInTime:s,categories:a,podIds:c}))]),w=y.map(g=>({...g,source:"entity"})),_=xe(p.map(g=>g.facts),r*2),b=new Set(w.map(g=>g.id)),v=_.filter(g=>!b.has(g.id)).map(g=>({...g,source:"search"})),E=[...w,...v].slice(0,r);if(l.hebbian.entity.enabled&&E.length>=2)try{E=await qr(E,{seedEntityIds:[e.id]})}catch(g){console.error("[hebbian-entity-boost]",g.message)}let R=i?xe(p.map(g=>g.chunks||[]),r):[],P=f.map(g=>({id:g.entityId,name:g.name,type:g.entityType,relation:g.relationType,direction:g.direction,mentions:g.mentionCount}));return{facts:E,chunks:R,matchedEntity:{id:e.id,name:e.name,type:e.entityType,mentions:e.mentionCount,description:e.description||null,aliases:e.aliases||[]},relatedEntities:P}}function as(e,t){let n=[e],r=(t.aliases||[]).filter(s=>typeof s=="string"&&s.trim());if(!r.length)return n;let o=(t.name||"").trim(),i=new Set([e.toLowerCase()]);for(let s of r){let a=e;if(o){let c=new RegExp(`\\b${ss(o)}\\b`,"gi");if(c.test(a))a=a.replace(c,s);else{i.has(s.toLowerCase())||(n.push(s),i.add(s.toLowerCase()));continue}}i.has(a.toLowerCase())||(n.push(a),i.add(a.toLowerCase()))}return n}function ss(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function cs(e,{namespaces:t,limit:n,minConfidence:r,useGraph:o,includeChunks:i,pointInTime:s,expand:a=!1,categories:c,podIds:u}){let m=a?await hr(e):[e],y=await Ae(m,{inputType:"query"}),f=await Promise.all(m.map((_,b)=>Jr(_,{queryEmbedding:y[b],namespaces:t,limit:n,minConfidence:r,includeChunks:i,pointInTime:s,categories:c,podIds:u}))),p=xe(f.map(_=>_.facts),n);if(p=p.map(_=>({..._,source:"search"})),l.hebbian.entity.enabled&&p.length>=2)try{p=await qr(p)}catch(_){console.error("[hebbian-entity-boost]",_.message)}if(o&&p.length)try{let _=await ur(p.slice(0,5));if(_.length){let b=await ls(_.map(E=>E.id)),v=await dr(b,{limit:5});p=pr(p,v,b,n)}}catch(_){console.error("[graph-enhancement] Failed:",_.message)}let w=i?xe(f.map(_=>_.chunks),n):[];return{facts:p,chunks:w,matchedEntity:null,relatedEntities:[]}}async function qr(e,t={}){let n=e.map(f=>f.id).filter(Boolean);if(n.length<2)return e;let r=await se(n);if(!r.size)return e;let o,i;if(t.seedEntityIds?.length)o=t.seedEntityIds,i=e;else{let f=t.seedFactCount??3,p=[];for(let w of e.slice(0,f)){let _=r.get(w.id)||[];for(let b of _)p.push(b)}o=p,i=e.slice(f)}if(!o.length)return e;let s=new Set;for(let f of i){let p=r.get(f.id)||[];for(let w of p)s.add(w)}if(!s.size)return e;let a=await ct([...new Set(o)],[...s]);if(!a.size)return e;let c=new Map,u=0;for(let f of e){let p=r.get(f.id)||[],w=0;for(let _ of p){let b=a.get(_)||0;b>w&&(w=b)}c.set(f.id,w),w>u&&(u=w)}if(u===0)return e;let m=l.hebbian.entity.rrfWeight;return e.map(f=>{let p=(c.get(f.id)||0)/u,w=(f.rrfScore||0)+m*p;return{...f,rrfScore:Math.round(w*100)/100,coRetrievalBoost:Math.round(p*100)/100}}).sort((f,p)=>(p.rrfScore||0)-(f.rrfScore||0))}async function ls(e){let t=l.hebbian.entity.expandPerSeed;if(!t||!e.length)return e;let{getCoRetrievedEntities:n}=await Promise.resolve().then(()=>(lt(),er)),r=await Promise.all(e.map(i=>n(i,{limit:t}).catch(()=>[]))),o=new Set(e);for(let i of r)for(let s of i)o.add(Number(s.partnerId));return[...o]}function xe(e,t){let n={},r={};for(let s of e)for(let[a,c]of s.entries())r[c.id]=c,n[c.id]=(n[c.id]||0)+1/(At+a+1);let o=Object.entries(n).sort(([,s],[,a])=>a-s),i=o.length?o[0][1]:1;return o.slice(0,t).map(([s,a])=>({...r[s],rrfScore:Math.round(a/i*100)/100}))}async function Jr(e,{queryEmbedding:t,namespaces:n,limit:r,minConfidence:o,includeChunks:i=!1,pointInTime:s,categories:a,podIds:c}){let u=t||await et(e,{inputType:"query"}),m=cr(e,u,{namespaces:n,limit:r,minConfidence:o,pointInTime:s,categories:a,podIds:c}),y=i?[rr(u,{namespaces:n,limit:r}),ir(e,{namespaces:n,limit:r})]:[],[f,...p]=await Promise.all([m,...y]),w=i&&p.length===2?us(p[0],p[1],r):[];return{facts:f,chunks:w}}function us(e,t,n){let r={},o={...Ye(e,"id"),...Ye(t,"id")};e.forEach((a,c)=>{r[a.id]=(r[a.id]||0)+Ja/(At+c+1)}),t.forEach((a,c)=>{r[a.id]=(r[a.id]||0)+za/(At+c+1)});let i=Object.entries(r).sort(([a,c],[u,m])=>{if(c!==m)return m-c;let y=o[a]?.importance==="vital"?1:0;return(o[u]?.importance==="vital"?1:0)-y}),s=i.length?i[0][1]:1;return i.slice(0,n).map(([a,c])=>({...o[a],rrfScore:Math.round(c/s*100)/100}))}var At,Ja,za,Xa,Xr=h(()=>{Se();tt();S();Wn();Ne();Xn();Qn();lt();nr();Ne();or();ar();lr();mr();_r();wr();ce();jr();mt();I();At=20,Ja=1,za=.7,Xa=60});me();B();me();import{appendFile as ko,readFile as oc,writeFile as ic,unlink as ac}from"node:fs/promises";import{createHash as Bo}from"node:crypto";var $o=Tt;async function We(e,t,n=null){try{let r={ts:new Date().toISOString(),hook:e,error:F(t?.message||String(t)),input_hash:n?Fo(n):null};await ko($o,JSON.stringify(r)+`
|
|
287
|
+
`,"utf8")}catch{}}async function tn(e,t=null){try{let{validateConfig:n}=await Promise.resolve().then(()=>(en(),Qt)),r=n().filter(o=>o.level==="fail");if(r.length===0)return!1;for(let o of r){let i=new Error(`${o.code}: ${o.message} \u2014 fix: ${o.fix}`);await We(e,i,t)}return!0}catch{return!1}}function Fo(e){try{let t=typeof e=="string"?e:JSON.stringify(e);return Bo("sha256").update(t).digest("hex").slice(0,12)}catch{return null}}B();import{resolve as Uo}from"node:path";import{existsSync as nn}from"node:fs";import{config as rn}from"dotenv";function on(){let e=Uo(process.cwd(),".env");nn(e)&&rn({path:e,quiet:!0}),nn(x)&&x!==e&&rn({path:x,quiet:!0}),process.env.SIGIL_AGENT||(process.env.SIGIL_AGENT="claude-code")}on();var ds=8,ps=20,ms=4800;async function fs(){let e=[];for await(let o of process.stdin)e.push(o);let t=Buffer.concat(e).toString("utf8").trim();if(!t)return G();let n=JSON.parse(t),r=n.prompt||"";if(r.length<ds||await tn("user-prompt-submit",t))return G();try{let{search:o}=await Promise.resolve().then(()=>(Xr(),zr)),i=(await Promise.resolve().then(()=>(S(),Bt))).default,s;try{s=await o(r,{namespaces:[i.defaults.namespace],limit:ps,useGraph:!1,route:!0,expand:!0,synthesize:!1,podScope:"auto",ctx:{cwd:n.cwd||null,sessionId:n.session_id||null}})}catch(f){return process.stderr.write(`[sigil:user-prompt-submit] scoped search failed: ${F(f.message)}
|
|
288
|
+
`),await(await Promise.resolve().then(()=>(I(),K))).default.destroy().catch(()=>{}),G()}let a=s?.facts||[];if(!a.length)return await(await Promise.resolve().then(()=>(I(),K))).default.destroy(),G();let c=[],u=0;for(let f of a){let p=(f.content||"").length+4;if(c.length>0&&u+p>ms)break;c.push(f),u+=p}let m=F([`Sigil memory (${c.length} relevant facts):`,...c.map(f=>`- ${f.content}`)].join(`
|
|
289
|
+
`));return await(await Promise.resolve().then(()=>(I(),K))).default.destroy(),G(m)}catch(o){process.stderr.write(`[sigil:user-prompt-submit] ${F(o.message)}
|
|
290
|
+
`),await We("user-prompt-submit",o,t);try{await(await Promise.resolve().then(()=>(I(),K))).default.destroy()}catch{}return G()}}function G(e){let t={hookSpecificOutput:{hookEventName:"UserPromptSubmit",...e&&{additionalContext:e}}};process.stdout.write(JSON.stringify(t))}fs();
|