@anmol-srv/sigil 0.12.2 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +359 -373
- package/dist/daemon.js +151 -165
- package/dist/hooks/post-tool-use.js +25 -22
- package/dist/hooks/session-end.js +76 -73
- package/dist/hooks/stop.js +72 -69
- package/dist/hooks/user-prompt-submit.js +48 -45
- package/dist/server.js +46 -41
- package/package.json +1 -1
- package/src/db/migrations/20260429120200_upgrade-embedding-dim-1024.cjs +11 -22
- package/src/gui/web/app.css +102 -0
- package/src/gui/web/app.js +84 -557
- package/src/gui/web/index.html +18 -185
- package/src/gui/web/setup.js +445 -0
|
@@ -1,64 +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
|
|
3
|
+
var Xr=Object.defineProperty;var h=(e,t)=>()=>(e&&(t=e(e=0)),t);var D=(e,t)=>{for(var n in t)Xr(e,n,{get:t[n],enumerable:!0})};function Q(e){if(!e||typeof e!="string")return e;let t=e;for(let n of Zr)t=t.replace(n,Z);return t=t.replace(Qr,(n,r)=>`${r}=${Z}`),t=t.replace(eo,(n,r)=>`${r}${Z}:${Z}@`),t=t.replace(no,(n,r)=>`${r}=${Z}`),t}var Z,Zr,Qr,eo,to,no,ue=h(()=>{Z="***MASKED***",Zr=[/\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],Qr=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"),eo=/(\w+:\/\/)([^:/\s]+):([^@\s]{3,})@/g,to=["DATABASE_URL","REDIS_URL","MONGODB_URI","MONGO_URI","POSTGRES_URL","DSN","CONNECTION_STRING","ENCRYPTION_KEY","JWT_SECRET","SIGIL_ENCRYPTION_KEY","SESSION_SECRET","WEBHOOK_SECRET"],no=new RegExp(`\\b(${to.join("|")})\\s*[=:]\\s*["']?([^\\s"']+)["']?`,"gi")});import{fileURLToPath as ro}from"node:url";import{dirname as At,join as S}from"node:path";import{existsSync as It}from"node:fs";import{homedir as oo}from"node:os";function io(){let e=At(ro(import.meta.url));for(let t=0;t<10;t++){if(It(S(e,"package.json"))&&It(S(e,"prompts")))return e;let n=At(e);if(n===e)break;e=n}return process.cwd()}var de,pe,fs,bt,N,x,k,hs,_s,ao,Ot,so,Tt,Es,ys,gs,ws,Ss,As,Is,bs,Os,Ts,Ds,Dt,Ns,Rs,B=h(()=>{de=io(),pe=S(de,"prompts"),fs=S(de,"src","db","migrations"),bt=oo(),N=S(bt,".sigil"),x=S(N,".env"),k=S(N,"config.json"),hs=S(N,"db"),_s=S(N,"CLAUDE.md"),ao=S(N,"schemas"),Ot=S(N,".hook-errors.log"),so=S(N,".last-clean-doctor"),Tt=S(N,".active-session.json"),Es=S(N,".stop-cursor.json"),ys=S(N,".hook-dedup.json"),gs=S(N,"sock"),ws=S(N,"sigild.pid"),Ss=S(N,"sigild.log"),As=S(N,"heartbeat.json"),Is=S(N,"gui.token"),bs=S(de,"dist","gui"),Os=S(de,"src","gui","web"),Ts=S(N,"iroh"),Ds=S(N,"identity.key"),Dt=S(bt,".claude"),Ns=S(Dt,"settings.json"),Rs=S(Dt,"CLAUDE.md")});var Me=h(()=>{});import{existsSync as xe,readFileSync as vt,writeFileSync as co,renameSync as Ct,mkdirSync as lo,chmodSync as uo,unlinkSync as Ps}from"node:fs";import{dirname as po}from"node:path";function me(){return{schemaVersion:ke,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 H(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Be(e,t){if(!H(t))return t;let n=Array.isArray(e)?[...e]:{...e};for(let[r,o]of Object.entries(t))n[r]=H(o)&&H(n[r])?Be(n[r],o):o;return n}function $e(){if(!xe(k))return{};try{return JSON.parse(vt(k,"utf8"))||{}}catch{return{}}}function fo(e){let t=e,n=Number(t.schemaVersion)||1;for(;n<ke;){let r=n+1,o=mo[r];t=o?o(t):{...t,schemaVersion:r},n=r}return t}function fe(e){let t=me(),n={};for(let r of Object.keys(t)){if(!(r in e))continue;if(!H(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"&&H(e.setup?.steps)&&(o.steps=e.setup.steps),n[r]=o}return n}function Pt(e){lo(po(k),{recursive:!0});let t=`${k}.tmp`;co(t,`${JSON.stringify(e,null,2)}
|
|
4
|
+
`,{mode:384}),Ct(t,k);try{uo(k,384)}catch{}}function ho(e,t){let n={};if(!H(t))throw new Error(`config patch for "${e}" must be an object`);if(e==="database"&&("mode"in t&&t.mode!==null&&!Nt.includes(t.mode)&&(n.mode=`must be one of ${Nt.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 _o(e){if(!xe(e))return null;let t={};for(let n of vt(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 Eo(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 yo(){if(!Rt){Rt=!0;try{let e=_o(x);if(!e)return;let t=Eo(e),n=fe($e()),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{wo(o,i)}catch{}try{Ct(x,`${x}.migrated`)}catch{}}catch{}}}function go(){yo();let e=$e(),t=fo(e);return xe(k)&&t.schemaVersion!==e.schemaVersion&&Pt(fe(t)),ee=Be(me(),fe(t)),ee}function Mt(){return ee||go()}function wo(e,t){if(!(e in me()))throw new Error(`unknown config section: ${e}`);ho(e,t);let n=fe($e());return n.schemaVersion=ke,n[e]={...n[e]||{},...t},Pt(n),ee=Be(me(),n),ee}var ke,Nt,mo,ee,Rt,xt=h(()=>{B();Me();ke=1,Nt=["local","docker","url"];mo={},ee=null;Rt=!1});var Bt={};D(Bt,{default:()=>l});var O,T,Fe,he,Ue,kt,So,l,A=h(()=>{xt();Me();O=(e,t)=>process.env[e]??t,T=()=>Mt(),Fe=e=>T().llm.provider===e&&T().llm.apiKey||"",he=e=>T().llm.provider===e&&T().llm.model||"",Ue=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.
|
|
4
6
|
PGlite was deprecated; existing PGlite data at ~/.sigil/db is preserved but unreachable from this version.
|
|
5
7
|
Set SIGIL_DB_TYPE=postgres in ~/.sigil/.env and configure SIGIL_DB_HOST / PORT / NAME / USER / PASSWORD.
|
|
6
|
-
Run \`sigil init\` for an interactive setup.`);
|
|
7
|
-
`)[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.`);So={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||"nomic-embed-text"},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||Ue("openai")},get voyageApiKey(){return process.env.VOYAGE_API_KEY||Ue("voyage")},get openrouterApiKey(){return process.env.OPENROUTER_API_KEY||Ue("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||Fe("openai")},get openaiModel(){return process.env.LLM_OPENAI_MODEL||he("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||he("ollama")||"qwen2.5:7b"},get cliModel(){return process.env.LLM_CLI_MODEL||he("claude-cli")||"haiku"},get cliPath(){return process.env.LLM_CLI_PATH||""},get apiKey(){return process.env.ANTHROPIC_API_KEY||Fe("anthropic")},get openrouterApiKey(){return process.env.OPENROUTER_API_KEY||Fe("openrouter")},get openrouterModel(){return process.env.LLM_OPENROUTER_MODEL||he("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}},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=So});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=Io(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 Io(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 Ao.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 Ao,Ut,Wt=h(()=>{Ao=[/\.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 Yt(e){let t=e.db.url;return t?{kind:"url",provider:Gt(t),connection:Ht(t)}:{kind:"local",provider:"local",connection:$t(e)}}var Kt=h(()=>{Ft();Wt()});var G={};D(G,{default:()=>d});import bo from"knex";function Oo(e){return Array.isArray(e)?e.map(He):e&&typeof e=="object"?He(e):e}function To(e,t){return t(Do(e))}function He(e){if(!e||typeof e!="object"||e instanceof Date)return e;if(Array.isArray(e))return e.map(He);let t={};for(let[n,r]of Object.entries(e))t[n.replace(/_([a-z])/g,(o,i)=>i.toUpperCase())]=r;return t}function Do(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}var jt,Vt,d,I=h(()=>{A();Kt();jt=Yt(l),Vt=bo({client:"pg",connection:jt.connection,pool:{min:2,max:10},postProcessResponse:Oo,wrapIdentifier:To});Vt.__sigilDriver=jt;d=Vt});var Zt={};D(Zt,{validateConfig:()=>Xt,validateConfigDeep:()=>No});function Xt(){let e=[];return Ro(e),Lo(e),vo(e),e}async function No(){let e=Xt();if(l.db.type==="postgres"&&!e.some(t=>t.code.startsWith("DB_")))try{await(await Promise.resolve().then(()=>(I(),G))).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 Ro(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:Co(t,n,r)})}if(t&&zt[t]){let r=zt[t];l.embedding[r]||e.push({level:"fail",code:"EMBEDDING_PROVIDER_MISSING_KEY",message:`EMBEDDING_PROVIDER=${t} but no ${_e(r)} found.`,fix:`Set ${_e(r)} in ~/.sigil/.env, or run 'sigil init' to reconfigure.`})}}function Lo(e){let{provider:t}=l.llm;if(t&&qt[t]){let n=qt[t];l.llm[n]||e.push({level:"fail",code:"LLM_PROVIDER_MISSING_KEY",message:`LLM_PROVIDER=${t} but no ${_e(n)} found.`,fix:`Set ${_e(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 vo(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 _e(e){return{openaiApiKey:"OPENAI_API_KEY",apiKey:"ANTHROPIC_API_KEY",openrouterApiKey:"OPENROUTER_API_KEY",voyageApiKey:"VOYAGE_API_KEY"}[e]||e}function Co(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,qt,zt,Qt=h(()=>{A();Jt={voyage:[/^voyage-/],openai:[/^text-embedding-/],ollama:[/^nomic-embed/,/^mxbai-embed/,/^all-minilm/,/^bge-/,/^snowflake-/,/^granite-embedding/]},qt={openai:"openaiApiKey",anthropic:"apiKey",openrouter:"openrouterApiKey"},zt={openai:"openaiApiKey",voyage:"voyageApiKey",openrouter:"openrouterApiKey"}});function We(e,t){let n={};for(let r of e)n[r[t]]=r;return n}function Ee(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 ye=h(()=>{});var on={};D(on,{chat:()=>$o,meta:()=>Fo,setup:()=>Uo});async function $o(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",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 Uo({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 Fo,an=h(()=>{A();Fo={id:"openai",label:"OpenAI",hint:"gpt-4o-mini"}});function P(e){return Math.ceil((e||"").length/4)}function Ye(e,t,n){let r=Ho[e];return r?(t*r.input+n*r.output)/1e6:0}function te({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))}async function Ke(e,t=3){for(let n=1;n<=t;n++)try{return await e()}catch(r){if(n===t)throw r;let o=Math.min(1e3*2**(n-1),1e4);await new Promise(i=>setTimeout(i,o))}}var Ho,ne=h(()=>{I();Ho={"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 sn={};D(sn,{chat:()=>Wo,meta:()=>Yo,setup:()=>Ko});async function Go(){if(!je){let{default:e}=await import("@anthropic-ai/sdk");je=new e({apiKey:l.llm.apiKey})}return je}async function Wo(e,{model:t,jsonMode:n=!1}={}){let r=t||"claude-haiku-4-5-20251001",o=await Go(),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||P(e),outputTokens:a.usage?.output_tokens||P(a.content[0].text),model:r}}async function Ko({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 je,Yo,cn=h(()=>{A();ne();je=null;Yo={id:"anthropic",label:"Anthropic",hint:"Claude Haiku \u2014 requires API key"}});var un={};D(un,{chat:()=>Vo,meta:()=>Jo,setup:()=>qo});async function Vo(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||jo).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",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 qo({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||ln,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||ln;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||W.extraction});if(t.isCancel(c))return null;n.LLM_EXTRACTION_MODEL=c||e.LLM_EXTRACTION_MODEL||W.extraction;let u=await t.text({message:"Decision model (AUDM; smart matters)",placeholder:e.LLM_DECISION_MODEL||W.decision});if(t.isCancel(u))return null;n.LLM_DECISION_MODEL=u||e.LLM_DECISION_MODEL||W.decision;let m=await t.text({message:"Synthesis model (read-time answer composition)",placeholder:e.SIGIL_SYNTH_MODEL||W.synthesis});if(t.isCancel(m))return null;n.SIGIL_SYNTH_MODEL=m||e.SIGIL_SYNTH_MODEL||W.synthesis}return t.note(`OpenRouter can drive both LLM calls and embeddings.
|
|
8
10
|
You will pick an embedding provider in the next step \u2014 "openrouter" is an option,
|
|
9
|
-
or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"OpenRouter scope"),{env:n}}var
|
|
11
|
+
or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"OpenRouter scope"),{env:n}}var jo,Jo,ln,W,dn=h(()=>{A();jo="https://openrouter.ai/api/v1";Jo={id:"openrouter",label:"OpenRouter",hint:"one key, many models (Anthropic / OpenAI / Meta / ...)"},ln="google/gemini-flash-latest",W={extraction:"openrouter:qwen/qwen3.5-flash",decision:"openrouter:anthropic/claude-sonnet-latest",synthesis:"openrouter:anthropic/claude-sonnet-latest"}});var mn={};D(mn,{chat:()=>oi,meta:()=>ii,setup:()=>ai});import{spawn as zo,spawnSync as Xo}from"node:child_process";import{existsSync as pn}from"node:fs";import{homedir as Zo}from"node:os";import{dirname as Qo,join as Ve}from"node:path";function ei(){if(Y)return Y;if(l.llm.cliPath)return Y=l.llm.cliPath;let e=Zo(),t=[Ve(Qo(process.execPath),"claude"),Ve(e,".local","bin","claude"),Ve(e,".claude","local","claude"),"/opt/homebrew/bin/claude","/usr/local/bin/claude","/usr/bin/claude"];for(let r of t)if(pn(r))return Y=r;let n=ti("claude");return n?Y=n:Y="claude"}function ti(e){let t=process.env.SHELL||"/bin/sh";try{let r=(Xo(t,["-lic",`command -v ${e}`],{encoding:"utf8",timeout:5e3}).stdout||"").trim().split(`
|
|
12
|
+
`).pop().trim();return r&&pn(r)?r:null}catch{return null}}function ri(e,t){let n=l.llm.cliTimeout||12e4,r=ei();return new Promise((o,i)=>{let s=zo(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 oi(e,{model:t,jsonMode:n=!1}={}){let r=t||l.llm.cliModel||"haiku",o=ni[r]||r,i=["-p","--model",o,"--output-format","json"],{stdout:s,stderr:a,code:c}=await ri(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:P(e),outputTokens:P(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||P(e),outputTokens:y.output_tokens||P(m),model:o,cost:u.total_cost_usd||0}}async function ai(){return{env:{}}}var Y,ni,ii,fn=h(()=>{A();ne();Y=null;ni={"claude-haiku-4-5-20251001":"haiku","claude-sonnet-4-6":"sonnet","claude-opus-4-6":"opus"};ii={id:"claude-cli",label:"Claude Code",hint:"uses your existing subscription \u2014 no extra API key"}});var hn={};D(hn,{chat:()=>si,meta:()=>ci,setup:()=>li});async function si(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",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||P(e),outputTokens:a.eval_count||P(a.message.content),model:r}}async function li({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 ci,_n=h(()=>{A();ne();ci={id:"ollama",label:"Ollama",hint:"local models \u2014 no API cost"}});var En={};D(En,{embedBatch:()=>di});async function di(e,{model:t,ollamaHost:n}){let r=Ee(e,ui),o=[];for(let i of r){let s=await fetch(`${n}/api/embed`,{method:"POST",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 ui,yn=h(()=>{ye();ui=50});var gn={};D(gn,{embedBatch:()=>pi});async function pi(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",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 wn=h(()=>{});var Sn={};D(Sn,{embedBatch:()=>fi});async function fi(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=Ee(e,mi),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",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 mi,An=h(()=>{ye();mi=50});var In={};D(In,{embedBatch:()=>_i});async function _i(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||hi).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",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 hi,bn=h(()=>{hi="https://openrouter.ai/api/v1"});import{spawn as Ei}from"node:child_process";async function Xe(e){if(!Je[e]){let t=ze[e];if(!t)throw new Error(`Unknown LLM provider: "${e}". Available: ${Object.keys(ze).join(", ")}`);let n=await t();Je[e]=n.chat}return Je[e]}async function Tn(e){if(!qe[e]){let t=On[e];if(!t)throw new Error(`Unknown embedding provider: "${e}". Available: ${Object.keys(On).join(", ")}`);let n=await t();qe[e]=n.embedBatch}return qe[e]}function Dn(e,t){if(!e)return{provider:t,model:null};let n=e.indexOf(":");return n>0&&ze[e.slice(0,n)]?{provider:e.slice(0,n),model:e.slice(n+1)}:{provider:t,model:e}}async function Nn(){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 yi(){return new Promise(e=>{let t=Ei("claude",["--version"],{stdio:"pipe"});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0)),setTimeout(()=>{t.kill(),e(!1)},3e3)})}async function Rn(){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 Nn())return L="ollama",L;if(await yi())return L="claude-cli",L;throw new Error(`No LLM provider available. Either:
|
|
10
13
|
- Set LLM_PROVIDER (openai, anthropic, openrouter, ollama, claude-cli)
|
|
11
14
|
- Set ANTHROPIC_API_KEY, OPENAI_API_KEY, or OPENROUTER_API_KEY
|
|
12
15
|
- Start Ollama locally
|
|
13
|
-
- Install the Claude CLI (claude)`)}async function
|
|
16
|
+
- Install the Claude CLI (claude)`)}async function Ln(){if(C)return C;if(l.embedding.provider)return C=l.embedding.provider,C;if(l.embedding.voyageApiKey)return C="voyage",C;if(await Nn())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:
|
|
14
17
|
- Set EMBEDDING_PROVIDER (voyage, ollama, openai, openrouter)
|
|
15
18
|
- Set VOYAGE_API_KEY (recommended \u2014 best quality)
|
|
16
19
|
- Start Ollama locally
|
|
17
20
|
- Set OPENAI_API_KEY
|
|
18
|
-
- 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 ze,On,Je,qe,L,C,Ze=h(()=>{A();ze={openai:()=>Promise.resolve().then(()=>(an(),on)),anthropic:()=>Promise.resolve().then(()=>(cn(),sn)),openrouter:()=>Promise.resolve().then(()=>(dn(),un)),"claude-cli":()=>Promise.resolve().then(()=>(fn(),mn)),ollama:()=>Promise.resolve().then(()=>(_n(),hn))},On={ollama:()=>Promise.resolve().then(()=>(yn(),En)),openai:()=>Promise.resolve().then(()=>(wn(),gn)),voyage:()=>Promise.resolve().then(()=>(An(),Sn)),openrouter:()=>Promise.resolve().then(()=>(bn(),In))},Je={},qe={};L=null,C=null});function $(e){return e?`[${e.join(",")}]`:null}function vn(){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 K(e="embedding"){return`(${e}::halfvec(${vn()}))`}function j(){return`?::halfvec(${vn()})`}var V=h(()=>{A()});import{createHash as gi}from"node:crypto";function Si(e,t,n,r="document"){let o=gi("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 Ai(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,Ii(n.embedding)]))}function Ii(e){return Array.isArray(e)||typeof e!="string"?e:(e.startsWith("[")?e.slice(1,-1):e).split(",").map(Number)}async function bi(e){e.length&&await d("embedding_cache").whereIn("key",e).update({hits:d.raw("hits + 1"),lastUsedAt:d.fn.now()})}async function Oi(e,t,n){if(e.length){for(let{key:r,embedding:o}of e)await d.raw(`
|
|
19
22
|
INSERT INTO embedding_cache (key, provider, model, embedding, hits, created_at, last_used_at)
|
|
20
23
|
VALUES (?, ?, ?, ?, 0, NOW(), NOW())
|
|
21
24
|
ON CONFLICT (key) DO UPDATE
|
|
22
25
|
SET last_used_at = NOW(),
|
|
23
26
|
hits = embedding_cache.hits + 1
|
|
24
|
-
`,[r,t,n
|
|
27
|
+
`,[r,t,n,$(o)]);await Di()}}async function Di(){let e=Date.now();if(e-Pn<Ti)return;Pn=e;let[{count:t}]=await d("embedding_cache").count("key as count"),n=Number(t);if(n<=Cn)return;let r=Math.min(n-Cn,wi);await d.raw(`
|
|
25
28
|
DELETE FROM embedding_cache WHERE key IN (
|
|
26
29
|
SELECT key FROM embedding_cache ORDER BY last_used_at ASC LIMIT ?
|
|
27
30
|
)
|
|
28
|
-
`,[r])}async function
|
|
29
|
-
`)})}let
|
|
31
|
+
`,[r])}async function Mn(e,t,n,r,o,i={}){if(!e.length)return[];let s=i.inputType||o?.inputType||"document",a=e.map(p=>Si(t,n,p,s)),c=await Ai(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[_]})}Oi(w,t,n).catch(_=>{process.stderr.write(`[embedding-cache] store failed: ${_.message}
|
|
32
|
+
`)})}let f=a.filter(p=>c.has(p));return f.length&&bi(f).catch(()=>{}),y}var Cn,wi,Pn,Ti,xn=h(()=>{V();I();Cn=1e4,wi=500;Pn=0,Ti=6e4});async function Qe(e,t={}){let[n]=await ge([e],t);return n}async function ge(e,{inputType:t="document",cache:n=!0}={}){if(!e.length)return[];let r=await Ln(),o=await Tn(r),i=l.embedding.model,s={...l.embedding,inputType:t};return n?Mn(e,r,i,o,s,{inputType:t}):o(e,s)}var $c,et=h(()=>{A();Ze();xn();({dimensions:$c}=l.embedding)});var kn,Bn=h(()=>{kn="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"});import{webcrypto as $n}from"node:crypto";function Ri(e){if(e<0||e>1024)throw new RangeError("Wrong ID size");!F||F.length<e?(F=Buffer.allocUnsafe(e*Ni),$n.getRandomValues(F),J=0):J+e>F.length&&($n.getRandomValues(F),J=0),J+=e}function we(e=21){Ri(e|=0);let t="";for(let n=J-e;n<J;n++)t+=kn[F[n]&63];return t}var Ni,F,J,tt=h(()=>{Bn();Ni=128});async function Fn(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 Un(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 Hn=h(()=>{I();V();A()});async function Se({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-${we(16)}`,u=r||l.defaults.namespace,{rows:[m]}=await d.raw(`
|
|
30
33
|
INSERT INTO pod (uid, pod_type, name, namespace, attrs, entity_id, connection_id, external_id, started_at, created_at, updated_at)
|
|
31
34
|
VALUES (?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, NOW(), NOW())
|
|
32
35
|
ON CONFLICT (pod_type, external_id, namespace) WHERE external_id IS NOT NULL DO UPDATE SET
|
|
33
36
|
attrs = pod.attrs || EXCLUDED.attrs,
|
|
34
37
|
updated_at = NOW()
|
|
35
38
|
RETURNING *, (xmax = 0) AS "isNew"
|
|
36
|
-
`,[c,e,n,u,JSON.stringify(o),i,s,t,a]);return{pod:
|
|
39
|
+
`,[c,e,n,u,JSON.stringify(o),i,s,t,a]);return{pod:m,isNew:m.isNew}}async function nt(e){return d("pod").where({uid:e}).first()||null}async function Gn({podType:e,externalId:t,namespace:n}){return d("pod").where({podType:e,externalId:t,namespace:n||l.defaults.namespace}).first()||null}async function rt(e,t){await d.raw("UPDATE pod SET attrs = attrs || ?::jsonb, updated_at = NOW() WHERE id = ?",[JSON.stringify(t),e])}async function Wn(e,t=new Date){await d("pod").where({id:e}).update({endedAt:t,updatedAt:d.fn.now()})}async function re(e,{docs:t=0,facts:n=0}){!t&&!n||await d.raw(`UPDATE pod
|
|
37
40
|
SET member_doc_count = member_doc_count + ?,
|
|
38
41
|
member_fact_count = member_fact_count + ?,
|
|
39
42
|
updated_at = NOW()
|
|
40
|
-
WHERE id = ?`,[t,n,e])}var
|
|
43
|
+
WHERE id = ?`,[t,n,e])}var Ae=h(()=>{tt();I();A()});var be={};D(be,{attach:()=>Ie,attachDocument:()=>Li,attachEntity:()=>vi,attachFact:()=>Kn,detach:()=>Ci,factIdsInPod:()=>xi,listMembers:()=>Pi,listPodsForMember:()=>Mi});async function Ie(e,t,n,r="primary"){let{rowCount:o}=await d.raw(`INSERT INTO pod_membership (pod_id, member_type, member_id, role)
|
|
41
44
|
VALUES (?, ?, ?, ?)
|
|
42
|
-
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 re(e,{facts:1}):t==="document"&&await re(e,{docs:1})),{attached:o>0}}async function Ci(e,t,n){let r=await d("pod_membership").where({podId:e,memberType:t,memberId:n}).del();return r>0&&(t==="fact"?await re(e,{facts:-1}):t==="document"&&await re(e,{docs:-1})),{detached:r>0}}async function Pi(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 Mi(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 xi(e){return await d("pod_membership").where({podId:e,memberType:"fact"}).pluck("memberId")}var Kn,Li,vi,ot=h(()=>{I();Ae();Kn=(e,t,n)=>Ie(e,"fact",t,n),Li=(e,t,n)=>Ie(e,"document",t,n),vi=(e,t,n)=>Ie(e,"entity",t,n)});async function jn(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 oe(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 Oe=h(()=>{I();ot()});async function Vn(e){let t=await Rn();return Dn(e,t)}async function it(e,{model:t,caller:n}={}){let{provider:r,model:o}=await Vn(t),i=await Xe(r),s=Date.now();try{let a=await Ke(()=>i(e,{model:o,jsonMode:!1}),l.llm.maxRetries),c=a.cost||Ye(a.model,a.inputTokens,a.outputTokens);return te({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 te({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 Te(e,{model:t,caller:n}={}){let{provider:r,model:o}=await Vn(t),i=await Xe(r),s=Date.now();try{let a=await Ke(()=>i(e,{model:o,jsonMode:!0}),l.llm.maxRetries),c=a.cost||Ye(a.model,a.inputTokens,a.outputTokens);return te({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"}),ki(a.text)}catch(a){throw te({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 ki(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 ie=h(()=>{A();Ze();ne()});import Bi from"node:path";async function Jn(e){e.length&&await d.raw(`UPDATE fact_lifecycle
|
|
43
46
|
SET access_count = access_count + 1,
|
|
44
47
|
last_accessed_at = NOW(),
|
|
45
48
|
stage = CASE WHEN stage = 'stable' THEN 'editing' ELSE stage END,
|
|
46
49
|
stage_entered_at = CASE WHEN stage = 'stable' THEN NOW() ELSE stage_entered_at END
|
|
47
|
-
WHERE fact_id = ANY(?)`,[e])}var
|
|
50
|
+
WHERE fact_id = ANY(?)`,[e])}var ml,fl,hl,qn=h(()=>{I();et();ie();V();ue();A();B();ml=Bi.join(pe,"audm-decision.md"),fl=l.memory.skipThreshold,hl=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(`
|
|
48
51
|
INSERT INTO hebbian_edge (fact_a_id, fact_b_id, strength, first_seen_at, last_seen_at)
|
|
49
52
|
VALUES ${r}
|
|
50
53
|
ON CONFLICT (fact_a_id, fact_b_id)
|
|
51
54
|
DO UPDATE SET
|
|
52
55
|
strength = hebbian_edge.strength + 1,
|
|
53
56
|
last_seen_at = NOW()
|
|
54
|
-
`,o)}var
|
|
57
|
+
`,o)}var Xn=h(()=>{I()});var Zn={};D(Zn,{consolidateEntityCoRetrievalEdges:()=>Ui,getCoRetrievedEntities:()=>Fi,getEdgeStrengthsForRanking:()=>st,getEntityHebbianStats:()=>Hi,strengthenEntityEdges:()=>at});function De(e){return $i/Math.max(e,1)}async function at(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(`
|
|
55
58
|
INSERT INTO entity_hebbian_edge (entity_a_id, entity_b_id, strength, first_seen_at, last_seen_at)
|
|
56
59
|
VALUES ${s}
|
|
57
60
|
ON CONFLICT (entity_a_id, entity_b_id)
|
|
58
61
|
DO UPDATE SET
|
|
59
62
|
strength = LEAST(entity_hebbian_edge.strength + ?, ?),
|
|
60
63
|
last_seen_at = NOW()
|
|
61
|
-
`,[...a,n,r])}async function
|
|
64
|
+
`,[...a,n,r])}async function Fi(e,t={}){if(!l.hebbian.entity.enabled)return[];let n=t.limit??10,r=t.minEffectiveStrength??l.hebbian.entity.minEffective,o=De(t.halfLifeDays??l.hebbian.entity.halfLifeDays),{rows:i}=await d.raw(`
|
|
62
65
|
SELECT
|
|
63
66
|
CASE WHEN entity_a_id = ? THEN entity_b_id ELSE entity_a_id END AS "partnerId",
|
|
64
67
|
(strength * EXP(-1.0 * ?::float8 * EXTRACT(EPOCH FROM (NOW() - last_seen_at)) / 86400.0))::float8 AS "effectiveStrength",
|
|
@@ -68,7 +71,7 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
68
71
|
WHERE entity_a_id = ? OR entity_b_id = ?
|
|
69
72
|
ORDER BY "effectiveStrength" DESC
|
|
70
73
|
LIMIT ?
|
|
71
|
-
`,[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 st(e,t,n={}){if(!l.hebbian.entity.enabled)return new Map;if(!e.length||!t.length)return new Map;let r=De(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(`
|
|
72
75
|
SELECT
|
|
73
76
|
CASE
|
|
74
77
|
WHEN entity_a_id = ANY(?::bigint[]) THEN entity_b_id
|
|
@@ -81,12 +84,12 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
81
84
|
OR
|
|
82
85
|
(entity_b_id = ANY(?::bigint[]) AND entity_a_id = ANY(?::bigint[]))
|
|
83
86
|
GROUP BY "candidateId"
|
|
84
|
-
`,[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 Ui({floor:e=.5,decayDays:t=90}={}){let n=De(l.hebbian.entity.halfLifeDays),{rows:r}=await d.raw(`
|
|
85
88
|
DELETE FROM entity_hebbian_edge
|
|
86
89
|
WHERE (strength * EXP(-1.0 * ?::float8 * EXTRACT(EPOCH FROM (NOW() - last_seen_at)) / 86400.0)) <= ?
|
|
87
90
|
AND last_seen_at < NOW() - (INTERVAL '1 day' * ?)
|
|
88
91
|
RETURNING entity_a_id
|
|
89
|
-
`,[n,e,t]);return r.length}async function
|
|
92
|
+
`,[n,e,t]);return r.length}async function Hi({topN:e=5}={}){let t=De(l.hebbian.entity.halfLifeDays),n=await d.raw(`
|
|
90
93
|
SELECT
|
|
91
94
|
COUNT(*)::int AS "edgeCount",
|
|
92
95
|
COALESCE(AVG(strength)::float8, 0) AS "avgStrength",
|
|
@@ -103,7 +106,7 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
103
106
|
JOIN entity eb ON eb.id = entity_b_id
|
|
104
107
|
ORDER BY "decayed" DESC
|
|
105
108
|
LIMIT ?
|
|
106
|
-
`,[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 $i,ct=h(()=>{I();A();$i=Math.log(2)});async function Qn(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(`
|
|
107
110
|
SELECT r.id AS "relationId", r.relation_type AS "relationType",
|
|
108
111
|
r.mention_count AS "mentionCount", r.valid_at AS "validAt",
|
|
109
112
|
e.id AS "entityId", e.uid, e.name, e.entity_type AS "entityType",
|
|
@@ -116,11 +119,11 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
116
119
|
${n?"AND r.relation_type = ?":""}
|
|
117
120
|
ORDER BY r.mention_count DESC
|
|
118
121
|
LIMIT ?
|
|
119
|
-
`,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 er=h(()=>{I()});function Ne({minConfidence:e="medium",pointInTime:t,categories:n}){let r=Gi[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 Gi,ae,Re=h(()=>{Gi={low:0,medium:1,high:2},ae=`CASE confidence
|
|
120
123
|
WHEN 'high' THEN 2
|
|
121
124
|
WHEN 'medium' THEN 1
|
|
122
125
|
ELSE 0
|
|
123
|
-
END`});async function
|
|
126
|
+
END`});async function tr(e,{namespaces:t,limit:n=20}){let r=$(e),o=`${K("embedding")} <=> ${j()}`,{rows:i}=await d.raw(`
|
|
124
127
|
SELECT id, document_id AS "documentId", chunk_index AS "chunkIndex",
|
|
125
128
|
content, section_heading AS "sectionHeading", namespace,
|
|
126
129
|
1 - (${o}) as similarity
|
|
@@ -129,7 +132,7 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
129
132
|
AND embedding IS NOT NULL
|
|
130
133
|
ORDER BY ${o}
|
|
131
134
|
LIMIT ?
|
|
132
|
-
`,[r,t,r,n]);return i}var
|
|
135
|
+
`,[r,t,r,n]);return i}var nr=h(()=>{I();V();A();Re()});async function rr(e,{namespaces:t,limit:n=20}){let{rows:r}=await d.raw(`
|
|
133
136
|
SELECT id, document_id AS "documentId", chunk_index AS "chunkIndex",
|
|
134
137
|
content, section_heading AS "sectionHeading", namespace,
|
|
135
138
|
ts_rank(search_vector, plainto_tsquery('english', ?)) as rank
|
|
@@ -138,10 +141,10 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
138
141
|
AND search_vector @@ plainto_tsquery('english', ?)
|
|
139
142
|
ORDER BY rank DESC
|
|
140
143
|
LIMIT ?
|
|
141
|
-
`,[e,t,e,n]);return r}var
|
|
144
|
+
`,[e,t,e,n]);return r}var or=h(()=>{I();Re()});async function ar(e,t,{namespaces:n,limit:r=5,minConfidence:o="medium",pointInTime:i,categories:s,podIds:a=null}){let c=$(t),u=`${K("embedding")} <=> ${j()}`,{temporalClause:m,categoryClause:y,filterParams:f}=Ne({minConfidence:o,pointInTime:i,categories:s}),p=r*Vi,w=Array.isArray(a),_=w&&a.length===0,b=w?_?"AND FALSE":`AND id = ANY(
|
|
142
145
|
SELECT member_id FROM pod_membership
|
|
143
146
|
WHERE member_type = 'fact' AND pod_id = ANY(?::int[])
|
|
144
|
-
)`:"",v=w&&!_?[a]:[],[E,...R]=
|
|
147
|
+
)`:"",v=w&&!_?[a]:[],[E,...R]=f,M=[c,c,n,E,...R,...v,c,p],g=[e,e,n,E,e,...R,...v,p],X=[p,p,r],se=`
|
|
145
148
|
WITH semantic AS (
|
|
146
149
|
SELECT id,
|
|
147
150
|
uid,
|
|
@@ -157,10 +160,10 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
157
160
|
WHERE namespace = ANY(?)
|
|
158
161
|
AND status = 'active'
|
|
159
162
|
AND embedding IS NOT NULL
|
|
160
|
-
AND ${
|
|
161
|
-
${
|
|
163
|
+
AND ${ae} >= ?
|
|
164
|
+
${m}
|
|
162
165
|
${y}
|
|
163
|
-
${
|
|
166
|
+
${b}
|
|
164
167
|
ORDER BY ${u}
|
|
165
168
|
LIMIT ?
|
|
166
169
|
),
|
|
@@ -178,11 +181,11 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
178
181
|
FROM fact
|
|
179
182
|
WHERE namespace = ANY(?)
|
|
180
183
|
AND status = 'active'
|
|
181
|
-
AND ${
|
|
184
|
+
AND ${ae} >= ?
|
|
182
185
|
AND search_vector @@ plainto_tsquery('english', ?)
|
|
183
|
-
${
|
|
186
|
+
${m}
|
|
184
187
|
${y}
|
|
185
|
-
${
|
|
188
|
+
${b}
|
|
186
189
|
ORDER BY keyword_rank DESC
|
|
187
190
|
LIMIT ?
|
|
188
191
|
),
|
|
@@ -202,8 +205,8 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
202
205
|
COALESCE(s.created_at, k.created_at) AS created_at,
|
|
203
206
|
COALESCE(s.similarity, 0) AS similarity,
|
|
204
207
|
(
|
|
205
|
-
${
|
|
206
|
-
+ ${
|
|
208
|
+
${Ki} * (1.0 / (${ir} + COALESCE(s.rank_ix, ?)))
|
|
209
|
+
+ ${ji} * (1.0 / (${ir} + COALESCE(k.rank_ix, ?)))
|
|
207
210
|
) AS rrf_raw
|
|
208
211
|
FROM semantic s
|
|
209
212
|
FULL OUTER JOIN keyword k ON s.id = k.id
|
|
@@ -223,11 +226,11 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
223
226
|
)
|
|
224
227
|
)
|
|
225
228
|
)) AS activation,
|
|
226
|
-
CASE f.importance WHEN 'vital' THEN ${
|
|
229
|
+
CASE f.importance WHEN 'vital' THEN ${Ji} ELSE 1.0 END AS importance_mult,
|
|
227
230
|
CASE f.confidence
|
|
228
|
-
WHEN 'high' THEN ${
|
|
229
|
-
WHEN 'medium' THEN ${
|
|
230
|
-
WHEN 'low' THEN ${
|
|
231
|
+
WHEN 'high' THEN ${qi}
|
|
232
|
+
WHEN 'medium' THEN ${zi}
|
|
233
|
+
WHEN 'low' THEN ${Xi}
|
|
231
234
|
ELSE 1.0
|
|
232
235
|
END AS confidence_mult
|
|
233
236
|
FROM fused f
|
|
@@ -244,7 +247,7 @@ or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"Op
|
|
|
244
247
|
ORDER BY final_score DESC,
|
|
245
248
|
CASE WHEN importance = 'vital' THEN 0 ELSE 1 END
|
|
246
249
|
LIMIT ?
|
|
247
|
-
`,
|
|
250
|
+
`,ce=[...M,...g,...X],{rows:le}=await d.raw(se,ce);if(!le.length)return[];let zr=le[0].final_score||le[0].rrf_raw||1;return le.map(Pe=>({...Pe,rrfScore:Math.round(Number(Pe.final_score||Pe.rrf_raw)/Number(zr)*100)/100}))}var ir,Ki,ji,Vi,Ji,qi,zi,Xi,sr=h(()=>{I();V();A();Re();ir=20,Ki=1,ji=.7,Vi=3,Ji=1.5,qi=1,zi=.85,Xi=.7});async function cr(e){let t=e.map(o=>o.id),n=await oe(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 lr(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 ur(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 dr=h(()=>{I();Oe()});var q,lt=h(()=>{q=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 mr(e){let t=pr.get(e);if(t)return t;let n=`You are a search query expander for a personal knowledge base.
|
|
248
251
|
|
|
249
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.
|
|
250
253
|
|
|
@@ -256,7 +259,7 @@ Think about:
|
|
|
256
259
|
|
|
257
260
|
User query: "${e}"
|
|
258
261
|
|
|
259
|
-
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 Te(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,Zi),i=o.length?[e,...o]:[e];return pr.set(e,i),i}catch(r){return console.error("[query-expander] Failed:",r.message),[e]}}var Zi,pr,fr=h(()=>{ie();lt();A();Zi=5,pr=new q({maxSize:100,ttlMs:300*1e3})});import{readFile as Qi}from"node:fs/promises";import{join as ea}from"node:path";async function Er(e){let t=e.trim().toLowerCase(),n=ut.get(t);if(n)return n;let o=`${await Qi(ta,"utf8")}
|
|
260
263
|
|
|
261
264
|
---
|
|
262
265
|
|
|
@@ -264,8 +267,8 @@ Query: ${e}
|
|
|
264
267
|
|
|
265
268
|
---
|
|
266
269
|
|
|
267
|
-
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
|
|
268
|
-
`),vi(n.name,r)}return t}function vi(e,t){Promise.resolve().then(()=>(er(),Qn)).then(({recordTrace:n})=>n({kind:"lifecycle",summary:`pod-resolution failed for kind "${e}"`,detail:{kind:e,error:t.message}})).catch(()=>{})}var Oi,Ti,Ni,Ri,tr,ze=f(()=>{M();Oi=["name"],Ti=new Set(["private","shared","public"]),Ni=new Set(["singleton-live","multi-active","rolling-window","always"]),Ri=new Set(["origin-only","shared-allowlist","open"]),tr=new Map});var Ze={};T(Ze,{CURSOR_PATH:()=>K,endActiveSession:()=>Ui,ensureActiveSession:()=>Bi,getActiveCursor:()=>Fi,getActiveSessionPodUid:()=>Xe});import{writeFile as Li,readFile as Ci,unlink as xi}from"node:fs/promises";import{existsSync as Pi,mkdirSync as Mi}from"node:fs";import{dirname as or}from"node:path";async function Ae(){try{let e=await Ci(K,"utf8");return JSON.parse(e)}catch{return null}}async function ir(e){Pi(or(K))||Mi(or(K),{recursive:!0}),await Li(K,JSON.stringify(e,null,2),"utf8")}async function Bi({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 Ae();if(s&&s.session_id===e&&s.namespace===i){let u=await Ue(s.pod_uid);if(u)return await He(u.id,{turn_count:(Hi(u.attrs)||0)+1}),await $i(s),u}let a=new Date,{pod:c}=await me({podType:ar,externalId:e,name:cr({sessionId:e,startedAt:a}),namespace:i,attrs:sr({sessionId:e,transcriptPath:t,cwd:n,turnCount:1,model:r}),startedAt:a});return await ir({session_id:e,pod_uid:c.uid,namespace:i,started_at:c.startedAt??a.toISOString(),last_seen_at:new Date().toISOString()}),c}async function $i(e){await ir({...e,last_seen_at:new Date().toISOString()})}async function Xe({allowStale:e=!1}={}){let t=await Ae();return!t||!t.pod_uid||!e&&t.started_at&&Date.now()-new Date(t.started_at).getTime()>ki?null:t.pod_uid}async function Fi(){return Ae()}async function Ui({conclusion:e=null,summary:t=null}={}){let n=await Ae();if(!n)return null;let r=await Ue(n.pod_uid);if(r){if(e||t){let o={};e&&(o.conclusion=e),t&&(o.summary=t),await He(r.id,o)}await yn(r.id)}try{await xi(K)}catch{}return r}function Hi(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 K,ki,Ie=f(()=>{fe();Qe();I();M();K=ut,ki=360*60*1e3});function sr({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 cr({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 ar,lr,Qe=f(()=>{Ie();ar="claude_session",lr={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 Xe();return e?[e]:[]}catch{return[]}}}});var Wi,ur,dr=f(()=>{b();I();Wi=1440*60*1e3,ur={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()-Wi);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 mr={};T(mr,{POD_TYPE:()=>tt,deriveProjectRoot:()=>rt,ensureProjectPod:()=>Ki,formatForDisplay:()=>Vi,membership:()=>_e,projectKind:()=>nt});import{execFileSync as Yi}from"node:child_process";import{basename as pr}from"node:path";async function Ki({cwd:e,namespace:t=null}){if(!e)return null;let n=rt(e),r=t||l.defaults.namespace,i=(n!==e?!1:et(e)===e)?n:et(e),{pod:s}=await me({podType:tt,externalId:n,name:pr(n)||n,namespace:r,attrs:{root_path:n,git_root:i||null,display_name:pr(n)||n,discovered_at:new Date().toISOString()},startedAt:new Date});return s}function rt(e){return et(e)||e}function et(e){try{return Yi("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}async function ji(){try{let{getActiveCursor:e}=await Promise.resolve().then(()=>(Ie(),Ze));return(await e())?.cwd||null}catch{return null}}function Vi(e){let t=Ji(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 Ji(e){if(!e)return{};if(typeof e=="object")return e;try{return JSON.parse(e)}catch{return{}}}var tt,nt,ot=f(()=>{fe();Ge();I();tt="project",nt={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 ji();if(!t)return[];let n=e.namespace||l.defaults.namespace,r=rt(t),o=await En({podType:tt,externalId:r,namespace:n});return o?[o.uid]:[]}}});async function zi(e){if(e.project)return e.project;if(!e.cwd)try{let{getActiveCursor:t}=await Promise.resolve().then(()=>(Ie(),Ze)),n=await t();e={...e,cwd:n?.cwd}}catch{return null}if(!e.cwd)return null;try{let{deriveProjectRoot:t}=await Promise.resolve().then(()=>(ot(),mr)),n=t(e.cwd);return n?n.split("/").pop():null}catch{return null}}function Xi(e){if(!e)return{};if(typeof e=="object")return e;try{return JSON.parse(e)}catch{return{}}}var qi,fr,hr=f(()=>{b();I();qi="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 zi(e);try{let o=await d("pod").where({podType:qi,namespace:t,status:"active"}).select("uid","attrs");return n?o.filter(s=>{let a=Xi(s.attrs);return!a.project||a.project===n}).map(s=>s.uid):o.map(s=>s.uid)}catch{return[]}}}});var Zi,_r,Er=f(()=>{b();I();Zi=["__virtual:vital__"],_r={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()=>Zi,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 ea(){if(!yr){for(let e of Qi)nr(e);yr=!0}}var Qi,yr,gr=f(()=>{ze();Qe();dr();ot();hr();Er();Qi=[lr,nt,ur,fr,_r],yr=!1;ea()});var Ir={};T(Ir,{isSearchableQuery:()=>wr,search:()=>oa});async function oa(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:h=l.search.synthesize,podScope:y=null,applyFloor:m=!0,ctx:p={}}={}){let w=Date.now();if(!wr(e)){let g=aa();return g._trace={query:e,searchable:!1,stages:[{stage:"guard",note:"query is not searchable (empty or wildcard-only)"}],durationMs:Date.now()-w},g}h&&(i=!0);let _=null;c&&(_=await jn(e),o=o||_.useGraph,a=a||_.expand,n=_.limit||n,s=s||_.pointInTime,u=u||(_.categories.length?_.categories:void 0));let O=await ua(e,t),v=await la(y,{...p,namespace:t?.[0]}),E;O?E=await da(O,e,{namespaces:t,limit:n,minConfidence:r,includeChunks:i,pointInTime:s,categories:u,podIds:v}):E=await fa(e,{namespaces:t,limit:n,minConfidence:r,useGraph:o,includeChunks:i,pointInTime:s,expand:a,categories:u,podIds:v});let R=null;if(m&&Array.isArray(E.facts)&&E.facts.length){let g=l.memory.injectionFloor,j=E.facts.length;E.facts=E.facts.filter(te=>{if(te.source==="entity")return!0;let ne=Number(te.similarity);return Number.isFinite(ne)?ne>=g:!0}),R={threshold:g,dropped:j-E.facts.length,kept:E.facts.length}}let x=E.facts.map(g=>g.id).filter(Boolean);if(In(x).catch(g=>console.error("[access-tracking]",g.message)),On(x.slice(0,8)).catch(g=>console.error("[hebbian]",g.message)),l.hebbian.entity.enabled&&x.length>=2&&ca(x).catch(g=>console.error("[hebbian-entity]",g.message)),h)try{E.synthesized=await sa(e,E)}catch(g){console.error("[synthesizer] failed:",g.message),E.synthesized=null}return E._trace=ia({query:e,namespaces:t,limit:n,minConfidence:r,useGraph:o,expand:a,route:c,routing:_,matchedEntity:O,podScope:y,podIds:v,result:E,factIds:x,floored:R,durationMs:Date.now()-w}),E}function ia({query:e,namespaces:t,limit:n,minConfidence:r,useGraph:o,expand:i,route:s,routing:a,matchedEntity:c,podScope:u,podIds:h,result:y,factIds:m,floored:p,durationMs:w}){let _=E=>{let R=Number(E);return Number.isFinite(R)?Math.round(R*1e4)/1e4:null},O=(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:h},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:O,chunks:v},synthesized:y.synthesized||null,relatedEntities:y.relatedEntities||[],reinforced:{factIds:m,note:"access_count bumped + Hebbian co-retrieval edges strengthened (off hot path)"}}}function wr(e){let t=String(e||"").trim();return t?!/^[*%_?\s]+$/.test(t):!1}function aa(){return{facts:[],chunks:[],matchedEntity:null,relatedEntities:[]}}async function sa(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 Te(o,{model:l.llm.extractionModel,caller:"query-router"});if(!i||!na.includes(i.intent)){let c=hr("factual",{});return ut.set(t,c),c}let s=_r[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 ut.set(t,a),a}catch(i){return console.error("[query-router] Failed:",i.message),hr("factual",{reasoning:`Fallback \u2014 ${i.message}`})}}function hr(e,t={}){let n=_r[e];return{intent:e,categories:n.categories,entities:[],expand:n.expand,useGraph:n.useGraph,limit:n.limit,pointInTime:null,reasoning:"",...t}}var ta,ut,na,_r,yr=h(()=>{ie();lt();A();B();ta=ea(pe,"query-router.md"),ut=new q({maxSize:200,ttlMs:600*1e3}),na=["preference","factual","entity_lookup","exploratory","temporal"],_r={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 dt,ra,gr,wr=h(()=>{dt=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}},ra=new dt,gr=ra});import{AsyncLocalStorage as oa}from"node:async_hooks";function Sr(){return ia.getStore()||null}var ia,Ar=h(()=>{ia=new oa});var br={};D(br,{clearTraces:()=>da,getTrace:()=>ua,listTraces:()=>la,recordTrace:()=>ca});function sa(){let e=Sr();return{deviceId:e?.device?.id??null,transport:e?.transport??null}}async function ca({kind:e,summary:t,detail:n={},namespace:r=null,durationMs:o=null}){let i=`trace-${we(16)}`,s=new Date().toISOString(),{deviceId:a,transport:c}=sa(),u=n;try{JSON.stringify(n).length>aa&&(u={truncated:!0,note:"trace detail exceeded size cap",summary:t})}catch{u={error:"detail not serializable"}}try{gr.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 la({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"?Ir(s.detail):s.detail}))}async function ua(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"?Ir(t.detail):t.detail}:null}async function da(){return{cleared:await d("trace_event").del()}}function Ir(e){try{return JSON.parse(e)}catch{return{}}}var aa,Or=h(()=>{tt();I();wr();Ar();aa=256*1024});function Dr(e){for(let t of pa)if(!e[t])throw new Error(`Pod kind missing required field: ${t}`);if(e.visibility&&!ma.has(e.visibility))throw new Error(`Pod kind ${e.name}: invalid visibility ${e.visibility}`);if(e.activeMode&&!fa.has(e.activeMode))throw new Error(`Pod kind ${e.name}: invalid activeMode ${e.activeMode}`);if(e.writePolicy&&!ha.has(e.writePolicy))throw new Error(`Pod kind ${e.name}: invalid writePolicy ${e.writePolicy}`);Tr.set(e.name,_a(e))}function _a(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 Nr(e={}){let t=[];for(let n of Tr.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
|
+
`),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.
|
|
269
272
|
Each retrieved item is labeled [F#] (a stored fact) or [C#] (a raw conversation chunk
|
|
270
273
|
that may include user/assistant turns and dates).
|
|
271
274
|
|
|
@@ -280,8 +283,8 @@ Instructions:
|
|
|
280
283
|
- Reason step-by-step internally for temporal questions ("first", "before", "after", "how many days") \u2014 compare the dates explicitly.
|
|
281
284
|
- Cite items in square brackets where they directly support the answer, e.g. [C2].
|
|
282
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.
|
|
283
|
-
- 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
|
|
284
|
-
`,"utf8")}catch{}}async function
|
|
285
|
-
`),await(await Promise.resolve().then(()=>(
|
|
286
|
-
`));return await(await Promise.resolve().then(()=>(
|
|
287
|
-
`),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 it(o,{model:i,caller:"synthesizer"})}async function qa(e){let t=await oe(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 at(r)}async function za(e,t={}){if(e==null||e==="global")return null;if(e==="auto"){let r=(await Nr(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 Xa(e,t){if(e.length<2||e.length>Ya)return null;let n=t[0]||l.defaults.namespace,r=await Fn(e,n);return r||(await Un(e,{namespace:n,limit:1}))[0]||null}async function Za(e,t,{namespaces:n,limit:r,minConfidence:o,includeChunks:i,pointInTime:s,categories:a,podIds:c}){let u=Qa(t,e),m=await ge(u,{inputType:"query"}),[y,f,...p]=await Promise.all([jn(e.id,{limit:r}),Qn(e.id,{limit:15}),...u.map((g,X)=>Vr(g,{queryEmbedding:m[X],namespaces:n,limit:r,minConfidence:o,includeChunks:i,pointInTime:s,categories:a,podIds:c}))]),w=y.map(g=>({...g,source:"entity"})),_=Ce(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 jr(E,{seedEntityIds:[e.id]})}catch(g){console.error("[hebbian-entity-boost]",g.message)}let R=i?Ce(p.map(g=>g.chunks||[]),r):[],M=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:M}}function Qa(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${es(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 es(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function ts(e,{namespaces:t,limit:n,minConfidence:r,useGraph:o,includeChunks:i,pointInTime:s,expand:a=!1,categories:c,podIds:u}){let m=a?await mr(e):[e],y=await ge(m,{inputType:"query"}),f=await Promise.all(m.map((_,b)=>Vr(_,{queryEmbedding:y[b],namespaces:t,limit:n,minConfidence:r,includeChunks:i,pointInTime:s,categories:c,podIds:u}))),p=Ce(f.map(_=>_.facts),n);if(p=p.map(_=>({..._,source:"search"})),l.hebbian.entity.enabled&&p.length>=2)try{p=await jr(p)}catch(_){console.error("[hebbian-entity-boost]",_.message)}if(o&&p.length)try{let _=await cr(p.slice(0,5));if(_.length){let b=await ns(_.map(E=>E.id)),v=await lr(b,{limit:5});p=ur(p,v,b,n)}}catch(_){console.error("[graph-enhancement] Failed:",_.message)}let w=i?Ce(f.map(_=>_.chunks),n):[];return{facts:p,chunks:w,matchedEntity:null,relatedEntities:[]}}async function jr(e,t={}){let n=e.map(f=>f.id).filter(Boolean);if(n.length<2)return e;let r=await oe(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 st([...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 ns(e){let t=l.hebbian.entity.expandPerSeed;if(!t||!e.length)return e;let{getCoRetrievedEntities:n}=await Promise.resolve().then(()=>(ct(),Zn)),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 Ce(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/(St+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 Vr(e,{queryEmbedding:t,namespaces:n,limit:r,minConfidence:o,includeChunks:i=!1,pointInTime:s,categories:a,podIds:c}){let u=t||await Qe(e,{inputType:"query"}),m=ar(e,u,{namespaces:n,limit:r,minConfidence:o,pointInTime:s,categories:a,podIds:c}),y=i?[tr(u,{namespaces:n,limit:r}),rr(e,{namespaces:n,limit:r})]:[],[f,...p]=await Promise.all([m,...y]),w=i&&p.length===2?rs(p[0],p[1],r):[];return{facts:f,chunks:w}}function rs(e,t,n){let r={},o={...We(e,"id"),...We(t,"id")};e.forEach((a,c)=>{r[a.id]=(r[a.id]||0)+Ga/(St+c+1)}),t.forEach((a,c)=>{r[a.id]=(r[a.id]||0)+Wa/(St+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 St,Ga,Wa,Ya,qr=h(()=>{ye();et();A();Hn();Oe();qn();Xn();ct();er();Oe();nr();or();sr();dr();fr();yr();ie();Yr();pt();I();St=20,Ga=1,Wa=.7,Ya=60});ue();B();ue();import{appendFile as Po,readFile as Xs,writeFile as Zs,unlink as Qs}from"node:fs/promises";import{createHash as Mo}from"node:crypto";var xo=Ot;async function Ge(e,t,n=null){try{let r={ts:new Date().toISOString(),hook:e,error:Q(t?.message||String(t)),input_hash:n?ko(n):null};await Po(xo,JSON.stringify(r)+`
|
|
287
|
+
`,"utf8")}catch{}}async function en(e,t=null){try{let{validateConfig:n}=await Promise.resolve().then(()=>(Qt(),Zt)),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 Ge(e,i,t)}return!0}catch{return!1}}function ko(e){try{let t=typeof e=="string"?e:JSON.stringify(e);return Mo("sha256").update(t).digest("hex").slice(0,12)}catch{return null}}B();import{resolve as Bo}from"node:path";import{existsSync as tn}from"node:fs";import{config as nn}from"dotenv";function rn(){let e=Bo(process.cwd(),".env");tn(e)&&nn({path:e,quiet:!0}),tn(x)&&x!==e&&nn({path:x,quiet:!0}),process.env.SIGIL_AGENT||(process.env.SIGIL_AGENT="claude-code")}rn();var os=8,is=20,as=4800;async function ss(){let e=[];for await(let o of process.stdin)e.push(o);let t=Buffer.concat(e).toString("utf8").trim();if(!t)return U();let n=JSON.parse(t),r=n.prompt||"";if(r.length<os||await en("user-prompt-submit",t))return U();try{let{search:o}=await Promise.resolve().then(()=>(qr(),Jr)),i=(await Promise.resolve().then(()=>(A(),Bt))).default,s;try{s=await o(r,{namespaces:[i.defaults.namespace],limit:is,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.message}
|
|
288
|
+
`),await(await Promise.resolve().then(()=>(I(),G))).default.destroy().catch(()=>{}),U()}let a=s?.facts||[];if(!a.length)return await(await Promise.resolve().then(()=>(I(),G))).default.destroy(),U();let c=[],u=0;for(let f of a){let p=(f.content||"").length+4;if(c.length>0&&u+p>as)break;c.push(f),u+=p}let m=Q([`Sigil memory (${c.length} relevant facts):`,...c.map(f=>`- ${f.content}`)].join(`
|
|
289
|
+
`));return await(await Promise.resolve().then(()=>(I(),G))).default.destroy(),U(m)}catch(o){process.stderr.write(`[sigil:user-prompt-submit] ${o.message}
|
|
290
|
+
`),await Ge("user-prompt-submit",o,t);try{await(await Promise.resolve().then(()=>(I(),G))).default.destroy()}catch{}return U()}}function U(e){let t={hookSpecificOutput:{hookEventName:"UserPromptSubmit",...e&&{additionalContext:e}}};process.stdout.write(JSON.stringify(t))}ss();
|