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