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