@anmol-srv/sigil 0.18.1 → 0.18.2

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.
Files changed (3) hide show
  1. package/dist/cli.js +95 -95
  2. package/dist/daemon.js +19 -19
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -204,7 +204,7 @@ Output the JSON array directly, no explanation or wrapping.`}function VM(e,t){le
204
204
  last_accessed_at = NOW(),
205
205
  stage = CASE WHEN stage = 'stable' THEN 'editing' ELSE stage END,
206
206
  stage_entered_at = CASE WHEN stage = 'stable' THEN NOW() ELSE stage_entered_at END
207
- WHERE fact_id = ANY(?)`,[e])}async function i1(e,{limit:t=10,since:r}={}){let n=b("fact as f").join("fact_lifecycle as fl","fl.fact_id","f.id").where({"f.status":"active"}).where("fl.access_count",">",0).orderBy("fl.access_count","desc").limit(t).select("f.*");return e&&n.where({"f.namespace":e}),r&&n.where("fl.last_accessed_at",">=",r),n}async function o1({namespace:e,limit:t=50,offset:r=0,category:n}={}){let i=b("fact").where({status:"active"}).select("id","uid","content","category","confidence","importance","createdAt","namespace").orderBy("createdAt","desc").limit(t).offset(r);return e&&i.where({namespace:e}),n&&i.where({category:n}),i}async function s1(e){let t=b("fact").where({status:"active"});e&&t.where({namespace:e});let[{count:r}]=await t.count("id as count");return Number(r)}async function a1(e){let r=typeof e=="string"&&e.length>8?{uid:e}:{id:Number(e)},n=await b("fact").where(r).first();return n?(await b("fact_entity").where({factId:n.id}).del(),await b("fact").where({id:n.id}).del(),n):null}async function c1(){return(await b("fact").where({status:"active"}).select("namespace").count("id as factCount").groupBy("namespace").orderBy("namespace")).map(t=>({namespace:t.namespace,factCount:Number(t.factCount)}))}async function l1(e){await b.raw("DELETE FROM relation WHERE source_fact_id IN (SELECT id FROM fact WHERE namespace = ?)",[e]),await b.raw("DELETE FROM fact_entity WHERE fact_id IN (SELECT id FROM fact WHERE namespace = ?)",[e]),await b.raw("DELETE FROM relation WHERE source_id IN (SELECT id FROM entity WHERE namespace = ?) OR target_id IN (SELECT id FROM entity WHERE namespace = ?)",[e,e]);let t=await b("fact").where({namespace:e}).del(),r=await b("chunk").where({namespace:e}).del(),n=await b("document").where({namespace:e}).del(),i=await b("entity").where({namespace:e}).del();return{factsDeleted:t,chunksDeleted:r,docsDeleted:n,entitiesDeleted:i}}var e1,uE,op,ir=f(()=>{Oo();B();rr();Xe();_r();No();N();K();e1=QM.join(rt,"audm-decision.md"),uE=x.memory.skipThreshold,op=x.memory.ambiguousThreshold});var el,u1,e7,gE,cp=f(()=>{el={preference:"Personal likes, dislikes, favorites, preferred tools/foods/methods",opinion:"Personal views, assessments, evaluations of tools/concepts/approaches",personal:"Personal facts \u2014 birthday, workplace, location, biographical details",experience:"Personal experiences \u2014 projects built, tools used, skills acquired",business_rule:"Organizational rules, policies, constraints",workflow:"Process flows, state transitions, procedures",architecture:"System design, service interactions, infrastructure",convention:"Coding patterns, naming rules, team standards",decision:"Why choices were made, tradeoffs considered",domain_knowledge:"Domain-specific terminology and concepts",key_insight:"Important takeaways, notable explanations",metric:"Quantitative data, measurements, statistics",issue:"Known problems, bugs, limitations, risks",action_item:"Tasks, follow-ups, assignments, deadlines"},u1=["preference","opinion","personal","experience"],e7=Object.keys(el).filter(e=>!u1.includes(e)),gE=el});import{readFile as d1}from"node:fs/promises";import{join as p1}from"node:path";async function wE(e,{title:t}={}){if(!e?.trim()||e.trim().length<m1)return{route:"noise",facts:[],entities:[],reasoning:"Empty or too short"};if(e.length>h1)return{route:"knowledge",facts:[],entities:[],reasoning:"Long content \u2014 auto-routed to full pipeline"};let n=`${await d1(f1,"utf8")}
207
+ WHERE fact_id = ANY(?)`,[e])}async function i1(e,{limit:t=10,since:r}={}){let n=b("fact as f").join("fact_lifecycle as fl","fl.fact_id","f.id").where({"f.status":"active"}).where("fl.access_count",">",0).orderBy("fl.access_count","desc").limit(t).select("f.*");return e&&n.where({"f.namespace":e}),r&&n.where("fl.last_accessed_at",">=",r),n}async function o1({namespace:e,limit:t=50,offset:r=0,category:n}={}){let i=b("fact").where({status:"active"}).select("id","uid","content","category","confidence","importance","createdAt","namespace").orderBy("createdAt","desc").limit(t).offset(r);return e&&i.where({namespace:e}),n&&i.where({category:n}),i}async function s1(e){let t=b("fact").where({status:"active"});e&&t.where({namespace:e});let[{count:r}]=await t.count("id as count");return Number(r)}async function a1(e){let r=typeof e=="string"&&e.length>8?{uid:e}:{id:Number(e)},n=await b("fact").where(r).first();return n?(await b("fact_entity").where({factId:n.id}).del(),await b("fact").where({id:n.id}).del(),n):null}async function c1(){return(await b("fact").where({status:"active"}).select("namespace").count("id as factCount").groupBy("namespace").orderBy("namespace")).map(t=>({namespace:t.namespace,factCount:Number(t.factCount)}))}async function l1(e){await b.raw("DELETE FROM relation WHERE source_fact_id IN (SELECT id FROM fact WHERE namespace = ?)",[e]),await b.raw("DELETE FROM fact_entity WHERE fact_id IN (SELECT id FROM fact WHERE namespace = ?)",[e]),await b.raw("DELETE FROM relation WHERE source_id IN (SELECT id FROM entity WHERE namespace = ?) OR target_id IN (SELECT id FROM entity WHERE namespace = ?)",[e,e]);let t=await b("fact").where({namespace:e}).del(),r=await b("chunk").where({namespace:e}).del(),n=await b("document").where({namespace:e}).del(),i=await b("entity").where({namespace:e}).del();return{factsDeleted:t,chunksDeleted:r,docsDeleted:n,entitiesDeleted:i}}var e1,uE,op,ir=f(()=>{Oo();B();rr();Xe();_r();No();N();K();e1=QM.join(rt,"audm-decision.md"),uE=x.memory.skipThreshold,op=x.memory.ambiguousThreshold});var el,u1,t7,gE,cp=f(()=>{el={preference:"Personal likes, dislikes, favorites, preferred tools/foods/methods",opinion:"Personal views, assessments, evaluations of tools/concepts/approaches",personal:"Personal facts \u2014 birthday, workplace, location, biographical details",experience:"Personal experiences \u2014 projects built, tools used, skills acquired",business_rule:"Organizational rules, policies, constraints",workflow:"Process flows, state transitions, procedures",architecture:"System design, service interactions, infrastructure",convention:"Coding patterns, naming rules, team standards",decision:"Why choices were made, tradeoffs considered",domain_knowledge:"Domain-specific terminology and concepts",key_insight:"Important takeaways, notable explanations",metric:"Quantitative data, measurements, statistics",issue:"Known problems, bugs, limitations, risks",action_item:"Tasks, follow-ups, assignments, deadlines"},u1=["preference","opinion","personal","experience"],t7=Object.keys(el).filter(e=>!u1.includes(e)),gE=el});import{readFile as d1}from"node:fs/promises";import{join as p1}from"node:path";async function wE(e,{title:t}={}){if(!e?.trim()||e.trim().length<m1)return{route:"noise",facts:[],entities:[],reasoning:"Empty or too short"};if(e.length>h1)return{route:"knowledge",facts:[],entities:[],reasoning:"Long content \u2014 auto-routed to full pipeline"};let n=`${await d1(f1,"utf8")}
208
208
 
209
209
  ---
210
210
 
@@ -822,13 +822,13 @@ ${i[0]}
822
822
  `))>=0;){let p=i.slice(0,u).trim();if(i=i.slice(u+1),!p)continue;let d;try{d=JSON.parse(p)}catch{continue}d.id===1&&d.result?(c({jsonrpc:"2.0",method:"notifications/initialized"}),c({jsonrpc:"2.0",id:2,method:"tools/call",params:{name:"status",arguments:{}}})):d.id===2&&(d.result?s({ok:!0}):s({ok:!1,reason:d.error?.message||"status tool returned no result"}))}}),c({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"sigil-verify",version:"1"}}})})}async function hH(e,{timeoutMs:t=12e3}={}){if(!e)return{ok:!1,reason:"no hook command"};let r=e.split(" ").filter(Boolean),n=r[0],i=r.slice(1),o=i.find(s=>s.endsWith(".js"));return o&&!jS(o)?{ok:!1,reason:`hook script not found at ${o}`}:new Promise(s=>{let a=!1,c="",l=HS(n,i,{stdio:["pipe","pipe","pipe"]}),u=m=>{if(!a){a=!0,clearTimeout(p);try{l.kill("SIGKILL")}catch{}s(m)}},p=setTimeout(()=>u({ok:!1,reason:`timed out after ${t}ms`}),t);p.unref?.(),l.on("error",m=>u({ok:!1,reason:`spawn failed: ${m.message}`})),l.stdout.on("data",m=>{c+=m.toString()}),l.on("close",()=>{let m=c.trim();if(!m)return u({ok:!0,note:"ran; no injection (no matching memory)"});try{JSON.parse(m),u({ok:!0})}catch{u({ok:!1,reason:`hook emitted non-JSON: ${m.slice(0,80)}`})}});let d=JSON.stringify({prompt:"sigil round-trip verification probe",session_id:"verify",cwd:process.cwd()});try{l.stdin.write(d),l.stdin.end()}catch{}})}var oa=f(()=>{});var VS={};A(VS,{detect:()=>wH,install:()=>_H,mergeHooks:()=>WS,meta:()=>yH,uninstall:()=>xH,verify:()=>bH,writeImportLine:()=>GS});import{join as _f}from"node:path";import{homedir as gH}from"node:os";import{existsSync as hn}from"node:fs";async function wH(){return or({dirs:[sa],bins:["claude"]})}async function GS({dryRun:e=!1}={}){let t=await import("node:fs/promises");e||await t.mkdir(sa,{recursive:!0});let r=`@${Er}`,n="";if(hn(St)&&(n=await t.readFile(St,"utf8")),n.includes(r))return{action:"skip",path:St,detail:"already imports sigil CLAUDE.md"};let i=n.trim()?`
823
823
  `:"",o=`${n}${i}${r}
824
824
  `;return{action:(await ge(St,o,{dryRun:e})).action,path:St,detail:n?"+1 @import line":"new file"}}async function WS({dryRun:e=!1}={}){let t=await import("node:fs/promises");await jt({dryRun:e});let r={};try{let u=await t.readFile(vt,"utf8");r=JSON.parse(u)}catch{}let n=u=>`'${qo}' ${u}`,i={UserPromptSubmit:{hooks:[{type:"command",command:n("user-prompt-submit"),timeout:10,statusMessage:"Searching memory..."}]},PostToolUse:{matcher:"Edit|Write|Bash",hooks:[{type:"command",command:n("post-tool-use"),timeout:10,async:!0}]},Stop:{hooks:[{type:"command",command:n("stop"),timeout:30,async:!0}]},SessionEnd:{hooks:[{type:"command",command:n("session-end"),timeout:10,async:!0}]}},o=hn(vt);r.hooks=r.hooks||{};let s=["user-prompt-submit.js","stop.js","post-tool-use.js","session-end.js"],a=u=>typeof u=="string"&&(u.includes("sigil-hook")||s.some(p=>u.endsWith(p)||u.includes(`/${p}`)));for(let[u,p]of Object.entries(i)){let m=(r.hooks[u]||[]).filter(h=>!h.hooks?.some(g=>a(g.command)));r.hooks[u]=[...m,p]}e||await t.mkdir(sa,{recursive:!0});let c=JSON.stringify(r,null,2);return{action:(await ge(vt,c,{dryRun:e})).action,path:vt,detail:o?"+UserPromptSubmit, +PostToolUse, +Stop, +SessionEnd hooks (other settings preserved)":"new settings.json with sigil hooks"}}async function _H({dryRun:e=!1}={}){let t=[],r=await yf({dryRun:e});r&&t.push({action:r.action,path:r.path,detail:`${r.bytes??0} bytes`});let n=await GS({dryRun:e});n&&t.push(n);let i=await WS({dryRun:e});return i&&t.push(i),{actions:t}}async function bH({deep:e=!1}={}){let t=await import("node:fs/promises"),r=`@${Er}`;if(!hn(St))return{installed:!1,reason:"~/.claude/CLAUDE.md missing \u2014 run `sigil init`"};if(!(await t.readFile(St,"utf8")).includes(r))return{installed:!1,reason:"@import line missing from ~/.claude/CLAUDE.md"};if(!hn(vt))return{installed:!1,reason:"~/.claude/settings.json missing \u2014 hooks not registered"};let i;try{i=JSON.parse(await t.readFile(vt,"utf8"))}catch{return{installed:!1,reason:"~/.claude/settings.json is not valid JSON"}}let o=i.hooks||{},s=["user-prompt-submit.js","post-tool-use.js","stop.js","session-end.js"],a=["UserPromptSubmit","PostToolUse","Stop","SessionEnd"],c=u=>{for(let p of o[u]||[])for(let d of p.hooks||[])if(typeof d.command=="string"&&(d.command.includes("sigil-hook")||s.some(m=>d.command.includes(m))))return d.command;return null},l=a.filter(u=>!c(u));if(l.length)return{installed:!1,reason:`hooks missing: ${l.join(", ")}`};for(let u of a){let p=c(u);if(p.includes("sigil-hook")){if(!hn(qo))return{installed:!1,reason:`hook launcher missing: ${qo} (run \`sigil init\`)`};continue}let d=p.match(/(\/[^\s"']+\.js)/);if(d&&!hn(d[1]))return{installed:!1,reason:`hook file missing on disk: ${d[1]} (run \`sigil init\`)`}}if(e){let u=c("UserPromptSubmit"),{verifyClaudeHookRoundTrip:p}=await Promise.resolve().then(()=>(oa(),ia)),d=await p(u);if(!d.ok)return{installed:!1,reason:`hook round-trip failed: ${d.reason}`}}return{installed:!0}}async function xH({dryRun:e=!1}={}){let t=await import("node:fs/promises"),r=[];if(hn(St)){let n=`@${Er}`,i=await t.readFile(St,"utf8"),o=new RegExp(`^${n.replace(/[.*+?^${}()|[\\]\\\\]/g,"\\\\$&")}\\s*\\n?`,"gm"),s=i.replace(o,"");if(s!==i){let a=await ge(St,s,{dryRun:e});r.push({action:a.action,path:St,detail:"-1 @import line"})}else r.push({action:"skip",path:St,detail:"@import not present"})}if(hn(vt)){let n;try{n=JSON.parse(await t.readFile(vt,"utf8"))}catch{return r.push({action:"skip",path:vt,detail:"invalid JSON \u2014 not touched"}),{actions:r}}let i=["user-prompt-submit.js","stop.js","post-tool-use.js","session-end.js"],o=a=>typeof a=="string"&&(a.includes("sigil-hook")||i.some(c=>a.endsWith(c)||a.includes(`/${c}`))),s=!1;for(let a of Object.keys(n.hooks||{})){let c=n.hooks[a],l=c.filter(u=>!u.hooks?.some(p=>o(p.command)));l.length!==c.length&&(s=!0,l.length===0?delete n.hooks[a]:n.hooks[a]=l)}if(s){let a=await ge(vt,JSON.stringify(n,null,2),{dryRun:e});r.push({action:a.action,path:vt,detail:"sigil hooks removed (other entries preserved)"})}else r.push({action:"skip",path:vt,detail:"no sigil hooks to remove"})}return{actions:r}}var sa,St,vt,yH,KS=f(()=>{dn();Jo();Yo();fn();sa=_f(gH(),".claude"),St=_f(sa,"CLAUDE.md"),vt=_f(sa,"settings.json"),yH={id:"claude-code",label:"Claude Code",hint:"hooks + @import \u2014 full auto-injection"}});var ZS={};A(ZS,{detect:()=>IH,install:()=>AH,meta:()=>SH,resolveServerPath:()=>YS,uninstall:()=>CH,verify:()=>$H,writeMcpEntry:()=>zS,writeRulesFile:()=>JS});import{join as aa,dirname as EH}from"node:path";import{homedir as vH}from"node:os";import{existsSync as gn}from"node:fs";async function IH(){return or({dirs:[El],apps:["Cursor"],bins:["cursor"]})}function YS(){let e=aa(qS,"dist","server.js"),t=aa(qS,"src","server.js");return gn(e)?e:t}async function zS({dryRun:e=!1}={}){let t=await import("node:fs/promises"),r={};try{let o=await t.readFile(ct,"utf8");r=JSON.parse(o)}catch(o){if(o.code!=="ENOENT")return{action:"skip",path:ct,detail:`invalid JSON \u2014 not touched (${o.message})`}}let n=gn(ct);return r.mcpServers=r.mcpServers||{},await jt({dryRun:e}),r.mcpServers.sigil={command:et,args:[]},e||await t.mkdir(El,{recursive:!0}),{action:(await ge(ct,JSON.stringify(r,null,2),{dryRun:e})).action,path:ct,detail:n?"+sigil MCP server (other entries preserved)":"new mcp.json with sigil entry"}}function TH(){return["---","description: Sigil persistent memory \u2014 consult before answering, save in batches","alwaysApply: true","---",""].join(`
825
- `)+mn({transport:"mcp"})}async function JS({dryRun:e=!1}={}){let t=await import("node:fs/promises");e||await t.mkdir(EH(_i),{recursive:!0});let r=await ge(_i,TH(),{dryRun:e});return{action:r.action,path:_i,detail:`${r.bytes??0} bytes, alwaysApply=true`}}async function AH({dryRun:e=!1}={}){let t=[],r=await zS({dryRun:e});r&&t.push(r);let n=await JS({dryRun:e});return n&&t.push(n),{actions:t}}async function $H({deep:e=!1}={}){let t=await import("node:fs/promises");if(!gn(ct))return{installed:!1,reason:"~/.cursor/mcp.json missing"};let r;try{r=JSON.parse(await t.readFile(ct,"utf8"))}catch{return{installed:!1,reason:"~/.cursor/mcp.json is not valid JSON"}}if(!r.mcpServers?.sigil)return{installed:!1,reason:"sigil entry missing from ~/.cursor/mcp.json"};if(!gn(_i))return{installed:!1,reason:"~/.cursor/rules/sigil.mdc missing"};if(!gn(et))return{installed:!1,reason:`MCP launcher missing at ${et} \u2014 run \`sigil connect\``};let n=YS();if(!gn(n))return{installed:!1,reason:`MCP server missing at ${n} \u2014 run \`sigil connect\` to refresh`};if(e){let{verifyMcpRoundTrip:i}=await Promise.resolve().then(()=>(oa(),ia)),o=await i(n);if(!o.ok)return{installed:!1,reason:`MCP round-trip failed: ${o.reason}`}}return{installed:!0}}async function CH({dryRun:e=!1}={}){let t=await import("node:fs/promises"),r=[];if(gn(ct)){let n;try{n=JSON.parse(await t.readFile(ct,"utf8"))}catch{return r.push({action:"skip",path:ct,detail:"invalid JSON \u2014 not touched"}),{actions:r}}if(n.mcpServers?.sigil){delete n.mcpServers.sigil;let i=await ge(ct,JSON.stringify(n,null,2),{dryRun:e});r.push({action:i.action,path:ct,detail:"-sigil MCP entry"})}else r.push({action:"skip",path:ct,detail:"sigil entry not present"})}return gn(_i)&&(e||await t.unlink(_i),r.push({action:"delete",path:_i,detail:"sigil rules file removed"})),{actions:r}}var El,ct,_i,qS,SH,XS=f(()=>{K();dn();Jo();Yo();fn();El=aa(vH(),".cursor"),ct=aa(El,"mcp.json"),_i=aa(El,"rules","sigil.mdc"),qS=ue,SH={id:"cursor",label:"Cursor",hint:"global MCP + always-applied rule (no native hooks)"}});var eI=He((Sre,QS)=>{"use strict";var bi=class e extends Error{constructor(t,r,n){super("[ParserError] "+t,r,n),this.name="ParserError",this.code="ParserError",Error.captureStackTrace&&Error.captureStackTrace(this,e)}},vl=class{constructor(t){this.parser=t,this.buf="",this.returned=null,this.result=null,this.resultTable=null,this.resultArr=null}},ca=class{constructor(){this.pos=0,this.col=0,this.line=0,this.obj={},this.ctx=this.obj,this.stack=[],this._buf="",this.char=null,this.ii=0,this.state=new vl(this.parseStart)}parse(t){if(t.length===0||t.length==null)return;this._buf=String(t),this.ii=-1,this.char=-1;let r;for(;r===!1||this.nextChar();)r=this.runOne();this._buf=null}nextChar(){return this.char===10&&(++this.line,this.col=-1),++this.ii,this.char=this._buf.codePointAt(this.ii),++this.pos,++this.col,this.haveBuffer()}haveBuffer(){return this.ii<this._buf.length}runOne(){return this.state.parser.call(this,this.state.returned)}finish(){this.char=1114112;let t;do t=this.state.parser,this.runOne();while(this.state.parser!==t);return this.ctx=null,this.state=null,this._buf=null,this.obj}next(t){if(typeof t!="function")throw new bi("Tried to set state to non-existent state: "+JSON.stringify(t));this.state.parser=t}goto(t){return this.next(t),this.runOne()}call(t,r){r&&this.next(r),this.stack.push(this.state),this.state=new vl(t)}callNow(t,r){return this.call(t,r),this.runOne()}return(t){if(this.stack.length===0)throw this.error(new bi("Stack underflow"));t===void 0&&(t=this.state.buf),this.state=this.stack.pop(),this.state.returned=t}returnNow(t){return this.return(t),this.runOne()}consume(){if(this.char===1114112)throw this.error(new bi("Unexpected end-of-buffer"));this.state.buf+=this._buf[this.ii]}error(t){return t.line=this.line,t.col=this.col,t.pos=this.pos,t}parseStart(){throw new bi("Must declare a parseStart method")}};ca.END=1114112;ca.Error=bi;QS.exports=ca});var rI=He((Ire,tI)=>{"use strict";tI.exports=e=>{let t=new Date(e);if(isNaN(t))throw new TypeError("Invalid Datetime");return t}});var Sl=He((Tre,nI)=>{"use strict";nI.exports=(e,t)=>{for(t=String(t);t.length<e;)t="0"+t;return t}});var oI=He((Are,iI)=>{"use strict";var Zo=Sl(),bf=class extends Date{constructor(t){super(t+"Z"),this.isFloating=!0}toISOString(){let t=`${this.getUTCFullYear()}-${Zo(2,this.getUTCMonth()+1)}-${Zo(2,this.getUTCDate())}`,r=`${Zo(2,this.getUTCHours())}:${Zo(2,this.getUTCMinutes())}:${Zo(2,this.getUTCSeconds())}.${Zo(3,this.getUTCMilliseconds())}`;return`${t}T${r}`}};iI.exports=e=>{let t=new bf(e);if(isNaN(t))throw new TypeError("Invalid Datetime");return t}});var cI=He(($re,aI)=>{"use strict";var sI=Sl(),kH=global.Date,xf=class extends kH{constructor(t){super(t),this.isDate=!0}toISOString(){return`${this.getUTCFullYear()}-${sI(2,this.getUTCMonth()+1)}-${sI(2,this.getUTCDate())}`}};aI.exports=e=>{let t=new xf(e);if(isNaN(t))throw new TypeError("Invalid Datetime");return t}});var uI=He((Cre,lI)=>{"use strict";var Il=Sl(),Ef=class extends Date{constructor(t){super(`0000-01-01T${t}Z`),this.isTime=!0}toISOString(){return`${Il(2,this.getUTCHours())}:${Il(2,this.getUTCMinutes())}:${Il(2,this.getUTCSeconds())}.${Il(3,this.getUTCMilliseconds())}`}};lI.exports=e=>{let t=new Ef(e);if(isNaN(t))throw new TypeError("Invalid Datetime");return t}});var Tl=He((exports,module)=>{"use strict";module.exports=makeParserClass(eI());module.exports.makeParserClass=makeParserClass;var TomlError=class e extends Error{constructor(t){super(t),this.name="TomlError",Error.captureStackTrace&&Error.captureStackTrace(this,e),this.fromTOML=!0,this.wrapped=null}};TomlError.wrap=e=>{let t=new TomlError(e.message);return t.code=e.code,t.wrapped=e,t};module.exports.TomlError=TomlError;var createDateTime=rI(),createDateTimeFloat=oI(),createDate=cI(),createTime=uI(),CTRL_I=9,CTRL_J=10,CTRL_M=13,CTRL_CHAR_BOUNDARY=31,CHAR_SP=32,CHAR_QUOT=34,CHAR_NUM=35,CHAR_APOS=39,CHAR_PLUS=43,CHAR_COMMA=44,CHAR_HYPHEN=45,CHAR_PERIOD=46,CHAR_0=48,CHAR_1=49,CHAR_7=55,CHAR_9=57,CHAR_COLON=58,CHAR_EQUALS=61,CHAR_A=65,CHAR_E=69,CHAR_F=70,CHAR_T=84,CHAR_U=85,CHAR_Z=90,CHAR_LOWBAR=95,CHAR_a=97,CHAR_b=98,CHAR_e=101,CHAR_f=102,CHAR_i=105,CHAR_l=108,CHAR_n=110,CHAR_o=111,CHAR_r=114,CHAR_s=115,CHAR_t=116,CHAR_u=117,CHAR_x=120,CHAR_z=122,CHAR_LCUB=123,CHAR_RCUB=125,CHAR_LSQB=91,CHAR_BSOL=92,CHAR_RSQB=93,CHAR_DEL=127,SURROGATE_FIRST=55296,SURROGATE_LAST=57343,escapes={[CHAR_b]:"\b",[CHAR_t]:" ",[CHAR_n]:`
826
- `,[CHAR_f]:"\f",[CHAR_r]:"\r",[CHAR_QUOT]:'"',[CHAR_BSOL]:"\\"};function isDigit(e){return e>=CHAR_0&&e<=CHAR_9}function isHexit(e){return e>=CHAR_A&&e<=CHAR_F||e>=CHAR_a&&e<=CHAR_f||e>=CHAR_0&&e<=CHAR_9}function isBit(e){return e===CHAR_1||e===CHAR_0}function isOctit(e){return e>=CHAR_0&&e<=CHAR_7}function isAlphaNumQuoteHyphen(e){return e>=CHAR_A&&e<=CHAR_Z||e>=CHAR_a&&e<=CHAR_z||e>=CHAR_0&&e<=CHAR_9||e===CHAR_APOS||e===CHAR_QUOT||e===CHAR_LOWBAR||e===CHAR_HYPHEN}function isAlphaNumHyphen(e){return e>=CHAR_A&&e<=CHAR_Z||e>=CHAR_a&&e<=CHAR_z||e>=CHAR_0&&e<=CHAR_9||e===CHAR_LOWBAR||e===CHAR_HYPHEN}var _type=Symbol("type"),_declared=Symbol("declared"),hasOwnProperty=Object.prototype.hasOwnProperty,defineProperty=Object.defineProperty,descriptor={configurable:!0,enumerable:!0,writable:!0,value:void 0};function hasKey(e,t){return hasOwnProperty.call(e,t)?!0:(t==="__proto__"&&defineProperty(e,"__proto__",descriptor),!1)}var INLINE_TABLE=Symbol("inline-table");function InlineTable(){return Object.defineProperties({},{[_type]:{value:INLINE_TABLE}})}function isInlineTable(e){return e===null||typeof e!="object"?!1:e[_type]===INLINE_TABLE}var TABLE=Symbol("table");function Table(){return Object.defineProperties({},{[_type]:{value:TABLE},[_declared]:{value:!1,writable:!0}})}function isTable(e){return e===null||typeof e!="object"?!1:e[_type]===TABLE}var _contentType=Symbol("content-type"),INLINE_LIST=Symbol("inline-list");function InlineList(e){return Object.defineProperties([],{[_type]:{value:INLINE_LIST},[_contentType]:{value:e}})}function isInlineList(e){return e===null||typeof e!="object"?!1:e[_type]===INLINE_LIST}var LIST=Symbol("list");function List(){return Object.defineProperties([],{[_type]:{value:LIST}})}function isList(e){return e===null||typeof e!="object"?!1:e[_type]===LIST}var _custom;try{let utilInspect=eval("require('util').inspect");_custom=utilInspect.custom}catch(e){}var _inspect=_custom||"inspect",BoxedBigInt=class{constructor(t){try{this.value=global.BigInt.asIntN(64,t)}catch{this.value=null}Object.defineProperty(this,_type,{value:INTEGER})}isNaN(){return this.value===null}toString(){return String(this.value)}[_inspect](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}},INTEGER=Symbol("integer");function Integer(e){let t=Number(e);return Object.is(t,-0)&&(t=0),global.BigInt&&!Number.isSafeInteger(t)?new BoxedBigInt(e):Object.defineProperties(new Number(t),{isNaN:{value:function(){return isNaN(this)}},[_type]:{value:INTEGER},[_inspect]:{value:()=>`[Integer: ${e}]`}})}function isInteger(e){return e===null||typeof e!="object"?!1:e[_type]===INTEGER}var FLOAT=Symbol("float");function Float(e){return Object.defineProperties(new Number(e),{[_type]:{value:FLOAT},[_inspect]:{value:()=>`[Float: ${e}]`}})}function isFloat(e){return e===null||typeof e!="object"?!1:e[_type]===FLOAT}function tomlType(e){let t=typeof e;if(t==="object"){if(e===null)return"null";if(e instanceof Date)return"datetime";if(_type in e)switch(e[_type]){case INLINE_TABLE:return"inline-table";case INLINE_LIST:return"inline-list";case TABLE:return"table";case LIST:return"list";case FLOAT:return"float";case INTEGER:return"integer"}}return t}function makeParserClass(e){class t extends e{constructor(){super(),this.ctx=this.obj=Table()}atEndOfWord(){return this.char===CHAR_NUM||this.char===CTRL_I||this.char===CHAR_SP||this.atEndOfLine()}atEndOfLine(){return this.char===e.END||this.char===CTRL_J||this.char===CTRL_M}parseStart(){if(this.char===e.END)return null;if(this.char===CHAR_LSQB)return this.call(this.parseTableOrList);if(this.char===CHAR_NUM)return this.call(this.parseComment);if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M)return null;if(isAlphaNumQuoteHyphen(this.char))return this.callNow(this.parseAssignStatement);throw this.error(new TomlError(`Unknown character "${this.char}"`))}parseWhitespaceToEOL(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M)return null;if(this.char===CHAR_NUM)return this.goto(this.parseComment);if(this.char===e.END||this.char===CTRL_J)return this.return();throw this.error(new TomlError("Unexpected character, expected only whitespace or comments till end of line"))}parseAssignStatement(){return this.callNow(this.parseAssign,this.recordAssignStatement)}recordAssignStatement(n){let i=this.ctx,o=n.key.pop();for(let s of n.key){if(hasKey(i,s)&&(!isTable(i[s])||i[s][_declared]))throw this.error(new TomlError("Can't redefine existing key"));i=i[s]=i[s]||Table()}if(hasKey(i,o))throw this.error(new TomlError("Can't redefine existing key"));return isInteger(n.value)||isFloat(n.value)?i[o]=n.value.valueOf():i[o]=n.value,this.goto(this.parseWhitespaceToEOL)}parseAssign(){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}recordAssignKeyword(n){return this.state.resultTable?this.state.resultTable.push(n):this.state.resultTable=[n],this.goto(this.parseAssignKeywordPreDot)}parseAssignKeywordPreDot(){if(this.char===CHAR_PERIOD)return this.next(this.parseAssignKeywordPostDot);if(this.char!==CHAR_SP&&this.char!==CTRL_I)return this.goto(this.parseAssignEqual)}parseAssignKeywordPostDot(){if(this.char!==CHAR_SP&&this.char!==CTRL_I)return this.callNow(this.parseKeyword,this.recordAssignKeyword)}parseAssignEqual(){if(this.char===CHAR_EQUALS)return this.next(this.parseAssignPreValue);throw this.error(new TomlError('Invalid character, expected "="'))}parseAssignPreValue(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseValue,this.recordAssignValue)}recordAssignValue(n){return this.returnNow({key:this.state.resultTable,value:n})}parseComment(){do if(this.char===e.END||this.char===CTRL_J)return this.return();while(this.nextChar())}parseTableOrList(){if(this.char===CHAR_LSQB)this.next(this.parseList);else return this.goto(this.parseTable)}parseTable(){return this.ctx=this.obj,this.goto(this.parseTableNext)}parseTableNext(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseKeyword,this.parseTableMore)}parseTableMore(n){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CHAR_RSQB){if(hasKey(this.ctx,n)&&(!isTable(this.ctx[n])||this.ctx[n][_declared]))throw this.error(new TomlError("Can't redefine existing key"));return this.ctx=this.ctx[n]=this.ctx[n]||Table(),this.ctx[_declared]=!0,this.next(this.parseWhitespaceToEOL)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,n))this.ctx=this.ctx[n]=Table();else if(isTable(this.ctx[n]))this.ctx=this.ctx[n];else if(isList(this.ctx[n]))this.ctx=this.ctx[n][this.ctx[n].length-1];else throw this.error(new TomlError("Can't redefine existing key"));return this.next(this.parseTableNext)}else throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}parseList(){return this.ctx=this.obj,this.goto(this.parseListNext)}parseListNext(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseKeyword,this.parseListMore)}parseListMore(n){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CHAR_RSQB){if(hasKey(this.ctx,n)||(this.ctx[n]=List()),isInlineList(this.ctx[n]))throw this.error(new TomlError("Can't extend an inline array"));if(isList(this.ctx[n])){let i=Table();this.ctx[n].push(i),this.ctx=i}else throw this.error(new TomlError("Can't redefine an existing key"));return this.next(this.parseListEnd)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,n))this.ctx=this.ctx[n]=Table();else{if(isInlineList(this.ctx[n]))throw this.error(new TomlError("Can't extend an inline array"));if(isInlineTable(this.ctx[n]))throw this.error(new TomlError("Can't extend an inline table"));if(isList(this.ctx[n]))this.ctx=this.ctx[n][this.ctx[n].length-1];else if(isTable(this.ctx[n]))this.ctx=this.ctx[n];else throw this.error(new TomlError("Can't redefine an existing key"))}return this.next(this.parseListNext)}else throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}parseListEnd(n){if(this.char===CHAR_RSQB)return this.next(this.parseWhitespaceToEOL);throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}parseValue(){if(this.char===e.END)throw this.error(new TomlError("Key without value"));if(this.char===CHAR_QUOT)return this.next(this.parseDoubleString);if(this.char===CHAR_APOS)return this.next(this.parseSingleString);if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)return this.goto(this.parseNumberSign);if(this.char===CHAR_i)return this.next(this.parseInf);if(this.char===CHAR_n)return this.next(this.parseNan);if(isDigit(this.char))return this.goto(this.parseNumberOrDateTime);if(this.char===CHAR_t||this.char===CHAR_f)return this.goto(this.parseBoolean);if(this.char===CHAR_LSQB)return this.call(this.parseInlineList,this.recordValue);if(this.char===CHAR_LCUB)return this.call(this.parseInlineTable,this.recordValue);throw this.error(new TomlError("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"))}recordValue(n){return this.returnNow(n)}parseInf(){if(this.char===CHAR_n)return this.next(this.parseInf2);throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseInf2(){if(this.char===CHAR_f)return this.state.buf==="-"?this.return(-1/0):this.return(1/0);throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseNan(){if(this.char===CHAR_a)return this.next(this.parseNan2);throw this.error(new TomlError('Unexpected character, expected "nan"'))}parseNan2(){if(this.char===CHAR_n)return this.return(NaN);throw this.error(new TomlError('Unexpected character, expected "nan"'))}parseKeyword(){return this.char===CHAR_QUOT?this.next(this.parseBasicString):this.char===CHAR_APOS?this.next(this.parseLiteralString):this.goto(this.parseBareKey)}parseBareKey(){do{if(this.char===e.END)throw this.error(new TomlError("Key ended without value"));if(isAlphaNumHyphen(this.char))this.consume();else{if(this.state.buf.length===0)throw this.error(new TomlError("Empty bare keys are not allowed"));return this.returnNow()}}while(this.nextChar())}parseSingleString(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiStringMaybe):this.goto(this.parseLiteralString)}parseLiteralString(){do{if(this.char===CHAR_APOS)return this.return();if(this.atEndOfLine())throw this.error(new TomlError("Unterminated string"));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}parseLiteralMultiStringMaybe(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiString):this.returnNow()}parseLiteralMultiString(){return this.char===CTRL_M?null:this.char===CTRL_J?this.next(this.parseLiteralMultiStringContent):this.goto(this.parseLiteralMultiStringContent)}parseLiteralMultiStringContent(){do{if(this.char===CHAR_APOS)return this.next(this.parseLiteralMultiEnd);if(this.char===e.END)throw this.error(new TomlError("Unterminated multi-line string"));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}parseLiteralMultiEnd(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiEnd2):(this.state.buf+="'",this.goto(this.parseLiteralMultiStringContent))}parseLiteralMultiEnd2(){return this.char===CHAR_APOS?this.return():(this.state.buf+="''",this.goto(this.parseLiteralMultiStringContent))}parseDoubleString(){return this.char===CHAR_QUOT?this.next(this.parseMultiStringMaybe):this.goto(this.parseBasicString)}parseBasicString(){do{if(this.char===CHAR_BSOL)return this.call(this.parseEscape,this.recordEscapeReplacement);if(this.char===CHAR_QUOT)return this.return();if(this.atEndOfLine())throw this.error(new TomlError("Unterminated string"));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}recordEscapeReplacement(n){return this.state.buf+=n,this.goto(this.parseBasicString)}parseMultiStringMaybe(){return this.char===CHAR_QUOT?this.next(this.parseMultiString):this.returnNow()}parseMultiString(){return this.char===CTRL_M?null:this.char===CTRL_J?this.next(this.parseMultiStringContent):this.goto(this.parseMultiStringContent)}parseMultiStringContent(){do{if(this.char===CHAR_BSOL)return this.call(this.parseMultiEscape,this.recordMultiEscapeReplacement);if(this.char===CHAR_QUOT)return this.next(this.parseMultiEnd);if(this.char===e.END)throw this.error(new TomlError("Unterminated multi-line string"));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}errorControlCharInString(){let n="\\u00";return this.char<16&&(n+="0"),n+=this.char.toString(16),this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${n} instead`))}recordMultiEscapeReplacement(n){return this.state.buf+=n,this.goto(this.parseMultiStringContent)}parseMultiEnd(){return this.char===CHAR_QUOT?this.next(this.parseMultiEnd2):(this.state.buf+='"',this.goto(this.parseMultiStringContent))}parseMultiEnd2(){return this.char===CHAR_QUOT?this.return():(this.state.buf+='""',this.goto(this.parseMultiStringContent))}parseMultiEscape(){return this.char===CTRL_M||this.char===CTRL_J?this.next(this.parseMultiTrim):this.char===CHAR_SP||this.char===CTRL_I?this.next(this.parsePreMultiTrim):this.goto(this.parseEscape)}parsePreMultiTrim(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CTRL_M||this.char===CTRL_J)return this.next(this.parseMultiTrim);throw this.error(new TomlError("Can't escape whitespace"))}parseMultiTrim(){return this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M?null:this.returnNow()}parseEscape(){if(this.char in escapes)return this.return(escapes[this.char]);if(this.char===CHAR_u)return this.call(this.parseSmallUnicode,this.parseUnicodeReturn);if(this.char===CHAR_U)return this.call(this.parseLargeUnicode,this.parseUnicodeReturn);throw this.error(new TomlError("Unknown escape character: "+this.char))}parseUnicodeReturn(n){try{let i=parseInt(n,16);if(i>=SURROGATE_FIRST&&i<=SURROGATE_LAST)throw this.error(new TomlError("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"));return this.returnNow(String.fromCodePoint(i))}catch(i){throw this.error(TomlError.wrap(i))}}parseSmallUnicode(){if(isHexit(this.char)){if(this.consume(),this.state.buf.length>=4)return this.return()}else throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}parseLargeUnicode(){if(isHexit(this.char)){if(this.consume(),this.state.buf.length>=8)return this.return()}else throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}parseNumberSign(){return this.consume(),this.next(this.parseMaybeSignedInfOrNan)}parseMaybeSignedInfOrNan(){return this.char===CHAR_i?this.next(this.parseInf):this.char===CHAR_n?this.next(this.parseNan):this.callNow(this.parseNoUnder,this.parseNumberIntegerStart)}parseNumberIntegerStart(){return this.char===CHAR_0?(this.consume(),this.next(this.parseNumberIntegerExponentOrDecimal)):this.goto(this.parseNumberInteger)}parseNumberIntegerExponentOrDecimal(){return this.char===CHAR_PERIOD?(this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat)):this.char===CHAR_E||this.char===CHAR_e?(this.consume(),this.next(this.parseNumberExponentSign)):this.returnNow(Integer(this.state.buf))}parseNumberInteger(){if(isDigit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder);if(this.char===CHAR_E||this.char===CHAR_e)return this.consume(),this.next(this.parseNumberExponentSign);if(this.char===CHAR_PERIOD)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);{let n=Integer(this.state.buf);if(n.isNaN())throw this.error(new TomlError("Invalid number"));return this.returnNow(n)}}}parseNoUnder(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD||this.char===CHAR_E||this.char===CHAR_e)throw this.error(new TomlError("Unexpected character, expected digit"));if(this.atEndOfWord())throw this.error(new TomlError("Incomplete number"));return this.returnNow()}parseNoUnderHexOctBinLiteral(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD)throw this.error(new TomlError("Unexpected character, expected digit"));if(this.atEndOfWord())throw this.error(new TomlError("Incomplete number"));return this.returnNow()}parseNumberFloat(){if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder,this.parseNumberFloat);if(isDigit(this.char))this.consume();else return this.char===CHAR_E||this.char===CHAR_e?(this.consume(),this.next(this.parseNumberExponentSign)):this.returnNow(Float(this.state.buf))}parseNumberExponentSign(){if(isDigit(this.char))return this.goto(this.parseNumberExponent);if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.call(this.parseNoUnder,this.parseNumberExponent);else throw this.error(new TomlError("Unexpected character, expected -, + or digit"))}parseNumberExponent(){if(isDigit(this.char))this.consume();else return this.char===CHAR_LOWBAR?this.call(this.parseNoUnder):this.returnNow(Float(this.state.buf))}parseNumberOrDateTime(){return this.char===CHAR_0?(this.consume(),this.next(this.parseNumberBaseOrDateTime)):this.goto(this.parseNumberOrDateTimeOnly)}parseNumberOrDateTimeOnly(){if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder,this.parseNumberInteger);if(isDigit(this.char))this.consume(),this.state.buf.length>4&&this.next(this.parseNumberInteger);else return this.char===CHAR_E||this.char===CHAR_e?(this.consume(),this.next(this.parseNumberExponentSign)):this.char===CHAR_PERIOD?(this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat)):this.char===CHAR_HYPHEN?this.goto(this.parseDateTime):this.char===CHAR_COLON?this.goto(this.parseOnlyTimeHour):this.returnNow(Integer(this.state.buf))}parseDateTimeOnly(){if(this.state.buf.length<4){if(isDigit(this.char))return this.consume();if(this.char===CHAR_COLON)return this.goto(this.parseOnlyTimeHour);throw this.error(new TomlError("Expected digit while parsing year part of a date"))}else{if(this.char===CHAR_HYPHEN)return this.goto(this.parseDateTime);throw this.error(new TomlError("Expected hyphen (-) while parsing year part of date"))}}parseNumberBaseOrDateTime(){return this.char===CHAR_b?(this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerBin)):this.char===CHAR_o?(this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerOct)):this.char===CHAR_x?(this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerHex)):this.char===CHAR_PERIOD?this.goto(this.parseNumberInteger):isDigit(this.char)?this.goto(this.parseDateTimeOnly):this.returnNow(Integer(this.state.buf))}parseIntegerHex(){if(isHexit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);{let n=Integer(this.state.buf);if(n.isNaN())throw this.error(new TomlError("Invalid number"));return this.returnNow(n)}}}parseIntegerOct(){if(isOctit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);{let n=Integer(this.state.buf);if(n.isNaN())throw this.error(new TomlError("Invalid number"));return this.returnNow(n)}}}parseIntegerBin(){if(isBit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);{let n=Integer(this.state.buf);if(n.isNaN())throw this.error(new TomlError("Invalid number"));return this.returnNow(n)}}}parseDateTime(){if(this.state.buf.length<4)throw this.error(new TomlError("Years less than 1000 must be zero padded to four characters"));return this.state.result=this.state.buf,this.state.buf="",this.next(this.parseDateMonth)}parseDateMonth(){if(this.char===CHAR_HYPHEN){if(this.state.buf.length<2)throw this.error(new TomlError("Months less than 10 must be zero padded to two characters"));return this.state.result+="-"+this.state.buf,this.state.buf="",this.next(this.parseDateDay)}else if(isDigit(this.char))this.consume();else throw this.error(new TomlError("Incomplete datetime"))}parseDateDay(){if(this.char===CHAR_T||this.char===CHAR_SP){if(this.state.buf.length<2)throw this.error(new TomlError("Days less than 10 must be zero padded to two characters"));return this.state.result+="-"+this.state.buf,this.state.buf="",this.next(this.parseStartTimeHour)}else{if(this.atEndOfWord())return this.returnNow(createDate(this.state.result+"-"+this.state.buf));if(isDigit(this.char))this.consume();else throw this.error(new TomlError("Incomplete datetime"))}}parseStartTimeHour(){return this.atEndOfWord()?this.returnNow(createDate(this.state.result)):this.goto(this.parseTimeHour)}parseTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2)throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));return this.state.result+="T"+this.state.buf,this.state.buf="",this.next(this.parseTimeMin)}else if(isDigit(this.char))this.consume();else throw this.error(new TomlError("Incomplete datetime"))}parseTimeMin(){if(this.state.buf.length<2&&isDigit(this.char))this.consume();else{if(this.state.buf.length===2&&this.char===CHAR_COLON)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseTimeSec);throw this.error(new TomlError("Incomplete datetime"))}}parseTimeSec(){if(isDigit(this.char)){if(this.consume(),this.state.buf.length===2)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseTimeZoneOrFraction)}else throw this.error(new TomlError("Incomplete datetime"))}parseOnlyTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2)throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));return this.state.result=this.state.buf,this.state.buf="",this.next(this.parseOnlyTimeMin)}else throw this.error(new TomlError("Incomplete time"))}parseOnlyTimeMin(){if(this.state.buf.length<2&&isDigit(this.char))this.consume();else{if(this.state.buf.length===2&&this.char===CHAR_COLON)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseOnlyTimeSec);throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeSec(){if(isDigit(this.char)){if(this.consume(),this.state.buf.length===2)return this.next(this.parseOnlyTimeFractionMaybe)}else throw this.error(new TomlError("Incomplete time"))}parseOnlyTimeFractionMaybe(){if(this.state.result+=":"+this.state.buf,this.char===CHAR_PERIOD)this.state.buf="",this.next(this.parseOnlyTimeFraction);else return this.return(createTime(this.state.result))}parseOnlyTimeFraction(){if(isDigit(this.char))this.consume();else if(this.atEndOfWord()){if(this.state.buf.length===0)throw this.error(new TomlError("Expected digit in milliseconds"));return this.returnNow(createTime(this.state.result+"."+this.state.buf))}else throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseTimeZoneOrFraction(){if(this.char===CHAR_PERIOD)this.consume(),this.next(this.parseDateTimeFraction);else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.next(this.parseTimeZoneHour);else{if(this.char===CHAR_Z)return this.consume(),this.return(createDateTime(this.state.result+this.state.buf));if(this.atEndOfWord())return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf));throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseDateTimeFraction(){if(isDigit(this.char))this.consume();else{if(this.state.buf.length===1)throw this.error(new TomlError("Expected digit in milliseconds"));if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.next(this.parseTimeZoneHour);else{if(this.char===CHAR_Z)return this.consume(),this.return(createDateTime(this.state.result+this.state.buf));if(this.atEndOfWord())return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf));throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}}parseTimeZoneHour(){if(isDigit(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.next(this.parseTimeZoneSep)}else throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}parseTimeZoneSep(){if(this.char===CHAR_COLON)this.consume(),this.next(this.parseTimeZoneMin);else throw this.error(new TomlError("Unexpected character in datetime, expected colon"))}parseTimeZoneMin(){if(isDigit(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.return(createDateTime(this.state.result+this.state.buf))}else throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}parseBoolean(){if(this.char===CHAR_t)return this.consume(),this.next(this.parseTrue_r);if(this.char===CHAR_f)return this.consume(),this.next(this.parseFalse_a)}parseTrue_r(){if(this.char===CHAR_r)return this.consume(),this.next(this.parseTrue_u);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseTrue_u(){if(this.char===CHAR_u)return this.consume(),this.next(this.parseTrue_e);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseTrue_e(){if(this.char===CHAR_e)return this.return(!0);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_a(){if(this.char===CHAR_a)return this.consume(),this.next(this.parseFalse_l);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_l(){if(this.char===CHAR_l)return this.consume(),this.next(this.parseFalse_s);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_s(){if(this.char===CHAR_s)return this.consume(),this.next(this.parseFalse_e);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_e(){if(this.char===CHAR_e)return this.return(!1);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseInlineList(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J)return null;if(this.char===e.END)throw this.error(new TomlError("Unterminated inline array"));return this.char===CHAR_NUM?this.call(this.parseComment):this.char===CHAR_RSQB?this.return(this.state.resultArr||InlineList()):this.callNow(this.parseValue,this.recordInlineListValue)}recordInlineListValue(n){if(this.state.resultArr){let i=this.state.resultArr[_contentType],o=tomlType(n);if(i!==o)throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${i} and ${o}`))}else this.state.resultArr=InlineList(tomlType(n));return isFloat(n)||isInteger(n)?this.state.resultArr.push(n.valueOf()):this.state.resultArr.push(n),this.goto(this.parseInlineListNext)}parseInlineListNext(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J)return null;if(this.char===CHAR_NUM)return this.call(this.parseComment);if(this.char===CHAR_COMMA)return this.next(this.parseInlineList);if(this.char===CHAR_RSQB)return this.goto(this.parseInlineList);throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}parseInlineTable(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===e.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M)throw this.error(new TomlError("Unterminated inline array"));return this.char===CHAR_RCUB?this.return(this.state.resultTable||InlineTable()):(this.state.resultTable||(this.state.resultTable=InlineTable()),this.callNow(this.parseAssign,this.recordInlineTableValue))}recordInlineTableValue(n){let i=this.state.resultTable,o=n.key.pop();for(let s of n.key){if(hasKey(i,s)&&(!isTable(i[s])||i[s][_declared]))throw this.error(new TomlError("Can't redefine existing key"));i=i[s]=i[s]||Table()}if(hasKey(i,o))throw this.error(new TomlError("Can't redefine existing key"));return isInteger(n.value)||isFloat(n.value)?i[o]=n.value.valueOf():i[o]=n.value,this.goto(this.parseInlineTableNext)}parseInlineTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===e.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M)throw this.error(new TomlError("Unterminated inline array"));if(this.char===CHAR_COMMA)return this.next(this.parseInlineTable);if(this.char===CHAR_RCUB)return this.goto(this.parseInlineTable);throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}return t}});var Al=He((kre,dI)=>{"use strict";dI.exports=RH;function RH(e,t){if(e.pos==null||e.line==null)return e;let r=e.message;if(r+=` at row ${e.line+1}, col ${e.col+1}, pos ${e.pos}:
825
+ `)+mn({transport:"mcp"})}async function JS({dryRun:e=!1}={}){let t=await import("node:fs/promises");e||await t.mkdir(EH(_i),{recursive:!0});let r=await ge(_i,TH(),{dryRun:e});return{action:r.action,path:_i,detail:`${r.bytes??0} bytes, alwaysApply=true`}}async function AH({dryRun:e=!1}={}){let t=[],r=await zS({dryRun:e});r&&t.push(r);let n=await JS({dryRun:e});return n&&t.push(n),{actions:t}}async function $H({deep:e=!1}={}){let t=await import("node:fs/promises");if(!gn(ct))return{installed:!1,reason:"~/.cursor/mcp.json missing"};let r;try{r=JSON.parse(await t.readFile(ct,"utf8"))}catch{return{installed:!1,reason:"~/.cursor/mcp.json is not valid JSON"}}if(!r.mcpServers?.sigil)return{installed:!1,reason:"sigil entry missing from ~/.cursor/mcp.json"};if(!gn(_i))return{installed:!1,reason:"~/.cursor/rules/sigil.mdc missing"};if(!gn(et))return{installed:!1,reason:`MCP launcher missing at ${et} \u2014 run \`sigil connect\``};let n=YS();if(!gn(n))return{installed:!1,reason:`MCP server missing at ${n} \u2014 run \`sigil connect\` to refresh`};if(e){let{verifyMcpRoundTrip:i}=await Promise.resolve().then(()=>(oa(),ia)),o=await i(n);if(!o.ok)return{installed:!1,reason:`MCP round-trip failed: ${o.reason}`}}return{installed:!0}}async function CH({dryRun:e=!1}={}){let t=await import("node:fs/promises"),r=[];if(gn(ct)){let n;try{n=JSON.parse(await t.readFile(ct,"utf8"))}catch{return r.push({action:"skip",path:ct,detail:"invalid JSON \u2014 not touched"}),{actions:r}}if(n.mcpServers?.sigil){delete n.mcpServers.sigil;let i=await ge(ct,JSON.stringify(n,null,2),{dryRun:e});r.push({action:i.action,path:ct,detail:"-sigil MCP entry"})}else r.push({action:"skip",path:ct,detail:"sigil entry not present"})}return gn(_i)&&(e||await t.unlink(_i),r.push({action:"delete",path:_i,detail:"sigil rules file removed"})),{actions:r}}var El,ct,_i,qS,SH,XS=f(()=>{K();dn();Jo();Yo();fn();El=aa(vH(),".cursor"),ct=aa(El,"mcp.json"),_i=aa(El,"rules","sigil.mdc"),qS=ue,SH={id:"cursor",label:"Cursor",hint:"global MCP + always-applied rule (no native hooks)"}});var eI=He((Ire,QS)=>{"use strict";var bi=class e extends Error{constructor(t,r,n){super("[ParserError] "+t,r,n),this.name="ParserError",this.code="ParserError",Error.captureStackTrace&&Error.captureStackTrace(this,e)}},vl=class{constructor(t){this.parser=t,this.buf="",this.returned=null,this.result=null,this.resultTable=null,this.resultArr=null}},ca=class{constructor(){this.pos=0,this.col=0,this.line=0,this.obj={},this.ctx=this.obj,this.stack=[],this._buf="",this.char=null,this.ii=0,this.state=new vl(this.parseStart)}parse(t){if(t.length===0||t.length==null)return;this._buf=String(t),this.ii=-1,this.char=-1;let r;for(;r===!1||this.nextChar();)r=this.runOne();this._buf=null}nextChar(){return this.char===10&&(++this.line,this.col=-1),++this.ii,this.char=this._buf.codePointAt(this.ii),++this.pos,++this.col,this.haveBuffer()}haveBuffer(){return this.ii<this._buf.length}runOne(){return this.state.parser.call(this,this.state.returned)}finish(){this.char=1114112;let t;do t=this.state.parser,this.runOne();while(this.state.parser!==t);return this.ctx=null,this.state=null,this._buf=null,this.obj}next(t){if(typeof t!="function")throw new bi("Tried to set state to non-existent state: "+JSON.stringify(t));this.state.parser=t}goto(t){return this.next(t),this.runOne()}call(t,r){r&&this.next(r),this.stack.push(this.state),this.state=new vl(t)}callNow(t,r){return this.call(t,r),this.runOne()}return(t){if(this.stack.length===0)throw this.error(new bi("Stack underflow"));t===void 0&&(t=this.state.buf),this.state=this.stack.pop(),this.state.returned=t}returnNow(t){return this.return(t),this.runOne()}consume(){if(this.char===1114112)throw this.error(new bi("Unexpected end-of-buffer"));this.state.buf+=this._buf[this.ii]}error(t){return t.line=this.line,t.col=this.col,t.pos=this.pos,t}parseStart(){throw new bi("Must declare a parseStart method")}};ca.END=1114112;ca.Error=bi;QS.exports=ca});var rI=He((Tre,tI)=>{"use strict";tI.exports=e=>{let t=new Date(e);if(isNaN(t))throw new TypeError("Invalid Datetime");return t}});var Sl=He((Are,nI)=>{"use strict";nI.exports=(e,t)=>{for(t=String(t);t.length<e;)t="0"+t;return t}});var oI=He(($re,iI)=>{"use strict";var Zo=Sl(),bf=class extends Date{constructor(t){super(t+"Z"),this.isFloating=!0}toISOString(){let t=`${this.getUTCFullYear()}-${Zo(2,this.getUTCMonth()+1)}-${Zo(2,this.getUTCDate())}`,r=`${Zo(2,this.getUTCHours())}:${Zo(2,this.getUTCMinutes())}:${Zo(2,this.getUTCSeconds())}.${Zo(3,this.getUTCMilliseconds())}`;return`${t}T${r}`}};iI.exports=e=>{let t=new bf(e);if(isNaN(t))throw new TypeError("Invalid Datetime");return t}});var cI=He((Cre,aI)=>{"use strict";var sI=Sl(),kH=global.Date,xf=class extends kH{constructor(t){super(t),this.isDate=!0}toISOString(){return`${this.getUTCFullYear()}-${sI(2,this.getUTCMonth()+1)}-${sI(2,this.getUTCDate())}`}};aI.exports=e=>{let t=new xf(e);if(isNaN(t))throw new TypeError("Invalid Datetime");return t}});var uI=He((kre,lI)=>{"use strict";var Il=Sl(),Ef=class extends Date{constructor(t){super(`0000-01-01T${t}Z`),this.isTime=!0}toISOString(){return`${Il(2,this.getUTCHours())}:${Il(2,this.getUTCMinutes())}:${Il(2,this.getUTCSeconds())}.${Il(3,this.getUTCMilliseconds())}`}};lI.exports=e=>{let t=new Ef(e);if(isNaN(t))throw new TypeError("Invalid Datetime");return t}});var Tl=He((exports,module)=>{"use strict";module.exports=makeParserClass(eI());module.exports.makeParserClass=makeParserClass;var TomlError=class e extends Error{constructor(t){super(t),this.name="TomlError",Error.captureStackTrace&&Error.captureStackTrace(this,e),this.fromTOML=!0,this.wrapped=null}};TomlError.wrap=e=>{let t=new TomlError(e.message);return t.code=e.code,t.wrapped=e,t};module.exports.TomlError=TomlError;var createDateTime=rI(),createDateTimeFloat=oI(),createDate=cI(),createTime=uI(),CTRL_I=9,CTRL_J=10,CTRL_M=13,CTRL_CHAR_BOUNDARY=31,CHAR_SP=32,CHAR_QUOT=34,CHAR_NUM=35,CHAR_APOS=39,CHAR_PLUS=43,CHAR_COMMA=44,CHAR_HYPHEN=45,CHAR_PERIOD=46,CHAR_0=48,CHAR_1=49,CHAR_7=55,CHAR_9=57,CHAR_COLON=58,CHAR_EQUALS=61,CHAR_A=65,CHAR_E=69,CHAR_F=70,CHAR_T=84,CHAR_U=85,CHAR_Z=90,CHAR_LOWBAR=95,CHAR_a=97,CHAR_b=98,CHAR_e=101,CHAR_f=102,CHAR_i=105,CHAR_l=108,CHAR_n=110,CHAR_o=111,CHAR_r=114,CHAR_s=115,CHAR_t=116,CHAR_u=117,CHAR_x=120,CHAR_z=122,CHAR_LCUB=123,CHAR_RCUB=125,CHAR_LSQB=91,CHAR_BSOL=92,CHAR_RSQB=93,CHAR_DEL=127,SURROGATE_FIRST=55296,SURROGATE_LAST=57343,escapes={[CHAR_b]:"\b",[CHAR_t]:" ",[CHAR_n]:`
826
+ `,[CHAR_f]:"\f",[CHAR_r]:"\r",[CHAR_QUOT]:'"',[CHAR_BSOL]:"\\"};function isDigit(e){return e>=CHAR_0&&e<=CHAR_9}function isHexit(e){return e>=CHAR_A&&e<=CHAR_F||e>=CHAR_a&&e<=CHAR_f||e>=CHAR_0&&e<=CHAR_9}function isBit(e){return e===CHAR_1||e===CHAR_0}function isOctit(e){return e>=CHAR_0&&e<=CHAR_7}function isAlphaNumQuoteHyphen(e){return e>=CHAR_A&&e<=CHAR_Z||e>=CHAR_a&&e<=CHAR_z||e>=CHAR_0&&e<=CHAR_9||e===CHAR_APOS||e===CHAR_QUOT||e===CHAR_LOWBAR||e===CHAR_HYPHEN}function isAlphaNumHyphen(e){return e>=CHAR_A&&e<=CHAR_Z||e>=CHAR_a&&e<=CHAR_z||e>=CHAR_0&&e<=CHAR_9||e===CHAR_LOWBAR||e===CHAR_HYPHEN}var _type=Symbol("type"),_declared=Symbol("declared"),hasOwnProperty=Object.prototype.hasOwnProperty,defineProperty=Object.defineProperty,descriptor={configurable:!0,enumerable:!0,writable:!0,value:void 0};function hasKey(e,t){return hasOwnProperty.call(e,t)?!0:(t==="__proto__"&&defineProperty(e,"__proto__",descriptor),!1)}var INLINE_TABLE=Symbol("inline-table");function InlineTable(){return Object.defineProperties({},{[_type]:{value:INLINE_TABLE}})}function isInlineTable(e){return e===null||typeof e!="object"?!1:e[_type]===INLINE_TABLE}var TABLE=Symbol("table");function Table(){return Object.defineProperties({},{[_type]:{value:TABLE},[_declared]:{value:!1,writable:!0}})}function isTable(e){return e===null||typeof e!="object"?!1:e[_type]===TABLE}var _contentType=Symbol("content-type"),INLINE_LIST=Symbol("inline-list");function InlineList(e){return Object.defineProperties([],{[_type]:{value:INLINE_LIST},[_contentType]:{value:e}})}function isInlineList(e){return e===null||typeof e!="object"?!1:e[_type]===INLINE_LIST}var LIST=Symbol("list");function List(){return Object.defineProperties([],{[_type]:{value:LIST}})}function isList(e){return e===null||typeof e!="object"?!1:e[_type]===LIST}var _custom;try{let utilInspect=eval("require('util').inspect");_custom=utilInspect.custom}catch(e){}var _inspect=_custom||"inspect",BoxedBigInt=class{constructor(t){try{this.value=global.BigInt.asIntN(64,t)}catch{this.value=null}Object.defineProperty(this,_type,{value:INTEGER})}isNaN(){return this.value===null}toString(){return String(this.value)}[_inspect](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}},INTEGER=Symbol("integer");function Integer(e){let t=Number(e);return Object.is(t,-0)&&(t=0),global.BigInt&&!Number.isSafeInteger(t)?new BoxedBigInt(e):Object.defineProperties(new Number(t),{isNaN:{value:function(){return isNaN(this)}},[_type]:{value:INTEGER},[_inspect]:{value:()=>`[Integer: ${e}]`}})}function isInteger(e){return e===null||typeof e!="object"?!1:e[_type]===INTEGER}var FLOAT=Symbol("float");function Float(e){return Object.defineProperties(new Number(e),{[_type]:{value:FLOAT},[_inspect]:{value:()=>`[Float: ${e}]`}})}function isFloat(e){return e===null||typeof e!="object"?!1:e[_type]===FLOAT}function tomlType(e){let t=typeof e;if(t==="object"){if(e===null)return"null";if(e instanceof Date)return"datetime";if(_type in e)switch(e[_type]){case INLINE_TABLE:return"inline-table";case INLINE_LIST:return"inline-list";case TABLE:return"table";case LIST:return"list";case FLOAT:return"float";case INTEGER:return"integer"}}return t}function makeParserClass(e){class t extends e{constructor(){super(),this.ctx=this.obj=Table()}atEndOfWord(){return this.char===CHAR_NUM||this.char===CTRL_I||this.char===CHAR_SP||this.atEndOfLine()}atEndOfLine(){return this.char===e.END||this.char===CTRL_J||this.char===CTRL_M}parseStart(){if(this.char===e.END)return null;if(this.char===CHAR_LSQB)return this.call(this.parseTableOrList);if(this.char===CHAR_NUM)return this.call(this.parseComment);if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M)return null;if(isAlphaNumQuoteHyphen(this.char))return this.callNow(this.parseAssignStatement);throw this.error(new TomlError(`Unknown character "${this.char}"`))}parseWhitespaceToEOL(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M)return null;if(this.char===CHAR_NUM)return this.goto(this.parseComment);if(this.char===e.END||this.char===CTRL_J)return this.return();throw this.error(new TomlError("Unexpected character, expected only whitespace or comments till end of line"))}parseAssignStatement(){return this.callNow(this.parseAssign,this.recordAssignStatement)}recordAssignStatement(n){let i=this.ctx,o=n.key.pop();for(let s of n.key){if(hasKey(i,s)&&(!isTable(i[s])||i[s][_declared]))throw this.error(new TomlError("Can't redefine existing key"));i=i[s]=i[s]||Table()}if(hasKey(i,o))throw this.error(new TomlError("Can't redefine existing key"));return isInteger(n.value)||isFloat(n.value)?i[o]=n.value.valueOf():i[o]=n.value,this.goto(this.parseWhitespaceToEOL)}parseAssign(){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}recordAssignKeyword(n){return this.state.resultTable?this.state.resultTable.push(n):this.state.resultTable=[n],this.goto(this.parseAssignKeywordPreDot)}parseAssignKeywordPreDot(){if(this.char===CHAR_PERIOD)return this.next(this.parseAssignKeywordPostDot);if(this.char!==CHAR_SP&&this.char!==CTRL_I)return this.goto(this.parseAssignEqual)}parseAssignKeywordPostDot(){if(this.char!==CHAR_SP&&this.char!==CTRL_I)return this.callNow(this.parseKeyword,this.recordAssignKeyword)}parseAssignEqual(){if(this.char===CHAR_EQUALS)return this.next(this.parseAssignPreValue);throw this.error(new TomlError('Invalid character, expected "="'))}parseAssignPreValue(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseValue,this.recordAssignValue)}recordAssignValue(n){return this.returnNow({key:this.state.resultTable,value:n})}parseComment(){do if(this.char===e.END||this.char===CTRL_J)return this.return();while(this.nextChar())}parseTableOrList(){if(this.char===CHAR_LSQB)this.next(this.parseList);else return this.goto(this.parseTable)}parseTable(){return this.ctx=this.obj,this.goto(this.parseTableNext)}parseTableNext(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseKeyword,this.parseTableMore)}parseTableMore(n){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CHAR_RSQB){if(hasKey(this.ctx,n)&&(!isTable(this.ctx[n])||this.ctx[n][_declared]))throw this.error(new TomlError("Can't redefine existing key"));return this.ctx=this.ctx[n]=this.ctx[n]||Table(),this.ctx[_declared]=!0,this.next(this.parseWhitespaceToEOL)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,n))this.ctx=this.ctx[n]=Table();else if(isTable(this.ctx[n]))this.ctx=this.ctx[n];else if(isList(this.ctx[n]))this.ctx=this.ctx[n][this.ctx[n].length-1];else throw this.error(new TomlError("Can't redefine existing key"));return this.next(this.parseTableNext)}else throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}parseList(){return this.ctx=this.obj,this.goto(this.parseListNext)}parseListNext(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseKeyword,this.parseListMore)}parseListMore(n){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CHAR_RSQB){if(hasKey(this.ctx,n)||(this.ctx[n]=List()),isInlineList(this.ctx[n]))throw this.error(new TomlError("Can't extend an inline array"));if(isList(this.ctx[n])){let i=Table();this.ctx[n].push(i),this.ctx=i}else throw this.error(new TomlError("Can't redefine an existing key"));return this.next(this.parseListEnd)}else if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,n))this.ctx=this.ctx[n]=Table();else{if(isInlineList(this.ctx[n]))throw this.error(new TomlError("Can't extend an inline array"));if(isInlineTable(this.ctx[n]))throw this.error(new TomlError("Can't extend an inline table"));if(isList(this.ctx[n]))this.ctx=this.ctx[n][this.ctx[n].length-1];else if(isTable(this.ctx[n]))this.ctx=this.ctx[n];else throw this.error(new TomlError("Can't redefine an existing key"))}return this.next(this.parseListNext)}else throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}parseListEnd(n){if(this.char===CHAR_RSQB)return this.next(this.parseWhitespaceToEOL);throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"))}parseValue(){if(this.char===e.END)throw this.error(new TomlError("Key without value"));if(this.char===CHAR_QUOT)return this.next(this.parseDoubleString);if(this.char===CHAR_APOS)return this.next(this.parseSingleString);if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)return this.goto(this.parseNumberSign);if(this.char===CHAR_i)return this.next(this.parseInf);if(this.char===CHAR_n)return this.next(this.parseNan);if(isDigit(this.char))return this.goto(this.parseNumberOrDateTime);if(this.char===CHAR_t||this.char===CHAR_f)return this.goto(this.parseBoolean);if(this.char===CHAR_LSQB)return this.call(this.parseInlineList,this.recordValue);if(this.char===CHAR_LCUB)return this.call(this.parseInlineTable,this.recordValue);throw this.error(new TomlError("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"))}recordValue(n){return this.returnNow(n)}parseInf(){if(this.char===CHAR_n)return this.next(this.parseInf2);throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseInf2(){if(this.char===CHAR_f)return this.state.buf==="-"?this.return(-1/0):this.return(1/0);throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseNan(){if(this.char===CHAR_a)return this.next(this.parseNan2);throw this.error(new TomlError('Unexpected character, expected "nan"'))}parseNan2(){if(this.char===CHAR_n)return this.return(NaN);throw this.error(new TomlError('Unexpected character, expected "nan"'))}parseKeyword(){return this.char===CHAR_QUOT?this.next(this.parseBasicString):this.char===CHAR_APOS?this.next(this.parseLiteralString):this.goto(this.parseBareKey)}parseBareKey(){do{if(this.char===e.END)throw this.error(new TomlError("Key ended without value"));if(isAlphaNumHyphen(this.char))this.consume();else{if(this.state.buf.length===0)throw this.error(new TomlError("Empty bare keys are not allowed"));return this.returnNow()}}while(this.nextChar())}parseSingleString(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiStringMaybe):this.goto(this.parseLiteralString)}parseLiteralString(){do{if(this.char===CHAR_APOS)return this.return();if(this.atEndOfLine())throw this.error(new TomlError("Unterminated string"));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}parseLiteralMultiStringMaybe(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiString):this.returnNow()}parseLiteralMultiString(){return this.char===CTRL_M?null:this.char===CTRL_J?this.next(this.parseLiteralMultiStringContent):this.goto(this.parseLiteralMultiStringContent)}parseLiteralMultiStringContent(){do{if(this.char===CHAR_APOS)return this.next(this.parseLiteralMultiEnd);if(this.char===e.END)throw this.error(new TomlError("Unterminated multi-line string"));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}parseLiteralMultiEnd(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiEnd2):(this.state.buf+="'",this.goto(this.parseLiteralMultiStringContent))}parseLiteralMultiEnd2(){return this.char===CHAR_APOS?this.return():(this.state.buf+="''",this.goto(this.parseLiteralMultiStringContent))}parseDoubleString(){return this.char===CHAR_QUOT?this.next(this.parseMultiStringMaybe):this.goto(this.parseBasicString)}parseBasicString(){do{if(this.char===CHAR_BSOL)return this.call(this.parseEscape,this.recordEscapeReplacement);if(this.char===CHAR_QUOT)return this.return();if(this.atEndOfLine())throw this.error(new TomlError("Unterminated string"));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}recordEscapeReplacement(n){return this.state.buf+=n,this.goto(this.parseBasicString)}parseMultiStringMaybe(){return this.char===CHAR_QUOT?this.next(this.parseMultiString):this.returnNow()}parseMultiString(){return this.char===CTRL_M?null:this.char===CTRL_J?this.next(this.parseMultiStringContent):this.goto(this.parseMultiStringContent)}parseMultiStringContent(){do{if(this.char===CHAR_BSOL)return this.call(this.parseMultiEscape,this.recordMultiEscapeReplacement);if(this.char===CHAR_QUOT)return this.next(this.parseMultiEnd);if(this.char===e.END)throw this.error(new TomlError("Unterminated multi-line string"));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}errorControlCharInString(){let n="\\u00";return this.char<16&&(n+="0"),n+=this.char.toString(16),this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${n} instead`))}recordMultiEscapeReplacement(n){return this.state.buf+=n,this.goto(this.parseMultiStringContent)}parseMultiEnd(){return this.char===CHAR_QUOT?this.next(this.parseMultiEnd2):(this.state.buf+='"',this.goto(this.parseMultiStringContent))}parseMultiEnd2(){return this.char===CHAR_QUOT?this.return():(this.state.buf+='""',this.goto(this.parseMultiStringContent))}parseMultiEscape(){return this.char===CTRL_M||this.char===CTRL_J?this.next(this.parseMultiTrim):this.char===CHAR_SP||this.char===CTRL_I?this.next(this.parsePreMultiTrim):this.goto(this.parseEscape)}parsePreMultiTrim(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CTRL_M||this.char===CTRL_J)return this.next(this.parseMultiTrim);throw this.error(new TomlError("Can't escape whitespace"))}parseMultiTrim(){return this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M?null:this.returnNow()}parseEscape(){if(this.char in escapes)return this.return(escapes[this.char]);if(this.char===CHAR_u)return this.call(this.parseSmallUnicode,this.parseUnicodeReturn);if(this.char===CHAR_U)return this.call(this.parseLargeUnicode,this.parseUnicodeReturn);throw this.error(new TomlError("Unknown escape character: "+this.char))}parseUnicodeReturn(n){try{let i=parseInt(n,16);if(i>=SURROGATE_FIRST&&i<=SURROGATE_LAST)throw this.error(new TomlError("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"));return this.returnNow(String.fromCodePoint(i))}catch(i){throw this.error(TomlError.wrap(i))}}parseSmallUnicode(){if(isHexit(this.char)){if(this.consume(),this.state.buf.length>=4)return this.return()}else throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}parseLargeUnicode(){if(isHexit(this.char)){if(this.consume(),this.state.buf.length>=8)return this.return()}else throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"))}parseNumberSign(){return this.consume(),this.next(this.parseMaybeSignedInfOrNan)}parseMaybeSignedInfOrNan(){return this.char===CHAR_i?this.next(this.parseInf):this.char===CHAR_n?this.next(this.parseNan):this.callNow(this.parseNoUnder,this.parseNumberIntegerStart)}parseNumberIntegerStart(){return this.char===CHAR_0?(this.consume(),this.next(this.parseNumberIntegerExponentOrDecimal)):this.goto(this.parseNumberInteger)}parseNumberIntegerExponentOrDecimal(){return this.char===CHAR_PERIOD?(this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat)):this.char===CHAR_E||this.char===CHAR_e?(this.consume(),this.next(this.parseNumberExponentSign)):this.returnNow(Integer(this.state.buf))}parseNumberInteger(){if(isDigit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder);if(this.char===CHAR_E||this.char===CHAR_e)return this.consume(),this.next(this.parseNumberExponentSign);if(this.char===CHAR_PERIOD)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);{let n=Integer(this.state.buf);if(n.isNaN())throw this.error(new TomlError("Invalid number"));return this.returnNow(n)}}}parseNoUnder(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD||this.char===CHAR_E||this.char===CHAR_e)throw this.error(new TomlError("Unexpected character, expected digit"));if(this.atEndOfWord())throw this.error(new TomlError("Incomplete number"));return this.returnNow()}parseNoUnderHexOctBinLiteral(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD)throw this.error(new TomlError("Unexpected character, expected digit"));if(this.atEndOfWord())throw this.error(new TomlError("Incomplete number"));return this.returnNow()}parseNumberFloat(){if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder,this.parseNumberFloat);if(isDigit(this.char))this.consume();else return this.char===CHAR_E||this.char===CHAR_e?(this.consume(),this.next(this.parseNumberExponentSign)):this.returnNow(Float(this.state.buf))}parseNumberExponentSign(){if(isDigit(this.char))return this.goto(this.parseNumberExponent);if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.call(this.parseNoUnder,this.parseNumberExponent);else throw this.error(new TomlError("Unexpected character, expected -, + or digit"))}parseNumberExponent(){if(isDigit(this.char))this.consume();else return this.char===CHAR_LOWBAR?this.call(this.parseNoUnder):this.returnNow(Float(this.state.buf))}parseNumberOrDateTime(){return this.char===CHAR_0?(this.consume(),this.next(this.parseNumberBaseOrDateTime)):this.goto(this.parseNumberOrDateTimeOnly)}parseNumberOrDateTimeOnly(){if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder,this.parseNumberInteger);if(isDigit(this.char))this.consume(),this.state.buf.length>4&&this.next(this.parseNumberInteger);else return this.char===CHAR_E||this.char===CHAR_e?(this.consume(),this.next(this.parseNumberExponentSign)):this.char===CHAR_PERIOD?(this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat)):this.char===CHAR_HYPHEN?this.goto(this.parseDateTime):this.char===CHAR_COLON?this.goto(this.parseOnlyTimeHour):this.returnNow(Integer(this.state.buf))}parseDateTimeOnly(){if(this.state.buf.length<4){if(isDigit(this.char))return this.consume();if(this.char===CHAR_COLON)return this.goto(this.parseOnlyTimeHour);throw this.error(new TomlError("Expected digit while parsing year part of a date"))}else{if(this.char===CHAR_HYPHEN)return this.goto(this.parseDateTime);throw this.error(new TomlError("Expected hyphen (-) while parsing year part of date"))}}parseNumberBaseOrDateTime(){return this.char===CHAR_b?(this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerBin)):this.char===CHAR_o?(this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerOct)):this.char===CHAR_x?(this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerHex)):this.char===CHAR_PERIOD?this.goto(this.parseNumberInteger):isDigit(this.char)?this.goto(this.parseDateTimeOnly):this.returnNow(Integer(this.state.buf))}parseIntegerHex(){if(isHexit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);{let n=Integer(this.state.buf);if(n.isNaN())throw this.error(new TomlError("Invalid number"));return this.returnNow(n)}}}parseIntegerOct(){if(isOctit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);{let n=Integer(this.state.buf);if(n.isNaN())throw this.error(new TomlError("Invalid number"));return this.returnNow(n)}}}parseIntegerBin(){if(isBit(this.char))this.consume();else{if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);{let n=Integer(this.state.buf);if(n.isNaN())throw this.error(new TomlError("Invalid number"));return this.returnNow(n)}}}parseDateTime(){if(this.state.buf.length<4)throw this.error(new TomlError("Years less than 1000 must be zero padded to four characters"));return this.state.result=this.state.buf,this.state.buf="",this.next(this.parseDateMonth)}parseDateMonth(){if(this.char===CHAR_HYPHEN){if(this.state.buf.length<2)throw this.error(new TomlError("Months less than 10 must be zero padded to two characters"));return this.state.result+="-"+this.state.buf,this.state.buf="",this.next(this.parseDateDay)}else if(isDigit(this.char))this.consume();else throw this.error(new TomlError("Incomplete datetime"))}parseDateDay(){if(this.char===CHAR_T||this.char===CHAR_SP){if(this.state.buf.length<2)throw this.error(new TomlError("Days less than 10 must be zero padded to two characters"));return this.state.result+="-"+this.state.buf,this.state.buf="",this.next(this.parseStartTimeHour)}else{if(this.atEndOfWord())return this.returnNow(createDate(this.state.result+"-"+this.state.buf));if(isDigit(this.char))this.consume();else throw this.error(new TomlError("Incomplete datetime"))}}parseStartTimeHour(){return this.atEndOfWord()?this.returnNow(createDate(this.state.result)):this.goto(this.parseTimeHour)}parseTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2)throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));return this.state.result+="T"+this.state.buf,this.state.buf="",this.next(this.parseTimeMin)}else if(isDigit(this.char))this.consume();else throw this.error(new TomlError("Incomplete datetime"))}parseTimeMin(){if(this.state.buf.length<2&&isDigit(this.char))this.consume();else{if(this.state.buf.length===2&&this.char===CHAR_COLON)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseTimeSec);throw this.error(new TomlError("Incomplete datetime"))}}parseTimeSec(){if(isDigit(this.char)){if(this.consume(),this.state.buf.length===2)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseTimeZoneOrFraction)}else throw this.error(new TomlError("Incomplete datetime"))}parseOnlyTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2)throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));return this.state.result=this.state.buf,this.state.buf="",this.next(this.parseOnlyTimeMin)}else throw this.error(new TomlError("Incomplete time"))}parseOnlyTimeMin(){if(this.state.buf.length<2&&isDigit(this.char))this.consume();else{if(this.state.buf.length===2&&this.char===CHAR_COLON)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseOnlyTimeSec);throw this.error(new TomlError("Incomplete time"))}}parseOnlyTimeSec(){if(isDigit(this.char)){if(this.consume(),this.state.buf.length===2)return this.next(this.parseOnlyTimeFractionMaybe)}else throw this.error(new TomlError("Incomplete time"))}parseOnlyTimeFractionMaybe(){if(this.state.result+=":"+this.state.buf,this.char===CHAR_PERIOD)this.state.buf="",this.next(this.parseOnlyTimeFraction);else return this.return(createTime(this.state.result))}parseOnlyTimeFraction(){if(isDigit(this.char))this.consume();else if(this.atEndOfWord()){if(this.state.buf.length===0)throw this.error(new TomlError("Expected digit in milliseconds"));return this.returnNow(createTime(this.state.result+"."+this.state.buf))}else throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseTimeZoneOrFraction(){if(this.char===CHAR_PERIOD)this.consume(),this.next(this.parseDateTimeFraction);else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.next(this.parseTimeZoneHour);else{if(this.char===CHAR_Z)return this.consume(),this.return(createDateTime(this.state.result+this.state.buf));if(this.atEndOfWord())return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf));throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}parseDateTimeFraction(){if(isDigit(this.char))this.consume();else{if(this.state.buf.length===1)throw this.error(new TomlError("Expected digit in milliseconds"));if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.next(this.parseTimeZoneHour);else{if(this.char===CHAR_Z)return this.consume(),this.return(createDateTime(this.state.result+this.state.buf));if(this.atEndOfWord())return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf));throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}}}parseTimeZoneHour(){if(isDigit(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.next(this.parseTimeZoneSep)}else throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}parseTimeZoneSep(){if(this.char===CHAR_COLON)this.consume(),this.next(this.parseTimeZoneMin);else throw this.error(new TomlError("Unexpected character in datetime, expected colon"))}parseTimeZoneMin(){if(isDigit(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.return(createDateTime(this.state.result+this.state.buf))}else throw this.error(new TomlError("Unexpected character in datetime, expected digit"))}parseBoolean(){if(this.char===CHAR_t)return this.consume(),this.next(this.parseTrue_r);if(this.char===CHAR_f)return this.consume(),this.next(this.parseFalse_a)}parseTrue_r(){if(this.char===CHAR_r)return this.consume(),this.next(this.parseTrue_u);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseTrue_u(){if(this.char===CHAR_u)return this.consume(),this.next(this.parseTrue_e);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseTrue_e(){if(this.char===CHAR_e)return this.return(!0);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_a(){if(this.char===CHAR_a)return this.consume(),this.next(this.parseFalse_l);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_l(){if(this.char===CHAR_l)return this.consume(),this.next(this.parseFalse_s);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_s(){if(this.char===CHAR_s)return this.consume(),this.next(this.parseFalse_e);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseFalse_e(){if(this.char===CHAR_e)return this.return(!1);throw this.error(new TomlError("Invalid boolean, expected true or false"))}parseInlineList(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J)return null;if(this.char===e.END)throw this.error(new TomlError("Unterminated inline array"));return this.char===CHAR_NUM?this.call(this.parseComment):this.char===CHAR_RSQB?this.return(this.state.resultArr||InlineList()):this.callNow(this.parseValue,this.recordInlineListValue)}recordInlineListValue(n){if(this.state.resultArr){let i=this.state.resultArr[_contentType],o=tomlType(n);if(i!==o)throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${i} and ${o}`))}else this.state.resultArr=InlineList(tomlType(n));return isFloat(n)||isInteger(n)?this.state.resultArr.push(n.valueOf()):this.state.resultArr.push(n),this.goto(this.parseInlineListNext)}parseInlineListNext(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J)return null;if(this.char===CHAR_NUM)return this.call(this.parseComment);if(this.char===CHAR_COMMA)return this.next(this.parseInlineList);if(this.char===CHAR_RSQB)return this.goto(this.parseInlineList);throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}parseInlineTable(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===e.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M)throw this.error(new TomlError("Unterminated inline array"));return this.char===CHAR_RCUB?this.return(this.state.resultTable||InlineTable()):(this.state.resultTable||(this.state.resultTable=InlineTable()),this.callNow(this.parseAssign,this.recordInlineTableValue))}recordInlineTableValue(n){let i=this.state.resultTable,o=n.key.pop();for(let s of n.key){if(hasKey(i,s)&&(!isTable(i[s])||i[s][_declared]))throw this.error(new TomlError("Can't redefine existing key"));i=i[s]=i[s]||Table()}if(hasKey(i,o))throw this.error(new TomlError("Can't redefine existing key"));return isInteger(n.value)||isFloat(n.value)?i[o]=n.value.valueOf():i[o]=n.value,this.goto(this.parseInlineTableNext)}parseInlineTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===e.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M)throw this.error(new TomlError("Unterminated inline array"));if(this.char===CHAR_COMMA)return this.next(this.parseInlineTable);if(this.char===CHAR_RCUB)return this.goto(this.parseInlineTable);throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}return t}});var Al=He((Rre,dI)=>{"use strict";dI.exports=RH;function RH(e,t){if(e.pos==null||e.line==null)return e;let r=e.message;if(r+=` at row ${e.line+1}, col ${e.col+1}, pos ${e.pos}:
827
827
  `,t&&t.split){let n=t.split(/\n/),i=String(Math.min(n.length,e.line+3)).length,o=" ";for(;o.length<i;)o+=" ";for(let s=Math.max(0,e.line-1);s<Math.min(n.length,e.line+2);++s){let a=String(s+1);if(a.length<i&&(a=" "+a),e.line===s){r+=a+"> "+n[s]+`
828
828
  `,r+=o+" ";for(let c=0;c<e.col;++c)r+=" ";r+=`^
829
829
  `}else r+=a+": "+n[s]+`
830
830
  `}}return e.message=r+`
831
- `,e}});var fI=He((Rre,pI)=>{"use strict";pI.exports=DH;var OH=Tl(),NH=Al();function DH(e){global.Buffer&&global.Buffer.isBuffer(e)&&(e=e.toString("utf8"));let t=new OH;try{return t.parse(e),t.finish()}catch(r){throw NH(r,e)}}});var gI=He((Ore,hI)=>{"use strict";hI.exports=PH;var LH=Tl(),mI=Al();function PH(e,t){t||(t={});let r=0,n=t.blocksize||40960,i=new LH;return new Promise((s,a)=>{setImmediate(o,r,n,s,a)});function o(s,a,c,l){if(s>=e.length)try{return c(i.finish())}catch(u){return l(mI(u,e))}try{i.parse(e.slice(s,s+a)),setImmediate(o,s+a,a,c,l)}catch(u){l(mI(u,e))}}}});var _I=He((Nre,wI)=>{"use strict";wI.exports=FH;var MH=s$("stream"),yI=Tl();function FH(e){return e?BH(e):UH(e)}function BH(e){let t=new yI;return e.setEncoding("utf8"),new Promise((r,n)=>{let i,o=!1,s=!1;function a(){if(o=!0,!i)try{r(t.finish())}catch(u){n(u)}}function c(u){s=!0,n(u)}e.once("end",a),e.once("error",c),l();function l(){i=!0;let u;for(;(u=e.read())!==null;)try{t.parse(u)}catch(p){return c(p)}if(i=!1,o)return a();s||e.once("readable",l)}})}function UH(){let e=new yI;return new MH.Transform({objectMode:!0,transform(t,r,n){try{e.parse(t.toString(r))}catch(i){this.emit("error",i)}n()},flush(t){try{this.push(e.finish())}catch(r){this.emit("error",r)}t()}})}});var bI=He((Dre,la)=>{"use strict";la.exports=fI();la.exports.async=gI();la.exports.stream=_I();la.exports.prettyError=Al()});var $I=He((Lre,If)=>{"use strict";If.exports=HH;If.exports.value=Sf;function HH(e){if(e===null)throw xi("null");if(e===void 0)throw xi("undefined");if(typeof e!="object")throw xi(typeof e);if(typeof e.toJSON=="function"&&(e=e.toJSON()),e==null)return null;let t=tt(e);if(t!=="table")throw xi(t);return vf("","",e)}function xi(e){return new Error("Can only stringify objects, not "+e)}function jH(){return new Error("Array values can't have mixed types")}function xI(e){return Object.keys(e).filter(t=>EI(e[t]))}function GH(e){return Object.keys(e).filter(t=>!EI(e[t]))}function $l(e){let t=Array.isArray(e)?[]:Object.prototype.hasOwnProperty.call(e,"__proto__")?{["__proto__"]:void 0}:{};for(let r of Object.keys(e))e[r]&&typeof e[r].toJSON=="function"&&!("toISOString"in e[r])?t[r]=e[r].toJSON():t[r]=e[r];return t}function vf(e,t,r){r=$l(r);var n,i;n=xI(r),i=GH(r);var o=[],s=t||"";n.forEach(c=>{var l=tt(r[c]);l!=="undefined"&&l!=="null"&&o.push(s+Cl(c)+" = "+II(r[c],!0))}),o.length>0&&o.push("");var a=e&&n.length>0?t+" ":"";return i.forEach(c=>{o.push(ej(e,a,c,r[c]))}),o.join(`
831
+ `,e}});var fI=He((Ore,pI)=>{"use strict";pI.exports=DH;var OH=Tl(),NH=Al();function DH(e){global.Buffer&&global.Buffer.isBuffer(e)&&(e=e.toString("utf8"));let t=new OH;try{return t.parse(e),t.finish()}catch(r){throw NH(r,e)}}});var gI=He((Nre,hI)=>{"use strict";hI.exports=PH;var LH=Tl(),mI=Al();function PH(e,t){t||(t={});let r=0,n=t.blocksize||40960,i=new LH;return new Promise((s,a)=>{setImmediate(o,r,n,s,a)});function o(s,a,c,l){if(s>=e.length)try{return c(i.finish())}catch(u){return l(mI(u,e))}try{i.parse(e.slice(s,s+a)),setImmediate(o,s+a,a,c,l)}catch(u){l(mI(u,e))}}}});var _I=He((Dre,wI)=>{"use strict";wI.exports=FH;var MH=s$("stream"),yI=Tl();function FH(e){return e?BH(e):UH(e)}function BH(e){let t=new yI;return e.setEncoding("utf8"),new Promise((r,n)=>{let i,o=!1,s=!1;function a(){if(o=!0,!i)try{r(t.finish())}catch(u){n(u)}}function c(u){s=!0,n(u)}e.once("end",a),e.once("error",c),l();function l(){i=!0;let u;for(;(u=e.read())!==null;)try{t.parse(u)}catch(p){return c(p)}if(i=!1,o)return a();s||e.once("readable",l)}})}function UH(){let e=new yI;return new MH.Transform({objectMode:!0,transform(t,r,n){try{e.parse(t.toString(r))}catch(i){this.emit("error",i)}n()},flush(t){try{this.push(e.finish())}catch(r){this.emit("error",r)}t()}})}});var bI=He((Lre,la)=>{"use strict";la.exports=fI();la.exports.async=gI();la.exports.stream=_I();la.exports.prettyError=Al()});var $I=He((Pre,If)=>{"use strict";If.exports=HH;If.exports.value=Sf;function HH(e){if(e===null)throw xi("null");if(e===void 0)throw xi("undefined");if(typeof e!="object")throw xi(typeof e);if(typeof e.toJSON=="function"&&(e=e.toJSON()),e==null)return null;let t=tt(e);if(t!=="table")throw xi(t);return vf("","",e)}function xi(e){return new Error("Can only stringify objects, not "+e)}function jH(){return new Error("Array values can't have mixed types")}function xI(e){return Object.keys(e).filter(t=>EI(e[t]))}function GH(e){return Object.keys(e).filter(t=>!EI(e[t]))}function $l(e){let t=Array.isArray(e)?[]:Object.prototype.hasOwnProperty.call(e,"__proto__")?{["__proto__"]:void 0}:{};for(let r of Object.keys(e))e[r]&&typeof e[r].toJSON=="function"&&!("toISOString"in e[r])?t[r]=e[r].toJSON():t[r]=e[r];return t}function vf(e,t,r){r=$l(r);var n,i;n=xI(r),i=GH(r);var o=[],s=t||"";n.forEach(c=>{var l=tt(r[c]);l!=="undefined"&&l!=="null"&&o.push(s+Cl(c)+" = "+II(r[c],!0))}),o.length>0&&o.push("");var a=e&&n.length>0?t+" ":"";return i.forEach(c=>{o.push(ej(e,a,c,r[c]))}),o.join(`
832
832
  `)}function EI(e){switch(tt(e)){case"undefined":case"null":case"integer":case"nan":case"float":case"boolean":case"string":case"datetime":return!0;case"array":return e.length===0||tt(e[0])!=="table";case"table":return Object.keys(e).length===0;default:return!1}}function tt(e){return e===void 0?"undefined":e===null?"null":typeof e=="bigint"||Number.isInteger(e)&&!Object.is(e,-0)?"integer":typeof e=="number"?"float":typeof e=="boolean"?"boolean":typeof e=="string"?"string":"toISOString"in e?isNaN(e)?"undefined":"datetime":Array.isArray(e)?"array":"table"}function Cl(e){var t=String(e);return/^[-A-Za-z0-9_]+$/.test(t)?t:vI(t)}function vI(e){return'"'+SI(e).replace(/"/g,'\\"')+'"'}function WH(e){return"'"+e+"'"}function VH(e,t){for(;t.length<e;)t="0"+t;return t}function SI(e){return e.replace(/\\/g,"\\\\").replace(/[\b]/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/([\u0000-\u001f\u007f])/,t=>"\\u"+VH(4,t.codePointAt(0).toString(16)))}function KH(e){let t=e.split(/\n/).map(r=>SI(r).replace(/"(?="")/g,'\\"')).join(`
833
833
  `);return t.slice(-1)==='"'&&(t+=`\\
834
834
  `),`"""
@@ -901,12 +901,12 @@ WantedBy=default.target
901
901
  END $$;`),await ba("postgres",`GRANT ALL PRIVILEGES ON DATABASE ${rs} TO ${wn}`),await ba(rs,`GRANT ALL ON SCHEMA public TO ${wn};
902
902
  ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO ${wn};
903
903
  ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO ${wn};
904
- CREATE EXTENSION IF NOT EXISTS vector;`);let s=`postgres://${wn}:${encodeURIComponent(i)}@localhost:${n}/${rs}`,a=await Yt(s);if(!a.ok)throw new Error(`provisioned container did not accept a TCP connection (${a.stage}): ${a.error}`);return{url:s,port:n,container:$t,image:Ci,reused:r.exists,pgvector:a.pgvector}}async function LG(){try{let{default:e}=await Promise.resolve().then(()=>(N(),de)),t=e.db.url||"";if(!/@localhost:|@127\.0\.0\.1:/.test(t))return{started:!1,reason:"not a local url"};if(!(await _n()).available)return{started:!1,reason:"docker unavailable"};let n=await T0();if(!n.exists)return{started:!1,reason:"no sigil-postgres container"};if(n.running)return{started:!1,reason:"already running"};let i=await Fe(dt(),["start",$t],{timeout:15e3});return i.code===0?{started:!0}:{started:!1,reason:i.err}}catch(e){return{started:!1,reason:e.message}}}async function PG(){return Fe(dt(),["stop",$t],{timeout:2e4})}async function MG({deleteVolume:e=!1}={}){await Fe(dt(),["rm","-f",$t],{timeout:2e4}),e&&await Fe(dt(),["volume","rm",Gf],{timeout:15e3})}var Fl,$t,Gf,Ci,rs,wn,xa=f(()=>{qe();Fl=null;$t="sigil-postgres",Gf="sigil-pgdata",Ci="pgvector/pgvector:pg16",rs="sigil",wn="sigil_app"});var Y,Ea=f(()=>{Y=class extends Error{constructor({message:t,hint:r,kind:n}){super(t),this.name="StepError",this.hint=r||null,this.kind=n||"other"}}});import FG from"node:net";import{spawn as BG}from"node:child_process";import{randomBytes as UG}from"node:crypto";function Wt(e){let t=Wi(e);return new Y({message:t.humanMessage,hint:t.fixHint,kind:t.kind})}function A0(){return UG(18).toString("base64url")}function bn(e){return Ge("database",e)}function qf(e,t,r=1200){return new Promise(n=>{let i=FG.connect(t,e),o=s=>{try{i.destroy()}catch{}n(s)};i.setTimeout(r),i.once("connect",()=>o(!0)),i.once("timeout",()=>o(!1)),i.once("error",()=>o(!1))})}function C0(e,t,r=2e4){return new Promise((n,i)=>{let o=Date.now(),s=async()=>{if(await qf(e,t,800))return n();if(Date.now()-o>r)return i(new Y({message:`Postgres did not start listening on ${e}:${t}.`,hint:"Check the Postgres logs, or use an external connection string.",kind:"unreachable"}));setTimeout(s,600)};s()})}function Yf(e){return new Promise(t=>{let r=BG(e,["--version"],{stdio:"ignore"});r.on("error",()=>t(!1)),r.on("close",n=>t(n===0)),setTimeout(()=>{try{r.kill()}catch{}t(!1)},3e3)})}var $0,xn,En,vn=f(()=>{qe();nt();Ea();$0=e=>`"${String(e).replace(/"/g,'""')}"`;xn="sigil",En="sigil_app"});import{userInfo as HG}from"node:os";import jG from"pg";async function WG(e,t,r){let n=new jG.Client({host:e,port:t,database:"postgres",user:r,connectionTimeoutMillis:2e3});try{await n.connect();let i=await n.query("SELECT version() AS v"),o=await n.query("SELECT 1 FROM pg_available_extensions WHERE name = 'vector'");return{ok:!0,version:i.rows[0].v,pgvectorAvailable:o.rowCount>0}}catch(i){return{ok:!1,code:i.code,message:i.message}}finally{try{await n.end()}catch{}}}async function k0(){let e=HG().username,t={installed:!1,running:!1,host:"localhost",port:5432,version:null,adminUser:e,pgvectorAvailable:!1};for(let i of GG){if(!await qf("127.0.0.1",i))continue;let o=await WG("127.0.0.1",i,e);if(o.ok){t.running=!0,t.installed=!0,t.port=i,t.version=o.version,t.pgvectorAvailable=o.pgvectorAvailable;break}}t.installed||(t.installed=await Yf("postgres")||await Yf("pg_ctl"));let r=await _n();return{embedded:{available:!0},local:t,docker:r}}var GG,R0=f(()=>{xa();vn();GG=[5432,5433]});import O0 from"knex";async function ns(e){let t;if(e.url){let n=e.url;if(ws(e.url)){let i=qa(e.url);if(!i)throw new Error("This is a connection-pooler URL. Migrations need the direct connection \u2014 paste your non-pooled connection string.");n=i}t=it(n)}else t=Bc(e);let r=O0({client:"pg",connection:t,pool:{min:1,max:2}});try{let[n,i]=await r.migrate.latest({directory:Kt});return{batchNo:n,ran:i}}finally{await r.destroy()}}async function N0(){let{ClientPGlite:e,PGLITE_DB_PATH:t}=await Promise.resolve().then(()=>(Hc(),xx)),r=O0({client:e,connection:{pglitePath:t},pool:{min:1,max:1}}),[n,i]=await r.migrate.latest({directory:Kt});return{batchNo:n,ran:i}}var va=f(()=>{K();So();Gi()});async function D0(e={},t=()=>{}){try{t({pct:10,label:"Configuring the in-process database\u2026"}),bn({mode:"embedded",url:null,password:null}),t({pct:40,label:"Creating tables (Postgres + pgvector, no server)\u2026"});let r=await N0();return t({pct:100,label:"Embedded database ready."}),{mode:"embedded",engine:"pglite",dataDir:vo,migrationsRan:r.ran.length}}catch(r){throw r instanceof Y?r:Wt(r)}}var L0=f(()=>{va();Hc();vn()});async function is(e){if(e.url){let r=await Yt(e.url);if(!r.ok)throw Wt({code:r.code,message:r.error||`connection failed at ${r.stage}`});return{database:r.database,provider:r.provider,pgvector:r.pgvector}}let t=await Mu(e);if(!t.ok)throw Wt({code:t.code,message:t.message});return{}}var Bl=f(()=>{qe();vn()});import{userInfo as VG}from"node:os";import{spawn as KG}from"node:child_process";async function P0(e,t=()=>{}){let r=e.host||"localhost",n=Number(e.port)||5432,i=e.adminUser||VG().username,o=e.adminPassword||"";try{e.action==="start"&&(t({pct:5,label:"Starting local Postgres\u2026"}),await qG(e),await C0(r,n)),t({pct:20,label:`Connecting to Postgres on ${r}:${n}\u2026`});let s=A0();t({pct:45,label:"Creating database, role, and pgvector\u2026"}),await Fu({admin:{host:r,port:n,user:i,password:o},sigil:{database:xn,user:En,password:s}}),t({pct:70,label:"Running migrations\u2026"});let a=await ns({host:r,port:n,database:xn,user:En,password:s});return t({pct:90,label:"Verifying connection\u2026"}),await is({host:r,port:n,database:xn,user:En,password:s}),bn({mode:"local",url:null,host:r,port:n,name:xn,user:En,password:s}),t({pct:100,label:"Database ready."}),{mode:"local",host:r,port:n,database:xn,user:En,migrationsRan:a.ran.length}}catch(s){throw s instanceof Y?s:Wt(s)}}async function qG(e={}){let t=[];if(process.platform==="darwin"){let r=e.brewFormula?[e.brewFormula]:["postgresql@17","postgresql@16","postgresql@15","postgresql@14","postgresql"];for(let n of r)t.push(["brew",["services","start",n]])}e.dataDir&&t.push(["pg_ctl",["-D",e.dataDir,"start"]]),process.platform==="linux"&&t.push(["systemctl",["start","postgresql"]]);for(let[r,n]of t)if(await new Promise(o=>{let s=KG(r,n,{stdio:"ignore"});s.on("error",()=>o(!1)),s.on("close",a=>o(a===0)),setTimeout(()=>{try{s.kill()}catch{}o(!1)},15e3)}))return;throw new Y({message:"Could not start the local Postgres service automatically.",hint:process.platform==="darwin"?"Start it yourself (e.g. `brew services start postgresql@17`) and retry, or use an external connection.":"Start it yourself (e.g. `sudo systemctl start postgresql`) and retry, or use an external connection.",kind:"unreachable"})}var M0=f(()=>{qe();va();vn();Bl()});async function F0(e,t=()=>{}){try{let r=await _n();if(!r.installed)throw new Y({message:"Docker is not installed on this machine.",hint:"Install Docker Desktop, or use a local install / external connection string.",kind:"other"});if(!r.running){t({pct:8,label:"Docker is installed but not running \u2014 starting it\u2026"});try{await Wf()}catch(o){throw new Y({message:o.message||"Could not start Docker.",hint:"Start Docker Desktop manually and retry, or use a local install / external connection.",kind:"other"})}}t({pct:25,label:"Provisioning a dedicated Sigil Postgres container\u2026"});let n=await Vf({onProgress:o=>t({pct:35,label:o})});t({pct:70,label:"Running migrations\u2026"});let i=await ns({url:n.url});return t({pct:90,label:"Verifying connection\u2026"}),await is({url:n.url}),bn({mode:"docker",url:n.url,host:"localhost",port:n.port,name:xn,user:En,password:null}),t({pct:100,label:"Database ready."}),{mode:"docker",url:n.url,port:n.port,reused:n.reused,migrationsRan:i.ran.length}}catch(r){throw r instanceof Y?r:r.dockerUnavailable?new Y({message:"Docker is not available.",hint:"Start Docker Desktop and retry.",kind:"other"}):Wt(r)}}var B0=f(()=>{xa();va();vn();Bl()});import U0 from"pg";async function H0(e,t=()=>{}){let{url:r}=e;try{t({pct:10,label:"Validating connection string\u2026"});let n;try{n=it(r)}catch(a){throw new Y({message:`That connection string is malformed: ${a.message}`,kind:"other"})}let i=await Yt(r);if(!i.ok&&i.stage==="connect"&&i.code==="3D000"&&(t({pct:30,label:`Creating database "${n.database}"\u2026`}),await YG(n),i=await Yt(r)),!i.ok)throw new Y({message:i.stage==="parse"?`That connection string is malformed: ${i.error}`:`Could not reach that database (${i.stage}): ${i.error}`,hint:"Double-check the host, port, credentials, and SSL settings.",kind:"unreachable"});if(!i.pgvector&&(t({pct:45,label:"Enabling pgvector\u2026"}),!(await zG(n)).ok))throw new Y({message:"pgvector is not enabled, and these credentials cannot enable it.",hint:"Enable the `vector` extension (managed providers expose this in their dashboard), then retry.",kind:"no-pgvector"});t({pct:65,label:"Running migrations\u2026"});let o=await ns({url:r});t({pct:90,label:"Verifying connection\u2026"});let s=await is({url:r});return bn({mode:"url",url:r,host:null,port:null,name:s.database,user:null,password:null}),t({pct:100,label:"Database ready."}),{mode:"url",database:s.database,provider:s.provider,migrationsRan:o.ran.length}}catch(n){throw n instanceof Y?n:Wt(n)}}async function YG(e){let t=new U0.Client({...e,database:"postgres"});await t.connect();try{(await t.query("SELECT 1 FROM pg_database WHERE datname = $1",[e.database])).rowCount===0&&await t.query(`CREATE DATABASE ${$0(e.database)}`)}finally{try{await t.end()}catch{}}}async function zG(e){let t=new U0.Client(e);await t.connect();try{return await t.query("CREATE EXTENSION IF NOT EXISTS vector"),{ok:!0}}catch(r){return{ok:!1,code:r.code,message:r.message}}finally{try{await t.end()}catch{}}}var j0=f(()=>{qe();So();va();vn();Bl()});function G0(e={}){let t={};return["embedded","local","docker","url"].includes(e.mode)||(t.mode="choose one of: embedded, local, docker, url"),e.mode==="url"&&!e.url&&(t.url="a connection string is required"),e.mode==="local"&&e.action&&!["connect","start"].includes(e.action)&&(t.action="must be connect or start"),{ok:Object.keys(t).length===0,errors:t}}async function QG(e={},t=()=>{}){let r=G0(e);if(!r.ok)throw new Y({message:`Invalid database input: ${JSON.stringify(r.errors)}`,kind:"other"});return e.mode==="embedded"?D0(e,t):e.mode==="local"?P0(e,t):e.mode==="docker"?F0(e,t):H0(e,t)}var JG,ZG,XG,W0,V0=f(()=>{R0();L0();M0();B0();j0();vn();JG="database",ZG="Database",XG=k0;W0={id:JG,title:ZG,detect:XG,validate:G0,apply:QG}});function K0(){return zf}function i2(){return{providers:K0()}}function o2(e={}){let t={},r=zf.find(n=>n.id===e.provider);return r?(e2.has(r.id)&&!e.apiKey&&(t.apiKey="an API key is required"),t2.has(r.id)&&!e.model&&(t.model="a model is required"),{ok:Object.keys(t).length===0,errors:t}):(t.provider="choose a provider",{ok:!1,errors:t})}async function s2(e,t=()=>{}){let r=zf.find(n=>n.id===e.provider);if(!r)throw new Y({message:`Unknown LLM provider: ${e.provider}`,kind:"other"});t({pct:20,label:"Saving provider\u2026"}),Ge("llm",{provider:r.id,model:e.model||null,apiKey:e.apiKey||null,host:e.host||null}),t({pct:55,label:"Testing live LLM call\u2026"});try{let{resetDetection:n}=await Promise.resolve().then(()=>(Co(),Yc));n();let{prompt:i}=await Promise.resolve().then(()=>(Xe(),zc)),o=await i("Reply with the single word: ok",{caller:"setup-llm-test"});return t({pct:100,label:"LLM ready."}),{provider:r.id,response:String(o).slice(0,200)}}catch(n){throw new Y({message:n.message,kind:"llm"})}}var zf,e2,t2,r2,n2,q0,Y0=f(()=>{nt();Ea();zf=[{id:"claude-cli",label:"Claude Code",hint:"Uses your existing Claude Code subscription \u2014 no API key",recommended:!0,fields:[]},{id:"openrouter",label:"OpenRouter",hint:"One key, many models (cheapest default)",fields:[{name:"apiKey",label:"OpenRouter API key",type:"password",placeholder:"sk-or-\u2026"},{name:"model",label:"Model",type:"text",placeholder:"google/gemini-flash-latest"}]},{id:"openai",label:"OpenAI",hint:"Direct OpenAI access",fields:[{name:"apiKey",label:"OpenAI API key",type:"password",placeholder:"sk-\u2026"},{name:"model",label:"Model",type:"text",placeholder:"gpt-4o-mini"}]},{id:"anthropic",label:"Anthropic",hint:"Direct Anthropic API access",fields:[{name:"apiKey",label:"Anthropic API key",type:"password",placeholder:"sk-ant-\u2026"}]},{id:"ollama",label:"Ollama",hint:"Local + private; slower on small machines",fields:[{name:"host",label:"Ollama host",type:"text",placeholder:"http://localhost:11434",optional:!0},{name:"model",label:"Model",type:"text",placeholder:"qwen2.5:7b"}]}],e2=new Set(["openrouter","openai","anthropic"]),t2=new Set(["openrouter","openai","ollama"]),r2="llm",n2="LLM provider";q0={id:r2,title:n2,detect:i2,listProviders:K0,validate:o2,apply:s2}});var J0={};A(J0,{OLLAMA_EMBED_MODELS:()=>Sa,RECOMMENDED_EMBED_MODEL:()=>Hl,isReachable:()=>jl,listCompatibleModels:()=>Gl,listInstalledModels:()=>z0,pullModel:()=>Jf});async function jl(e=Ul){try{return(await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}async function z0(e=Ul){let t=await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Ollama /api/tags returned ${t.status}`);return((await t.json()).models||[]).map(n=>String(n.name||"").split(":")[0])}async function Gl(e=Ul){let t=[];try{t=await z0(e)}catch{}let r=new Set(t);return Sa.map(n=>({...n,installed:r.has(n.name)}))}async function Jf(e,t=()=>{},r=Ul){let n=await fetch(`${r}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:e,stream:!0})});if(!n.ok||!n.body)throw new Error(`Ollama pull failed: ${n.status}`);let i=n.body.getReader(),o=new TextDecoder,s="";for(;;){let{value:a,done:c}=await i.read();if(c)break;s+=o.decode(a,{stream:!0});let l;for(;(l=s.indexOf(`
905
- `))!==-1;){let u=s.slice(0,l).trim();if(s=s.slice(l+1),!u)continue;let p;try{p=JSON.parse(u)}catch{continue}if(p.error)throw new Error(p.error);let d=p.total?Math.round((p.completed||0)/p.total*100):null;t({status:p.status||"",percent:d})}}}var Ul,Sa,Hl,Zf=f(()=>{Ul="http://localhost:11434",Sa=[{name:"mxbai-embed-large",dim:1024,size:"~670MB",recommended:!0},{name:"bge-large",dim:1024,size:"~670MB"},{name:"bge-m3",dim:1024,size:"~1.2GB"},{name:"snowflake-arctic-embed2",dim:1024,size:"~1.2GB"}],Hl=Sa.find(e=>e.recommended).name});var Xf={};A(Xf,{checkCorpusConsistency:()=>a2});async function a2({namespace:e=null}={}){let t=b("fact").where({status:"active"}).whereNotNull("embedding");e&&(t=t.where({namespace:e}));let n=(await t.select("embeddingModel").count({c:"*"}).groupBy("embeddingModel")).map(c=>({model:c.embeddingModel||"(unknown)",count:Number(c.c)})).filter(c=>c.count>0).sort((c,l)=>l.count-c.count),i=n.reduce((c,l)=>c+l.count,0),o=x.embedding.model||null,s=n.length>1,a=n.filter(c=>c.model!==o).reduce((c,l)=>c+l.count,0);return{current:o,histogram:n,mixed:s,total:i,stale:a}}var Qf=f(()=>{B();N()});function Z0(){let e=De();return process.env.OLLAMA_HOST||e.embedding?.host||"http://localhost:11434"}function X0(){let e=De();return em.map(t=>({...t,sharedKeyAvailable:t.shared&&e.llm.provider===t.id&&!!e.llm.apiKey}))}async function u2(){let e=Z0(),t=await jl(e),r=await Gl(e);return{providers:X0(),ollama:{reachable:t,host:e,models:r,recommended:Hl}}}function Q0(e,t){if(t.apiKey)return t.apiKey;if(e.shared){let r=De();if(r.llm.provider===e.id&&r.llm.apiKey)return r.llm.apiKey}return null}function d2(e={}){let t={},r=em.find(n=>n.id===e.provider);return r?r.keyed&&!Q0(r,e)&&(t.apiKey="an API key is required"):t.provider="choose a provider",{ok:Object.keys(t).length===0,errors:t}}async function p2(e,t=()=>{}){let r=em.find(i=>i.id===e.provider);if(!r)throw new Y({message:`Unknown embedding provider: ${e.provider}`,kind:"other"});let n=r.model;if(r.id==="ollama"&&e.model){let i=Sa.map(o=>o.name);if(!i.includes(e.model))throw new Y({message:`"${e.model}" isn't a known 1024-dim Ollama embedding model.`,hint:`Choose one of: ${i.join(", ")}.`,kind:"model-not-found"});n=e.model}if(t({pct:20,label:"Saving provider\u2026"}),Ge("embedding",{provider:r.id,model:n,apiKey:Q0(r,e),host:e.host||null}),r.id==="ollama"){let i=Z0();if(!await jl(i))throw new Y({message:"The local Ollama server is not reachable.",hint:"Start it with `ollama serve`, then retry.",kind:"ollama-down"});if(!(await Gl(i)).find(s=>s.name===n)?.installed){t({pct:30,label:`Pulling ${n}\u2026`});try{await Jf(n,({status:s,percent:a})=>{let c=a==null?35:30+Math.round(a*.2);t({pct:c,label:`Pulling ${n}: ${s}${a==null?"":` ${a}%`}`})},i)}catch(s){throw new Y({message:`Failed to pull ${n} from Ollama: ${s.message}`,hint:`Pull it manually with \`ollama pull ${n}\`, then retry.`,kind:"model-not-found"})}}}t({pct:55,label:"Testing embed call\u2026"});try{let{resetDetection:i}=await Promise.resolve().then(()=>(Co(),Yc));i();let{embed:o}=await Promise.resolve().then(()=>(rr(),Gs)),s=await o("Sigil setup embedding test",{cache:!1});if(!Array.isArray(s)||s.length===0)throw new Y({message:"The embedder returned an empty vector.",kind:"other"});if(s.length!==1024)throw new Y({message:`This model returned ${s.length}-dim vectors, but Sigil requires ${1024}.`,hint:`Pick a provider/model that produces ${1024}-dim embeddings.`,kind:"model-not-found"});let a="";try{let{checkCorpusConsistency:c}=await Promise.resolve().then(()=>(Qf(),Xf)),l=await c();l.stale>0&&(a=` ${l.stale} existing facts use a different model \u2014 run \`sigil repair embeddings\` so they rank correctly.`)}catch{}return t({pct:100,label:`Embedder ready.${a}`}),{provider:r.id,model:r.model,dim:s.length,staleFacts:!!a}}catch(i){if(i instanceof Y)throw i;let{diagnoseError:o}=await Promise.resolve().then(()=>(qe(),Pn)),s=o(i);throw new Y({message:s.humanMessage,hint:s.fixHint,kind:s.kind})}}var em,c2,l2,eT,tT=f(()=>{nt();Ea();qt();Zf();em=[{id:"openai",label:"OpenAI",hint:"text-embedding-3-large @ 1024 \u2014 best out-of-the-box quality",recommended:!0,model:"text-embedding-3-large",keyed:!0,shared:!0},{id:"voyage",label:"Voyage",hint:"voyage-3 @ 1024",model:"voyage-3",keyed:!0,shared:!1},{id:"openrouter",label:"OpenRouter",hint:"Gateway; reuses your LLM key",model:"openai/text-embedding-3-large",keyed:!0,shared:!0},{id:"ollama",label:"Ollama (local)",hint:"1024-dim local embeddings, free \u2014 pick a model, auto-pulled if missing",model:Hl,keyed:!1,shared:!1}],c2="embedding",l2="Embeddings";eT={id:c2,title:l2,detect:u2,listProviders:X0,validate:d2,apply:p2}});function h2(){return{ok:!0}}async function g2(){return{ok:!0}}var f2,m2,rT,nT=f(()=>{f2="connectors",m2="Coding agents";rT={id:f2,title:m2,validate:h2,apply:g2}});function _2(e={}){let t=(e.name||"").trim(),r={};return t?t.length>80&&(r.name="that name is too long"):r.name="tell us what to call you",{ok:Object.keys(r).length===0,errors:r}}async function b2(e,t=()=>{}){let r=(e.name||"").trim();if(!r)throw new Y({message:"A name is required.",kind:"other"});t({pct:15,label:"Saving your name\u2026"}),Ge("identity",{name:r}),t({pct:40,label:"Writing a first memory (testing the full stack)\u2026"});try{let{ingestDocument:n}=await Promise.resolve().then(()=>(Zs(),Js)),{default:i}=await Promise.resolve().then(()=>(N(),de)),o=await n({content:`The user's name is ${r}.`,namespace:i.defaults.namespace,classify:!0}),s=(o.facts?.added??0)+(o.facts?.updated??0);if(!s&&!o.skipped&&o.route!=="noise")throw new Y({message:"The memory pipeline ran but stored no fact.",kind:"other"});return t({pct:100,label:"All set."}),{name:r,factsAdded:s,route:o.route??null}}catch(n){if(n instanceof Y)throw n;let{diagnoseError:i}=await Promise.resolve().then(()=>(qe(),Pn)),o=i(n);throw new Y({message:o.humanMessage,hint:o.fixHint,kind:o.kind})}}var y2,w2,iT,oT=f(()=>{nt();Ea();y2="identity",w2="Your name";iT={id:y2,title:w2,validate:_2,apply:b2}});var Wl={};A(Wl,{disconnectAllClients:()=>sT,dropConfiguredDatabase:()=>x2,factoryReset:()=>E2,wipeMemoryData:()=>aT});async function sT(){let{listClients:e}=await Promise.resolve().then(()=>(Si(),es)),t=await e(),r=[];for(let n of t)try{(await n.verify()).installed&&(await n.uninstall({dryRun:!1}),r.push(n.id))}catch{}return r}async function aT(){let{default:e}=await Promise.resolve().then(()=>(B(),se)),{rows:t}=await e.raw("SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename NOT LIKE 'knex\\_%'"),r=t.map(n=>n.tablename);return r.length?(await e.raw(`TRUNCATE ${r.map(n=>`"${n}"`).join(", ")} RESTART IDENTITY CASCADE`),r.length):0}async function x2(){let e=De(),t=e.database?.mode;if(t==="docker"){let{removeLocalPostgres:r}=await Promise.resolve().then(()=>(xa(),Kf));return await r({deleteVolume:!0}),{kind:"docker",dropped:!0,detail:"removed sigil-postgres container + volume"}}if(t==="local"){let r=(await import("pg")).default,{userInfo:n}=await import("node:os"),i=e.database.name||"sigil",o=new r.Client({host:e.database.host||"localhost",port:e.database.port||5432,database:"postgres",user:e.database.adminUser||n().username,password:""});await o.connect();try{return await o.query(`DROP DATABASE IF EXISTS "${i.replace(/"/g,'""')}" WITH (FORCE)`),{kind:"local",dropped:!0,detail:`dropped database "${i}"`}}finally{try{await o.end()}catch{}}}return{kind:t||"none",dropped:!1,detail:"external/managed database left intact"}}async function E2({wipeMemory:e=!0}={}){let t=await sT(),r=0;if(e)try{r=await aT()}catch{}return ms(),{disconnected:t,tablesWiped:r,configWiped:!0}}var Vl=f(()=>{nt()});var uT={};A(uT,{detectStep:()=>im,factoryResetSetup:()=>cm,getSetupConfig:()=>sm,getSetupState:()=>Ar,listSteps:()=>nm,resetSetup:()=>am,runStep:()=>om});function tm(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(tm);let t={};for(let[r,n]of Object.entries(e))typeof n=="string"&&/url|uri|dsn|conn/i.test(r)?t[r]=n.replace(/(\w+:\/\/[^:@/\s]+):[^@/\s]+@/g,"$1:***@"):n&&typeof n=="object"?t[r]=tm(n):t[r]=n;return t}function lT(e){let t=rm.find(r=>r.id===e);if(!t){let r=new Error(`setup step not available: ${e}`);throw r.code="invalid_params",r}return t}function nm(){let e=new Set(rm.map(t=>t.id));return cT.map(t=>({...t,implemented:e.has(t.id)}))}function Ar(){let e=De(),t=cT.map(i=>({...i,implemented:rm.some(o=>o.id===i.id),status:e.setup?.steps?.[i.id]||"pending"})),r=t.find(i=>i.implemented&&i.status!=="done")?.id||null;return{complete:t.length>0&&t.every(i=>i.status==="done"),steps:t,currentStep:r}}async function im(e){let t=lT(e);return typeof t.detect=="function"?t.detect():{}}async function om(e,t={}){let r=lT(e),n=r.validate?r.validate(t):{ok:!0};if(!n.ok)return be.emit("setup",{step:e,status:"error",pct:0,label:"Please fix the highlighted fields.",errors:n.errors}),{ok:!1,step:e,errors:n.errors,state:Ar()};fs(e,"active"),be.emit("setup",{step:e,status:"active",pct:0,label:`Starting ${r.title}\u2026`});let i=(o={})=>be.emit("setup",{step:e,status:"active",pct:o.pct??0,label:o.label||""});try{let o=await r.apply(t,i);fs(e,"done");let s=tm(o);be.emit("setup",{step:e,status:"done",pct:100,label:`${r.title} ready.`,result:s});let a=Ar();return a.steps.every(l=>l.status==="done")&&!a.complete&&Iu(!0),{ok:!0,step:e,result:s,state:Ar()}}catch(o){return fs(e,"error"),be.emit("setup",{step:e,status:"error",pct:0,label:o.message,hint:o.hint||null,kind:o.kind||"other"}),{ok:!1,step:e,error:o.message,hint:o.hint||null,kind:o.kind||"other",state:Ar()}}}function sm(){let e=De(),t=null;if(e.database.url)try{t=new URL(e.database.url).host}catch{t="(connection url)"}return{database:{mode:e.database.mode,host:e.database.host,port:e.database.port,name:e.database.name,urlHost:t},llm:{provider:e.llm.provider,model:e.llm.model,hasKey:!!e.llm.apiKey},embedding:{provider:e.embedding.provider,model:e.embedding.model,dim:1024,hasKey:!!e.embedding.apiKey},identity:{name:e.identity.name},setup:e.setup}}function am(){return ms(),be.emit("setup",{step:null,status:"reset",pct:0,label:"Setup reset."}),Ar()}async function cm({wipeMemory:e=!0}={}){let{factoryReset:t}=await Promise.resolve().then(()=>(Vl(),Wl)),r=await t({wipeMemory:e});return be.emit("setup",{step:null,status:"reset",pct:0,label:"Sigil reset."}),{...r,state:Ar()}}var rm,cT,lm=f(()=>{ri();nt();V0();Y0();tT();nT();oT();rm=[W0,q0,eT,rT,iT],cT=[{id:"database",title:"Database"},{id:"llm",title:"LLM provider"},{id:"embedding",title:"Embeddings"},{id:"connectors",title:"Coding agents"},{id:"identity",title:"Your name"}]});function dT(e){e.register("setup.state",async()=>Ar()),e.register("setup.config",async()=>sm()),e.register("setup.steps",async()=>({steps:nm()})),e.register("setup.detect",async(t={})=>im(t.step)),e.register("setup.run",async(t={})=>om(t.step,t.input||{})),e.register("setup.reset",async()=>am()),e.register("setup.factoryReset",async(t={})=>cm({wipeMemory:t.wipeMemory!==!1}))}var pT=f(()=>{lm()});var mT={};A(mT,{CLASSIFIER_PROMPT:()=>fT,classifyTurn:()=>v2,saveFacts:()=>S2});async function v2(e){let{promptJson:t}=await Promise.resolve().then(()=>(Xe(),zc)),r=(await Promise.resolve().then(()=>(N(),de))).default,n=`${fT}
904
+ CREATE EXTENSION IF NOT EXISTS vector;`);let s=`postgres://${wn}:${encodeURIComponent(i)}@localhost:${n}/${rs}`,a=await Yt(s);if(!a.ok)throw new Error(`provisioned container did not accept a TCP connection (${a.stage}): ${a.error}`);return{url:s,port:n,container:$t,image:Ci,reused:r.exists,pgvector:a.pgvector}}async function LG(){try{let{default:e}=await Promise.resolve().then(()=>(N(),de)),t=e.db.url||"";if(!/@localhost:|@127\.0\.0\.1:/.test(t))return{started:!1,reason:"not a local url"};if(!(await _n()).available)return{started:!1,reason:"docker unavailable"};let n=await T0();if(!n.exists)return{started:!1,reason:"no sigil-postgres container"};if(n.running)return{started:!1,reason:"already running"};let i=await Fe(dt(),["start",$t],{timeout:15e3});return i.code===0?{started:!0}:{started:!1,reason:i.err}}catch(e){return{started:!1,reason:e.message}}}async function PG(){return Fe(dt(),["stop",$t],{timeout:2e4})}async function MG({deleteVolume:e=!1}={}){await Fe(dt(),["rm","-f",$t],{timeout:2e4}),e&&await Fe(dt(),["volume","rm",Gf],{timeout:15e3})}var Fl,$t,Gf,Ci,rs,wn,xa=f(()=>{qe();Fl=null;$t="sigil-postgres",Gf="sigil-pgdata",Ci="pgvector/pgvector:pg16",rs="sigil",wn="sigil_app"});var Y,Ea=f(()=>{Y=class extends Error{constructor({message:t,hint:r,kind:n}){super(t),this.name="StepError",this.hint=r||null,this.kind=n||"other"}}});import FG from"node:net";import{spawn as BG}from"node:child_process";import{randomBytes as UG}from"node:crypto";function Wt(e){let t=Wi(e);return new Y({message:t.humanMessage,hint:t.fixHint,kind:t.kind})}function A0(){return UG(18).toString("base64url")}function bn(e){return Ge("database",e)}function qf(e,t,r=1200){return new Promise(n=>{let i=FG.connect(t,e),o=s=>{try{i.destroy()}catch{}n(s)};i.setTimeout(r),i.once("connect",()=>o(!0)),i.once("timeout",()=>o(!1)),i.once("error",()=>o(!1))})}function C0(e,t,r=2e4){return new Promise((n,i)=>{let o=Date.now(),s=async()=>{if(await qf(e,t,800))return n();if(Date.now()-o>r)return i(new Y({message:`Postgres did not start listening on ${e}:${t}.`,hint:"Check the Postgres logs, or use an external connection string.",kind:"unreachable"}));setTimeout(s,600)};s()})}function Yf(e){return new Promise(t=>{let r=BG(e,["--version"],{stdio:"ignore"});r.on("error",()=>t(!1)),r.on("close",n=>t(n===0)),setTimeout(()=>{try{r.kill()}catch{}t(!1)},3e3)})}var $0,xn,En,vn=f(()=>{qe();nt();Ea();$0=e=>`"${String(e).replace(/"/g,'""')}"`;xn="sigil",En="sigil_app"});import{userInfo as HG}from"node:os";import jG from"pg";function WG(e){return typeof e?.code=="string"&&e.code.startsWith("28")?!0:/SASL|SCRAM|password must be a string|password authentication failed/i.test(e?.message||"")}async function VG(e,t,r){let n=new jG.Client({host:e,port:t,database:"postgres",user:r,password:"",connectionTimeoutMillis:2e3});try{await n.connect();let i=await n.query("SELECT version() AS v"),o=await n.query("SELECT 1 FROM pg_available_extensions WHERE name = 'vector'");return{ok:!0,present:!0,version:i.rows[0].v,pgvectorAvailable:o.rowCount>0}}catch(i){return WG(i)?{ok:!1,present:!0,requiresAuth:!0}:{ok:!1,present:!1,code:i.code,message:i.message}}finally{try{await n.end()}catch{}}}async function k0(){let e=HG().username,t={installed:!1,running:!1,host:"localhost",port:5432,version:null,adminUser:e,pgvectorAvailable:!1,requiresAuth:!1};for(let i of GG){if(!await qf("127.0.0.1",i))continue;let o=await VG("127.0.0.1",i,e);if(o.ok||o.present){t.running=!0,t.installed=!0,t.port=i,o.ok?(t.version=o.version,t.pgvectorAvailable=o.pgvectorAvailable):t.requiresAuth=!0;break}}t.installed||(t.installed=await Yf("postgres")||await Yf("pg_ctl"));let r=await _n();return{embedded:{available:!0},local:t,docker:r}}var GG,R0=f(()=>{xa();vn();GG=[5432,5433]});import O0 from"knex";async function ns(e){let t;if(e.url){let n=e.url;if(ws(e.url)){let i=qa(e.url);if(!i)throw new Error("This is a connection-pooler URL. Migrations need the direct connection \u2014 paste your non-pooled connection string.");n=i}t=it(n)}else t=Bc(e);let r=O0({client:"pg",connection:t,pool:{min:1,max:2}});try{let[n,i]=await r.migrate.latest({directory:Kt});return{batchNo:n,ran:i}}finally{await r.destroy()}}async function N0(){let{ClientPGlite:e,PGLITE_DB_PATH:t}=await Promise.resolve().then(()=>(Hc(),xx)),r=O0({client:e,connection:{pglitePath:t},pool:{min:1,max:1}}),[n,i]=await r.migrate.latest({directory:Kt});return{batchNo:n,ran:i}}var va=f(()=>{K();So();Gi()});async function D0(e={},t=()=>{}){try{t({pct:10,label:"Configuring the in-process database\u2026"}),bn({mode:"embedded",url:null,password:null}),t({pct:40,label:"Creating tables (Postgres + pgvector, no server)\u2026"});let r=await N0();return t({pct:100,label:"Embedded database ready."}),{mode:"embedded",engine:"pglite",dataDir:vo,migrationsRan:r.ran.length}}catch(r){throw r instanceof Y?r:Wt(r)}}var L0=f(()=>{va();Hc();vn()});async function is(e){if(e.url){let r=await Yt(e.url);if(!r.ok)throw Wt({code:r.code,message:r.error||`connection failed at ${r.stage}`});return{database:r.database,provider:r.provider,pgvector:r.pgvector}}let t=await Mu(e);if(!t.ok)throw Wt({code:t.code,message:t.message});return{}}var Bl=f(()=>{qe();vn()});import{userInfo as KG}from"node:os";import{spawn as qG}from"node:child_process";async function P0(e,t=()=>{}){let r=e.host||"localhost",n=Number(e.port)||5432,i=e.adminUser||KG().username,o=e.adminPassword||"";try{e.action==="start"&&(t({pct:5,label:"Starting local Postgres\u2026"}),await YG(e),await C0(r,n)),t({pct:20,label:`Connecting to Postgres on ${r}:${n}\u2026`});let s=A0();t({pct:45,label:"Creating database, role, and pgvector\u2026"}),await Fu({admin:{host:r,port:n,user:i,password:o},sigil:{database:xn,user:En,password:s}}),t({pct:70,label:"Running migrations\u2026"});let a=await ns({host:r,port:n,database:xn,user:En,password:s});return t({pct:90,label:"Verifying connection\u2026"}),await is({host:r,port:n,database:xn,user:En,password:s}),bn({mode:"local",url:null,host:r,port:n,name:xn,user:En,password:s}),t({pct:100,label:"Database ready."}),{mode:"local",host:r,port:n,database:xn,user:En,migrationsRan:a.ran.length}}catch(s){throw s instanceof Y?s:Wt(s)}}async function YG(e={}){let t=[];if(process.platform==="darwin"){let r=e.brewFormula?[e.brewFormula]:["postgresql@17","postgresql@16","postgresql@15","postgresql@14","postgresql"];for(let n of r)t.push(["brew",["services","start",n]])}e.dataDir&&t.push(["pg_ctl",["-D",e.dataDir,"start"]]),process.platform==="linux"&&t.push(["systemctl",["start","postgresql"]]);for(let[r,n]of t)if(await new Promise(o=>{let s=qG(r,n,{stdio:"ignore"});s.on("error",()=>o(!1)),s.on("close",a=>o(a===0)),setTimeout(()=>{try{s.kill()}catch{}o(!1)},15e3)}))return;throw new Y({message:"Could not start the local Postgres service automatically.",hint:process.platform==="darwin"?"Start it yourself (e.g. `brew services start postgresql@17`) and retry, or use an external connection.":"Start it yourself (e.g. `sudo systemctl start postgresql`) and retry, or use an external connection.",kind:"unreachable"})}var M0=f(()=>{qe();va();vn();Bl()});async function F0(e,t=()=>{}){try{let r=await _n();if(!r.installed)throw new Y({message:"Docker is not installed on this machine.",hint:"Install Docker Desktop, or use a local install / external connection string.",kind:"other"});if(!r.running){t({pct:8,label:"Docker is installed but not running \u2014 starting it\u2026"});try{await Wf()}catch(o){throw new Y({message:o.message||"Could not start Docker.",hint:"Start Docker Desktop manually and retry, or use a local install / external connection.",kind:"other"})}}t({pct:25,label:"Provisioning a dedicated Sigil Postgres container\u2026"});let n=await Vf({onProgress:o=>t({pct:35,label:o})});t({pct:70,label:"Running migrations\u2026"});let i=await ns({url:n.url});return t({pct:90,label:"Verifying connection\u2026"}),await is({url:n.url}),bn({mode:"docker",url:n.url,host:"localhost",port:n.port,name:xn,user:En,password:null}),t({pct:100,label:"Database ready."}),{mode:"docker",url:n.url,port:n.port,reused:n.reused,migrationsRan:i.ran.length}}catch(r){throw r instanceof Y?r:r.dockerUnavailable?new Y({message:"Docker is not available.",hint:"Start Docker Desktop and retry.",kind:"other"}):Wt(r)}}var B0=f(()=>{xa();va();vn();Bl()});import U0 from"pg";async function H0(e,t=()=>{}){let{url:r}=e;try{t({pct:10,label:"Validating connection string\u2026"});let n;try{n=it(r)}catch(a){throw new Y({message:`That connection string is malformed: ${a.message}`,kind:"other"})}let i=await Yt(r);if(!i.ok&&i.stage==="connect"&&i.code==="3D000"&&(t({pct:30,label:`Creating database "${n.database}"\u2026`}),await zG(n),i=await Yt(r)),!i.ok)throw new Y({message:i.stage==="parse"?`That connection string is malformed: ${i.error}`:`Could not reach that database (${i.stage}): ${i.error}`,hint:"Double-check the host, port, credentials, and SSL settings.",kind:"unreachable"});if(!i.pgvector&&(t({pct:45,label:"Enabling pgvector\u2026"}),!(await JG(n)).ok))throw new Y({message:"pgvector is not enabled, and these credentials cannot enable it.",hint:"Enable the `vector` extension (managed providers expose this in their dashboard), then retry.",kind:"no-pgvector"});t({pct:65,label:"Running migrations\u2026"});let o=await ns({url:r});t({pct:90,label:"Verifying connection\u2026"});let s=await is({url:r});return bn({mode:"url",url:r,host:null,port:null,name:s.database,user:null,password:null}),t({pct:100,label:"Database ready."}),{mode:"url",database:s.database,provider:s.provider,migrationsRan:o.ran.length}}catch(n){throw n instanceof Y?n:Wt(n)}}async function zG(e){let t=new U0.Client({...e,database:"postgres"});await t.connect();try{(await t.query("SELECT 1 FROM pg_database WHERE datname = $1",[e.database])).rowCount===0&&await t.query(`CREATE DATABASE ${$0(e.database)}`)}finally{try{await t.end()}catch{}}}async function JG(e){let t=new U0.Client(e);await t.connect();try{return await t.query("CREATE EXTENSION IF NOT EXISTS vector"),{ok:!0}}catch(r){return{ok:!1,code:r.code,message:r.message}}finally{try{await t.end()}catch{}}}var j0=f(()=>{qe();So();va();vn();Bl()});function G0(e={}){let t={};return["embedded","local","docker","url"].includes(e.mode)||(t.mode="choose one of: embedded, local, docker, url"),e.mode==="url"&&!e.url&&(t.url="a connection string is required"),e.mode==="local"&&e.action&&!["connect","start"].includes(e.action)&&(t.action="must be connect or start"),{ok:Object.keys(t).length===0,errors:t}}async function e2(e={},t=()=>{}){let r=G0(e);if(!r.ok)throw new Y({message:`Invalid database input: ${JSON.stringify(r.errors)}`,kind:"other"});return e.mode==="embedded"?D0(e,t):e.mode==="local"?P0(e,t):e.mode==="docker"?F0(e,t):H0(e,t)}var ZG,XG,QG,W0,V0=f(()=>{R0();L0();M0();B0();j0();vn();ZG="database",XG="Database",QG=k0;W0={id:ZG,title:XG,detect:QG,validate:G0,apply:e2}});function K0(){return zf}function o2(){return{providers:K0()}}function s2(e={}){let t={},r=zf.find(n=>n.id===e.provider);return r?(t2.has(r.id)&&!e.apiKey&&(t.apiKey="an API key is required"),r2.has(r.id)&&!e.model&&(t.model="a model is required"),{ok:Object.keys(t).length===0,errors:t}):(t.provider="choose a provider",{ok:!1,errors:t})}async function a2(e,t=()=>{}){let r=zf.find(n=>n.id===e.provider);if(!r)throw new Y({message:`Unknown LLM provider: ${e.provider}`,kind:"other"});t({pct:20,label:"Saving provider\u2026"}),Ge("llm",{provider:r.id,model:e.model||null,apiKey:e.apiKey||null,host:e.host||null}),t({pct:55,label:"Testing live LLM call\u2026"});try{let{resetDetection:n}=await Promise.resolve().then(()=>(Co(),Yc));n();let{prompt:i}=await Promise.resolve().then(()=>(Xe(),zc)),o=await i("Reply with the single word: ok",{caller:"setup-llm-test"});return t({pct:100,label:"LLM ready."}),{provider:r.id,response:String(o).slice(0,200)}}catch(n){throw new Y({message:n.message,kind:"llm"})}}var zf,t2,r2,n2,i2,q0,Y0=f(()=>{nt();Ea();zf=[{id:"claude-cli",label:"Claude Code",hint:"Uses your existing Claude Code subscription \u2014 no API key",recommended:!0,fields:[]},{id:"openrouter",label:"OpenRouter",hint:"One key, many models (cheapest default)",fields:[{name:"apiKey",label:"OpenRouter API key",type:"password",placeholder:"sk-or-\u2026"},{name:"model",label:"Model",type:"text",placeholder:"google/gemini-flash-latest"}]},{id:"openai",label:"OpenAI",hint:"Direct OpenAI access",fields:[{name:"apiKey",label:"OpenAI API key",type:"password",placeholder:"sk-\u2026"},{name:"model",label:"Model",type:"text",placeholder:"gpt-4o-mini"}]},{id:"anthropic",label:"Anthropic",hint:"Direct Anthropic API access",fields:[{name:"apiKey",label:"Anthropic API key",type:"password",placeholder:"sk-ant-\u2026"}]},{id:"ollama",label:"Ollama",hint:"Local + private; slower on small machines",fields:[{name:"host",label:"Ollama host",type:"text",placeholder:"http://localhost:11434",optional:!0},{name:"model",label:"Model",type:"text",placeholder:"qwen2.5:7b"}]}],t2=new Set(["openrouter","openai","anthropic"]),r2=new Set(["openrouter","openai","ollama"]),n2="llm",i2="LLM provider";q0={id:n2,title:i2,detect:o2,listProviders:K0,validate:s2,apply:a2}});var J0={};A(J0,{OLLAMA_EMBED_MODELS:()=>Sa,RECOMMENDED_EMBED_MODEL:()=>Hl,isReachable:()=>jl,listCompatibleModels:()=>Gl,listInstalledModels:()=>z0,pullModel:()=>Jf});async function jl(e=Ul){try{return(await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}async function z0(e=Ul){let t=await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Ollama /api/tags returned ${t.status}`);return((await t.json()).models||[]).map(n=>String(n.name||"").split(":")[0])}async function Gl(e=Ul){let t=[];try{t=await z0(e)}catch{}let r=new Set(t);return Sa.map(n=>({...n,installed:r.has(n.name)}))}async function Jf(e,t=()=>{},r=Ul){let n=await fetch(`${r}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:e,stream:!0})});if(!n.ok||!n.body)throw new Error(`Ollama pull failed: ${n.status}`);let i=n.body.getReader(),o=new TextDecoder,s="";for(;;){let{value:a,done:c}=await i.read();if(c)break;s+=o.decode(a,{stream:!0});let l;for(;(l=s.indexOf(`
905
+ `))!==-1;){let u=s.slice(0,l).trim();if(s=s.slice(l+1),!u)continue;let p;try{p=JSON.parse(u)}catch{continue}if(p.error)throw new Error(p.error);let d=p.total?Math.round((p.completed||0)/p.total*100):null;t({status:p.status||"",percent:d})}}}var Ul,Sa,Hl,Zf=f(()=>{Ul="http://localhost:11434",Sa=[{name:"mxbai-embed-large",dim:1024,size:"~670MB",recommended:!0},{name:"bge-large",dim:1024,size:"~670MB"},{name:"bge-m3",dim:1024,size:"~1.2GB"},{name:"snowflake-arctic-embed2",dim:1024,size:"~1.2GB"}],Hl=Sa.find(e=>e.recommended).name});var Xf={};A(Xf,{checkCorpusConsistency:()=>c2});async function c2({namespace:e=null}={}){let t=b("fact").where({status:"active"}).whereNotNull("embedding");e&&(t=t.where({namespace:e}));let n=(await t.select("embeddingModel").count({c:"*"}).groupBy("embeddingModel")).map(c=>({model:c.embeddingModel||"(unknown)",count:Number(c.c)})).filter(c=>c.count>0).sort((c,l)=>l.count-c.count),i=n.reduce((c,l)=>c+l.count,0),o=x.embedding.model||null,s=n.length>1,a=n.filter(c=>c.model!==o).reduce((c,l)=>c+l.count,0);return{current:o,histogram:n,mixed:s,total:i,stale:a}}var Qf=f(()=>{B();N()});function Z0(){let e=De();return process.env.OLLAMA_HOST||e.embedding?.host||"http://localhost:11434"}function X0(){let e=De();return em.map(t=>({...t,sharedKeyAvailable:t.shared&&e.llm.provider===t.id&&!!e.llm.apiKey}))}async function d2(){let e=Z0(),t=await jl(e),r=await Gl(e);return{providers:X0(),ollama:{reachable:t,host:e,models:r,recommended:Hl}}}function Q0(e,t){if(t.apiKey)return t.apiKey;if(e.shared){let r=De();if(r.llm.provider===e.id&&r.llm.apiKey)return r.llm.apiKey}return null}function p2(e={}){let t={},r=em.find(n=>n.id===e.provider);return r?r.keyed&&!Q0(r,e)&&(t.apiKey="an API key is required"):t.provider="choose a provider",{ok:Object.keys(t).length===0,errors:t}}async function f2(e,t=()=>{}){let r=em.find(i=>i.id===e.provider);if(!r)throw new Y({message:`Unknown embedding provider: ${e.provider}`,kind:"other"});let n=r.model;if(r.id==="ollama"&&e.model){let i=Sa.map(o=>o.name);if(!i.includes(e.model))throw new Y({message:`"${e.model}" isn't a known 1024-dim Ollama embedding model.`,hint:`Choose one of: ${i.join(", ")}.`,kind:"model-not-found"});n=e.model}if(t({pct:20,label:"Saving provider\u2026"}),Ge("embedding",{provider:r.id,model:n,apiKey:Q0(r,e),host:e.host||null}),r.id==="ollama"){let i=Z0();if(!await jl(i))throw new Y({message:"The local Ollama server is not reachable.",hint:"Start it with `ollama serve`, then retry.",kind:"ollama-down"});if(!(await Gl(i)).find(s=>s.name===n)?.installed){t({pct:30,label:`Pulling ${n}\u2026`});try{await Jf(n,({status:s,percent:a})=>{let c=a==null?35:30+Math.round(a*.2);t({pct:c,label:`Pulling ${n}: ${s}${a==null?"":` ${a}%`}`})},i)}catch(s){throw new Y({message:`Failed to pull ${n} from Ollama: ${s.message}`,hint:`Pull it manually with \`ollama pull ${n}\`, then retry.`,kind:"model-not-found"})}}}t({pct:55,label:"Testing embed call\u2026"});try{let{resetDetection:i}=await Promise.resolve().then(()=>(Co(),Yc));i();let{embed:o}=await Promise.resolve().then(()=>(rr(),Gs)),s=await o("Sigil setup embedding test",{cache:!1});if(!Array.isArray(s)||s.length===0)throw new Y({message:"The embedder returned an empty vector.",kind:"other"});if(s.length!==1024)throw new Y({message:`This model returned ${s.length}-dim vectors, but Sigil requires ${1024}.`,hint:`Pick a provider/model that produces ${1024}-dim embeddings.`,kind:"model-not-found"});let a="";try{let{checkCorpusConsistency:c}=await Promise.resolve().then(()=>(Qf(),Xf)),l=await c();l.stale>0&&(a=` ${l.stale} existing facts use a different model \u2014 run \`sigil repair embeddings\` so they rank correctly.`)}catch{}return t({pct:100,label:`Embedder ready.${a}`}),{provider:r.id,model:r.model,dim:s.length,staleFacts:!!a}}catch(i){if(i instanceof Y)throw i;let{diagnoseError:o}=await Promise.resolve().then(()=>(qe(),Pn)),s=o(i);throw new Y({message:s.humanMessage,hint:s.fixHint,kind:s.kind})}}var em,l2,u2,eT,tT=f(()=>{nt();Ea();qt();Zf();em=[{id:"openai",label:"OpenAI",hint:"text-embedding-3-large @ 1024 \u2014 best out-of-the-box quality",recommended:!0,model:"text-embedding-3-large",keyed:!0,shared:!0},{id:"voyage",label:"Voyage",hint:"voyage-3 @ 1024",model:"voyage-3",keyed:!0,shared:!1},{id:"openrouter",label:"OpenRouter",hint:"Gateway; reuses your LLM key",model:"openai/text-embedding-3-large",keyed:!0,shared:!0},{id:"ollama",label:"Ollama (local)",hint:"1024-dim local embeddings, free \u2014 pick a model, auto-pulled if missing",model:Hl,keyed:!1,shared:!1}],l2="embedding",u2="Embeddings";eT={id:l2,title:u2,detect:d2,listProviders:X0,validate:p2,apply:f2}});function g2(){return{ok:!0}}async function y2(){return{ok:!0}}var m2,h2,rT,nT=f(()=>{m2="connectors",h2="Coding agents";rT={id:m2,title:h2,validate:g2,apply:y2}});function b2(e={}){let t=(e.name||"").trim(),r={};return t?t.length>80&&(r.name="that name is too long"):r.name="tell us what to call you",{ok:Object.keys(r).length===0,errors:r}}async function x2(e,t=()=>{}){let r=(e.name||"").trim();if(!r)throw new Y({message:"A name is required.",kind:"other"});t({pct:15,label:"Saving your name\u2026"}),Ge("identity",{name:r}),t({pct:40,label:"Writing a first memory (testing the full stack)\u2026"});try{let{ingestDocument:n}=await Promise.resolve().then(()=>(Zs(),Js)),{default:i}=await Promise.resolve().then(()=>(N(),de)),o=await n({content:`The user's name is ${r}.`,namespace:i.defaults.namespace,classify:!0}),s=(o.facts?.added??0)+(o.facts?.updated??0);if(!s&&!o.skipped&&o.route!=="noise")throw new Y({message:"The memory pipeline ran but stored no fact.",kind:"other"});return t({pct:100,label:"All set."}),{name:r,factsAdded:s,route:o.route??null}}catch(n){if(n instanceof Y)throw n;let{diagnoseError:i}=await Promise.resolve().then(()=>(qe(),Pn)),o=i(n);throw new Y({message:o.humanMessage,hint:o.fixHint,kind:o.kind})}}var w2,_2,iT,oT=f(()=>{nt();Ea();w2="identity",_2="Your name";iT={id:w2,title:_2,validate:b2,apply:x2}});var Wl={};A(Wl,{disconnectAllClients:()=>sT,dropConfiguredDatabase:()=>E2,factoryReset:()=>v2,wipeMemoryData:()=>aT});async function sT(){let{listClients:e}=await Promise.resolve().then(()=>(Si(),es)),t=await e(),r=[];for(let n of t)try{(await n.verify()).installed&&(await n.uninstall({dryRun:!1}),r.push(n.id))}catch{}return r}async function aT(){let{default:e}=await Promise.resolve().then(()=>(B(),se)),{rows:t}=await e.raw("SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename NOT LIKE 'knex\\_%'"),r=t.map(n=>n.tablename);return r.length?(await e.raw(`TRUNCATE ${r.map(n=>`"${n}"`).join(", ")} RESTART IDENTITY CASCADE`),r.length):0}async function E2(){let e=De(),t=e.database?.mode;if(t==="docker"){let{removeLocalPostgres:r}=await Promise.resolve().then(()=>(xa(),Kf));return await r({deleteVolume:!0}),{kind:"docker",dropped:!0,detail:"removed sigil-postgres container + volume"}}if(t==="local"){let r=(await import("pg")).default,{userInfo:n}=await import("node:os"),i=e.database.name||"sigil",o=new r.Client({host:e.database.host||"localhost",port:e.database.port||5432,database:"postgres",user:e.database.adminUser||n().username,password:""});await o.connect();try{return await o.query(`DROP DATABASE IF EXISTS "${i.replace(/"/g,'""')}" WITH (FORCE)`),{kind:"local",dropped:!0,detail:`dropped database "${i}"`}}finally{try{await o.end()}catch{}}}return{kind:t||"none",dropped:!1,detail:"external/managed database left intact"}}async function v2({wipeMemory:e=!0}={}){let t=await sT(),r=0;if(e)try{r=await aT()}catch{}return ms(),{disconnected:t,tablesWiped:r,configWiped:!0}}var Vl=f(()=>{nt()});var uT={};A(uT,{detectStep:()=>im,factoryResetSetup:()=>cm,getSetupConfig:()=>sm,getSetupState:()=>Ar,listSteps:()=>nm,resetSetup:()=>am,runStep:()=>om});function tm(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(tm);let t={};for(let[r,n]of Object.entries(e))typeof n=="string"&&/url|uri|dsn|conn/i.test(r)?t[r]=n.replace(/(\w+:\/\/[^:@/\s]+):[^@/\s]+@/g,"$1:***@"):n&&typeof n=="object"?t[r]=tm(n):t[r]=n;return t}function lT(e){let t=rm.find(r=>r.id===e);if(!t){let r=new Error(`setup step not available: ${e}`);throw r.code="invalid_params",r}return t}function nm(){let e=new Set(rm.map(t=>t.id));return cT.map(t=>({...t,implemented:e.has(t.id)}))}function Ar(){let e=De(),t=cT.map(i=>({...i,implemented:rm.some(o=>o.id===i.id),status:e.setup?.steps?.[i.id]||"pending"})),r=t.find(i=>i.implemented&&i.status!=="done")?.id||null;return{complete:t.length>0&&t.every(i=>i.status==="done"),steps:t,currentStep:r}}async function im(e){let t=lT(e);return typeof t.detect=="function"?t.detect():{}}async function om(e,t={}){let r=lT(e),n=r.validate?r.validate(t):{ok:!0};if(!n.ok)return be.emit("setup",{step:e,status:"error",pct:0,label:"Please fix the highlighted fields.",errors:n.errors}),{ok:!1,step:e,errors:n.errors,state:Ar()};fs(e,"active"),be.emit("setup",{step:e,status:"active",pct:0,label:`Starting ${r.title}\u2026`});let i=(o={})=>be.emit("setup",{step:e,status:"active",pct:o.pct??0,label:o.label||""});try{let o=await r.apply(t,i);fs(e,"done");let s=tm(o);be.emit("setup",{step:e,status:"done",pct:100,label:`${r.title} ready.`,result:s});let a=Ar();return a.steps.every(l=>l.status==="done")&&!a.complete&&Iu(!0),{ok:!0,step:e,result:s,state:Ar()}}catch(o){return fs(e,"error"),be.emit("setup",{step:e,status:"error",pct:0,label:o.message,hint:o.hint||null,kind:o.kind||"other"}),{ok:!1,step:e,error:o.message,hint:o.hint||null,kind:o.kind||"other",state:Ar()}}}function sm(){let e=De(),t=null;if(e.database.url)try{t=new URL(e.database.url).host}catch{t="(connection url)"}return{database:{mode:e.database.mode,host:e.database.host,port:e.database.port,name:e.database.name,urlHost:t},llm:{provider:e.llm.provider,model:e.llm.model,hasKey:!!e.llm.apiKey},embedding:{provider:e.embedding.provider,model:e.embedding.model,dim:1024,hasKey:!!e.embedding.apiKey},identity:{name:e.identity.name},setup:e.setup}}function am(){return ms(),be.emit("setup",{step:null,status:"reset",pct:0,label:"Setup reset."}),Ar()}async function cm({wipeMemory:e=!0}={}){let{factoryReset:t}=await Promise.resolve().then(()=>(Vl(),Wl)),r=await t({wipeMemory:e});return be.emit("setup",{step:null,status:"reset",pct:0,label:"Sigil reset."}),{...r,state:Ar()}}var rm,cT,lm=f(()=>{ri();nt();V0();Y0();tT();nT();oT();rm=[W0,q0,eT,rT,iT],cT=[{id:"database",title:"Database"},{id:"llm",title:"LLM provider"},{id:"embedding",title:"Embeddings"},{id:"connectors",title:"Coding agents"},{id:"identity",title:"Your name"}]});function dT(e){e.register("setup.state",async()=>Ar()),e.register("setup.config",async()=>sm()),e.register("setup.steps",async()=>({steps:nm()})),e.register("setup.detect",async(t={})=>im(t.step)),e.register("setup.run",async(t={})=>om(t.step,t.input||{})),e.register("setup.reset",async()=>am()),e.register("setup.factoryReset",async(t={})=>cm({wipeMemory:t.wipeMemory!==!1}))}var pT=f(()=>{lm()});var mT={};A(mT,{CLASSIFIER_PROMPT:()=>fT,classifyTurn:()=>S2,saveFacts:()=>I2});async function S2(e){let{promptJson:t}=await Promise.resolve().then(()=>(Xe(),zc)),r=(await Promise.resolve().then(()=>(N(),de))).default,n=`${fT}
906
906
 
907
907
  ---
908
908
  User message:
909
- ${e}`,i=await t(n,{model:r.llm.extractionModel,caller:"stop-hook"});return!i||i.memorable!==!0?[]:Array.isArray(i.facts)?i.facts.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>=8&&o.length<=200):[]}async function S2(e,{podUids:t=[],throwOnError:r=!1}={}){let{ingestDocument:n}=await Promise.resolve().then(()=>(Zs(),Js)),i=(await Promise.resolve().then(()=>(N(),de))).default;for(let o of e)try{await n({content:o,namespace:i.defaults.namespace,classify:!1,podUids:t})}catch(s){if(process.stderr.write(`[sigil:stop] save failed: ${nr(s.message)}
909
+ ${e}`,i=await t(n,{model:r.llm.extractionModel,caller:"stop-hook"});return!i||i.memorable!==!0?[]:Array.isArray(i.facts)?i.facts.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>=8&&o.length<=200):[]}async function I2(e,{podUids:t=[],throwOnError:r=!1}={}){let{ingestDocument:n}=await Promise.resolve().then(()=>(Zs(),Js)),i=(await Promise.resolve().then(()=>(N(),de))).default;for(let o of e)try{await n({content:o,namespace:i.defaults.namespace,classify:!1,podUids:t})}catch(s){if(process.stderr.write(`[sigil:stop] save failed: ${nr(s.message)}
910
910
  `),r)throw s}try{let{updateContextSnapshot:o}=await Promise.resolve().then(()=>(an(),sn));await o({namespace:i.defaults.namespace})}catch{}}var fT,hT=f(()=>{No();fT=`You decide whether a user's message contains durable, memorable content for a long-term AI memory system, and extract the facts if so.
911
911
 
912
912
  SAVE these signals:
@@ -932,19 +932,19 @@ Each saved fact must:
932
932
  Respond as STRICT JSON, no markdown:
933
933
  {"memorable": boolean, "facts": ["...", "..."]}
934
934
 
935
- If "memorable" is false, "facts" must be an empty array.`});var Ia={};A(Ia,{appendSpool:()=>O2,drainStopSpool:()=>L2,spoolCount:()=>D2});import{existsSync as I2,readFileSync as T2,writeFileSync as A2,renameSync as $2,mkdirSync as C2,appendFileSync as k2}from"node:fs";import{dirname as R2}from"node:path";function O2({message:e,sessionId:t=null,cwd:r=null,transcriptPath:n=null,reason:i="unknown"}){if(e)try{C2(R2(Rr),{recursive:!0});let o={message:nr(e),sessionId:t,cwd:r,transcriptPath:n,reason:i,ts:Date.now()};k2(Rr,`${JSON.stringify(o)}
936
- `,"utf8"),N2()}catch{}}function um(){if(!I2(Rr))return[];try{return T2(Rr,"utf8").split(`
935
+ If "memorable" is false, "facts" must be an empty array.`});var Ia={};A(Ia,{appendSpool:()=>N2,drainStopSpool:()=>P2,spoolCount:()=>L2});import{existsSync as T2,readFileSync as A2,writeFileSync as $2,renameSync as C2,mkdirSync as k2,appendFileSync as R2}from"node:fs";import{dirname as O2}from"node:path";function N2({message:e,sessionId:t=null,cwd:r=null,transcriptPath:n=null,reason:i="unknown"}){if(e)try{k2(O2(Rr),{recursive:!0});let o={message:nr(e),sessionId:t,cwd:r,transcriptPath:n,reason:i,ts:Date.now()};R2(Rr,`${JSON.stringify(o)}
936
+ `,"utf8"),D2()}catch{}}function um(){if(!T2(Rr))return[];try{return A2(Rr,"utf8").split(`
937
937
  `).filter(Boolean).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(Boolean)}catch{return[]}}function yT(e){let t=`${Rr}.tmp`,r=e.map(n=>JSON.stringify(n)).join(`
938
- `);A2(t,r?`${r}
939
- `:"","utf8"),$2(t,Rr)}function N2(){let e=um();e.length>gT&&yT(e.slice(e.length-gT))}function D2(){return um().length}async function L2(){let e=um();if(!e.length)return{drained:0,remaining:0,replayed:0};let{classifyTurn:t,saveFacts:r}=await Promise.resolve().then(()=>(hT(),mT)),n=[],i=0,o=0;for(let s of e)try{let a=await t(s.message);a.length&&(await r(a,{podUids:[],throwOnError:!0}),o+=a.length),i++}catch{n.push(s)}return yT(n),{drained:i,remaining:n.length,replayed:o}}var gT,Ta=f(()=>{K();No();gT=500});function _T(e){e.register("repair.embeddings",async(t={})=>{let r=!!t.dryRun,n=t.namespace||null,i=!!t.allChunks,o=x.embedding.model||null,s=Number(x.embedding.dimensions)||1024;if(!o){let g=new Error("No embedding model configured \u2014 run `sigil init` before repairing.");throw g.code="invalid_config",g}let a=g=>(n&&g.where({namespace:n}),g.where({status:"active"}).andWhere(function(){this.whereNull("embedding").orWhereNull("embeddingModel").orWhereNot("embeddingModel",o)})),c=g=>(n&&g.where({namespace:n}),i||g.whereNull("embedding"),g),l=Number((await a(b("fact")).count({c:"*"}))[0]?.c||0),u=Number((await c(b("chunk")).count({c:"*"}))[0]?.c||0);if(r){let g=0;try{g=(await Promise.resolve().then(()=>(Ta(),Ia))).spoolCount()}catch{}return{dryRun:!0,namespace:n,model:o,facts:{scanned:l,repaired:0},chunks:{scanned:u,repaired:0},spool:{pending:g}}}let p=0;for(;;){let g=await a(b("fact")).select("id","content").limit(wT);if(!g.length)break;let w=await br(g.map(_=>_.content));for(let _=0;_<g.length;_++)await b("fact").where({id:g[_].id}).update({embedding:$e(w[_],{assertDim:!0}),embeddingModel:o,embeddingDim:s}),p++}let d=0,m=0;for(;;){let g=c(b("chunk")).select("id","content","contextualPrefix").orderBy("id","asc").limit(wT);i&&g.where("id",">",m);let w=await g;if(!w.length)break;let _=w.map(I=>I.contextualPrefix?`${I.contextualPrefix}
940
- ${I.content}`:I.content),E=await br(_);for(let I=0;I<w.length;I++)await b("chunk").where({id:w[I].id}).update({embedding:$e(E[I],{assertDim:!0})}),d++,m=w[I].id}let h={drained:0,remaining:0,replayed:0};try{let{drainStopSpool:g}=await Promise.resolve().then(()=>(Ta(),Ia));h=await g()}catch{}return{dryRun:!1,namespace:n,model:o,facts:{scanned:l,repaired:p},chunks:{scanned:u,repaired:d},spool:h}})}var wT,bT=f(()=>{B();N();qt();rr();_r();wT=100});function xT(e,{startedAt:t}){sx(e,{startedAt:t}),rv(e),Tv(e),$v(e),kv(e),Lv(e),Mv(e),Bv(e),Hv(e),Gv(e),tS(e),nS(e),oS(e),aS(e),OS(e),DS(e),PS(e),FS(e),qI(e),o0(e),a0(e),f0(e),h0(e),y0(e),b0(e),E0(e),dT(e),_T(e)}var ET=f(()=>{ax();nv();Av();Cv();Rv();Pv();Fv();Uv();jv();Wv();rS();iS();sS();cS();NS();LS();MS();BS();YI();s0();c0();m0();g0();w0();x0();v0();pT();bT()});var dm={};A(dm,{probeProviders:()=>P2});async function P2({llm:e=!0,embed:t=!0}={}){let r={checkedAt:Date.now()},[n,i]=await Promise.all([t?M2():Promise.resolve(null),e?F2():Promise.resolve(null)]);return t&&(r.embedding=n),e&&(r.llm=i),r}async function M2(){let e=x.embedding.provider||null,t=x.embedding.model||null;if(!e)return{ok:!1,provider:null,model:null,dim:1024,error:"not configured"};try{let{embed:r}=await Promise.resolve().then(()=>(rr(),Gs)),n=await r("Sigil provider health probe",{cache:!1});return!Array.isArray(n)||n.length!==1024?{ok:!1,provider:e,model:t,dim:Array.isArray(n)?n.length:null,error:`returned ${Array.isArray(n)?`${n.length}-dim`:"no"} vector, expected ${1024}`}:{ok:!0,provider:e,model:t,dim:n.length,error:null}}catch(r){return{ok:!1,provider:e,model:t,dim:null,error:r.message}}}async function F2(){let e=x.llm.provider||null,t=null;try{let{getConfig:r}=await Promise.resolve().then(()=>(nt(),Tu));t=r()?.llm?.model||null}catch{}if(!e)return{ok:!1,provider:null,model:null,error:"not configured"};try{let{prompt:r}=await Promise.resolve().then(()=>(Xe(),zc)),n=await r("Reply with the single word: ok",{caller:"provider-probe"});return typeof n!="string"||!n.trim()?{ok:!1,provider:e,model:t,error:"empty response from provider"}:{ok:!0,provider:e,model:t,error:null}}catch(r){return{ok:!1,provider:e,model:t,error:r.message}}}var pm=f(()=>{N();qt()});var vT={};A(vT,{installLiteProxy:()=>H2});async function H2({registry:e,log:t}){let{getMemoryClient:r}=await Promise.resolve().then(()=>(_l(),wl)),n=0,i=0;for(let o of B2)e.replace(o,async s=>(await r()).call(o,s))&&n++;for(let o of U2)e.replace(o,()=>{let a=new Error(`"${o}" is not available on a lite-follower device. Run on the master device.`);throw a.code="not_on_follower",a})&&i++;t(`lite-follower: ${n} methods proxied, ${i} forbidden, rest local`)}var B2,U2,ST=f(()=>{B2=new Set(["search","searchEntity","traverseGraph","getFactContext","getEntityContext","getPod","listPods","listFacts","status","refreshContext.fetch","refreshContext.explain","remember","forgetFact","ingestDoc"]),U2=new Set(["pair.create","pair.list","pair.revoke","pair.sweep","device.list","device.revoke","device.activate","runMigrations","testDbConnection"])});var TT={};A(TT,{startDaemon:()=>IT});import{createWriteStream as j2,writeFileSync as G2,rmSync as W2}from"node:fs";import{appendFile as V2}from"node:fs/promises";async function IT({foreground:e=!1}={}){delete process.env.SIGIL_AGENT,await Ru();let t=await dr();t&&(process.stderr.write(`[sigild] already running (pid ${t})
941
- `),process.exit(0));let r=Y2();r(`starting (pid ${process.pid}, node ${process.version})`),process.on("unhandledRejection",p=>{r(`unhandledRejection: ${p?.stack||p}`)}),process.on("uncaughtException",p=>{r(`uncaughtException: ${p?.stack||p}`),process.exit(1)}),Ua();let n=kh();Gu(n),xT(n,{startedAt:fm});let{default:i}=await Promise.resolve().then(()=>(N(),de)),o=null;if(i.http.enabled)try{o=await rx({registry:n,log:r,config:i})}catch(p){p.code==="EADDRINUSE"&&(r(`http port ${i.http.port} already in use \u2014 another daemon is serving; exiting`),process.stderr.write(`[sigild] already running (port ${i.http.port} in use)
942
- `),Qa(),process.exit(0)),r(`http server failed to start: ${p.message}`)}await Cu();let s=await Nh({registry:n,log:r});if(i.network.mode!=="lite-follower"){try{let{ensureLocalPostgresRunning:p}=await Promise.resolve().then(()=>(xa(),Kf));(await p()).started&&r("started local sigil-postgres container")}catch{}q2(r),(async()=>{try{let{probeProviders:p}=await Promise.resolve().then(()=>(pm(),dm)),{setProviderHealth:d}=await Promise.resolve().then(()=>(Fr(),bs)),m=await p();d(m),m.embedding&&!m.embedding.ok&&r(`embedding provider DOWN: ${m.embedding.error}`),m.llm&&!m.llm.ok&&r(`llm provider DOWN: ${m.llm.error}`),m.embedding?.ok&&m.llm?.ok&&r("providers healthy (llm + embedding probed ok)")}catch(p){r(`provider probe failed: ${p.message}`)}})(),(async()=>{try{let{drainStopSpool:p}=await Promise.resolve().then(()=>(Ta(),Ia)),d=await p();d.drained&&r(`stop-spool drained: ${d.drained} turns replayed (${d.replayed} facts, ${d.remaining} remaining)`)}catch(p){r(`stop-spool drain failed: ${p.message}`)}})()}let a=!1;if(i.network.enabled)try{if(i.network.mode==="master"){let{registerProtocol:m}=await Promise.resolve().then(()=>(xr(),ln)),{PAIR_ALPN:h,createPairAcceptor:g}=await Promise.resolve().then(()=>(Ml(),jf)),{RPC_ALPN:w,createRpcAcceptor:_}=await Promise.resolve().then(()=>(ff(),_S));m(h,g({log:r})),m(w,_({registry:n,log:r})),r(`registered accept handlers: ${h}, ${w}`)}let{getNodeInfo:p}=await Promise.resolve().then(()=>(xr(),ln)),d=await p();a=!0,r(`iroh node up: ${d.nodeId}`),d.relayUrl&&r(`iroh relay: ${d.relayUrl}`)}catch(p){r(`iroh failed to start: ${p.message}`)}else r(`iroh disabled (SIGIL_MODE=${i.network.mode})`);if(i.network.mode==="lite-follower")try{let{installLiteProxy:p}=await Promise.resolve().then(()=>(ST(),vT));await p({registry:n,log:r})}catch(p){r(`lite-proxy install failed: ${p.message}`)}let c=await K2(),l=()=>{try{G2(Nr,JSON.stringify({pid:process.pid,version:c,node:process.version,startedAt:fm,ts:Date.now(),supervised:process.env.SIGIL_SUPERVISED==="1"}),"utf8")}catch{}};l();let u=setInterval(l,15e3);u.unref(),ku(async p=>{r(`received ${p}, shutting down`),clearInterval(u);try{W2(Nr,{force:!0})}catch{}if(await s.close(),o&&await o.close(),a)try{let{shutdownEndpoint:d}=await Promise.resolve().then(()=>(xr(),ln));await d()}catch(d){r(`iroh shutdown failed: ${d.message}`)}try{let{default:d}=await Promise.resolve().then(()=>(B(),se));await d.destroy()}catch(d){r(`pool destroy failed: ${d.message}`)}await ja(),Qa(),r("stopped")}),r(`ready in ${Date.now()-fm}ms \u2014 ${n.list().length} methods registered`),e&&process.stdout.write(`sigild ready
943
- `)}async function K2(){try{let{readFile:e}=await import("node:fs/promises"),{join:t}=await import("node:path"),{PKG_ROOT:r}=await Promise.resolve().then(()=>(K(),Ma));return JSON.parse(await e(t(r,"package.json"),"utf8")).version}catch{return"unknown"}}async function q2(e){try{let{default:t}=await Promise.resolve().then(()=>(B(),se)),{setDbHealth:r}=await Promise.resolve().then(()=>(Fr(),bs));try{await t.raw("SELECT 1"),r({healthy:!0,error:null,checkedAt:Date.now()})}catch(n){r({healthy:!1,error:n.message,checkedAt:Date.now()}),e(`DB UNREACHABLE: ${n.message} \u2014 memory operations will fail until Postgres is back`)}}catch{}}function Y2(){let e;try{e=j2(he,{flags:"a"})}catch{}return t=>{let r=`[${new Date().toISOString()}] ${t}
944
- `;e?e.write(r):process.stderr.write(r)}}var fm,AT=f(()=>{nt();K();Dn();Rh();Fr();Dh();ox();ET();fm=Date.now();import.meta.url===`file://${process.argv[1]}`&&IT({foreground:!0}).catch(async e=>{try{await V2(he,`[fatal] ${e.stack||e.message}
938
+ `);$2(t,r?`${r}
939
+ `:"","utf8"),C2(t,Rr)}function D2(){let e=um();e.length>gT&&yT(e.slice(e.length-gT))}function L2(){return um().length}async function P2(){let e=um();if(!e.length)return{drained:0,remaining:0,replayed:0};let{classifyTurn:t,saveFacts:r}=await Promise.resolve().then(()=>(hT(),mT)),n=[],i=0,o=0;for(let s of e)try{let a=await t(s.message);a.length&&(await r(a,{podUids:[],throwOnError:!0}),o+=a.length),i++}catch{n.push(s)}return yT(n),{drained:i,remaining:n.length,replayed:o}}var gT,Ta=f(()=>{K();No();gT=500});function _T(e){e.register("repair.embeddings",async(t={})=>{let r=!!t.dryRun,n=t.namespace||null,i=!!t.allChunks,o=x.embedding.model||null,s=Number(x.embedding.dimensions)||1024;if(!o){let g=new Error("No embedding model configured \u2014 run `sigil init` before repairing.");throw g.code="invalid_config",g}let a=g=>(n&&g.where({namespace:n}),g.where({status:"active"}).andWhere(function(){this.whereNull("embedding").orWhereNull("embeddingModel").orWhereNot("embeddingModel",o)})),c=g=>(n&&g.where({namespace:n}),i||g.whereNull("embedding"),g),l=Number((await a(b("fact")).count({c:"*"}))[0]?.c||0),u=Number((await c(b("chunk")).count({c:"*"}))[0]?.c||0);if(r){let g=0;try{g=(await Promise.resolve().then(()=>(Ta(),Ia))).spoolCount()}catch{}return{dryRun:!0,namespace:n,model:o,facts:{scanned:l,repaired:0},chunks:{scanned:u,repaired:0},spool:{pending:g}}}let p=0;for(;;){let g=await a(b("fact")).select("id","content").limit(wT);if(!g.length)break;let w=await br(g.map(_=>_.content));for(let _=0;_<g.length;_++)await b("fact").where({id:g[_].id}).update({embedding:$e(w[_],{assertDim:!0}),embeddingModel:o,embeddingDim:s}),p++}let d=0,m=0;for(;;){let g=c(b("chunk")).select("id","content","contextualPrefix").orderBy("id","asc").limit(wT);i&&g.where("id",">",m);let w=await g;if(!w.length)break;let _=w.map(I=>I.contextualPrefix?`${I.contextualPrefix}
940
+ ${I.content}`:I.content),E=await br(_);for(let I=0;I<w.length;I++)await b("chunk").where({id:w[I].id}).update({embedding:$e(E[I],{assertDim:!0})}),d++,m=w[I].id}let h={drained:0,remaining:0,replayed:0};try{let{drainStopSpool:g}=await Promise.resolve().then(()=>(Ta(),Ia));h=await g()}catch{}return{dryRun:!1,namespace:n,model:o,facts:{scanned:l,repaired:p},chunks:{scanned:u,repaired:d},spool:h}})}var wT,bT=f(()=>{B();N();qt();rr();_r();wT=100});function xT(e,{startedAt:t}){sx(e,{startedAt:t}),rv(e),Tv(e),$v(e),kv(e),Lv(e),Mv(e),Bv(e),Hv(e),Gv(e),tS(e),nS(e),oS(e),aS(e),OS(e),DS(e),PS(e),FS(e),qI(e),o0(e),a0(e),f0(e),h0(e),y0(e),b0(e),E0(e),dT(e),_T(e)}var ET=f(()=>{ax();nv();Av();Cv();Rv();Pv();Fv();Uv();jv();Wv();rS();iS();sS();cS();NS();LS();MS();BS();YI();s0();c0();m0();g0();w0();x0();v0();pT();bT()});var dm={};A(dm,{probeProviders:()=>M2});async function M2({llm:e=!0,embed:t=!0}={}){let r={checkedAt:Date.now()},[n,i]=await Promise.all([t?F2():Promise.resolve(null),e?B2():Promise.resolve(null)]);return t&&(r.embedding=n),e&&(r.llm=i),r}async function F2(){let e=x.embedding.provider||null,t=x.embedding.model||null;if(!e)return{ok:!1,provider:null,model:null,dim:1024,error:"not configured"};try{let{embed:r}=await Promise.resolve().then(()=>(rr(),Gs)),n=await r("Sigil provider health probe",{cache:!1});return!Array.isArray(n)||n.length!==1024?{ok:!1,provider:e,model:t,dim:Array.isArray(n)?n.length:null,error:`returned ${Array.isArray(n)?`${n.length}-dim`:"no"} vector, expected ${1024}`}:{ok:!0,provider:e,model:t,dim:n.length,error:null}}catch(r){return{ok:!1,provider:e,model:t,dim:null,error:r.message}}}async function B2(){let e=x.llm.provider||null,t=null;try{let{getConfig:r}=await Promise.resolve().then(()=>(nt(),Tu));t=r()?.llm?.model||null}catch{}if(!e)return{ok:!1,provider:null,model:null,error:"not configured"};try{let{prompt:r}=await Promise.resolve().then(()=>(Xe(),zc)),n=await r("Reply with the single word: ok",{caller:"provider-probe"});return typeof n!="string"||!n.trim()?{ok:!1,provider:e,model:t,error:"empty response from provider"}:{ok:!0,provider:e,model:t,error:null}}catch(r){return{ok:!1,provider:e,model:t,error:r.message}}}var pm=f(()=>{N();qt()});var vT={};A(vT,{installLiteProxy:()=>j2});async function j2({registry:e,log:t}){let{getMemoryClient:r}=await Promise.resolve().then(()=>(_l(),wl)),n=0,i=0;for(let o of U2)e.replace(o,async s=>(await r()).call(o,s))&&n++;for(let o of H2)e.replace(o,()=>{let a=new Error(`"${o}" is not available on a lite-follower device. Run on the master device.`);throw a.code="not_on_follower",a})&&i++;t(`lite-follower: ${n} methods proxied, ${i} forbidden, rest local`)}var U2,H2,ST=f(()=>{U2=new Set(["search","searchEntity","traverseGraph","getFactContext","getEntityContext","getPod","listPods","listFacts","status","refreshContext.fetch","refreshContext.explain","remember","forgetFact","ingestDoc"]),H2=new Set(["pair.create","pair.list","pair.revoke","pair.sweep","device.list","device.revoke","device.activate","runMigrations","testDbConnection"])});var TT={};A(TT,{startDaemon:()=>IT});import{createWriteStream as G2,writeFileSync as W2,rmSync as V2}from"node:fs";import{appendFile as K2}from"node:fs/promises";async function IT({foreground:e=!1}={}){delete process.env.SIGIL_AGENT,await Ru();let t=await dr();t&&(process.stderr.write(`[sigild] already running (pid ${t})
941
+ `),process.exit(0));let r=z2();r(`starting (pid ${process.pid}, node ${process.version})`),process.on("unhandledRejection",p=>{r(`unhandledRejection: ${p?.stack||p}`)}),process.on("uncaughtException",p=>{r(`uncaughtException: ${p?.stack||p}`),process.exit(1)}),Ua();let n=kh();Gu(n),xT(n,{startedAt:fm});let{default:i}=await Promise.resolve().then(()=>(N(),de)),o=null;if(i.http.enabled)try{o=await rx({registry:n,log:r,config:i})}catch(p){p.code==="EADDRINUSE"&&(r(`http port ${i.http.port} already in use \u2014 another daemon is serving; exiting`),process.stderr.write(`[sigild] already running (port ${i.http.port} in use)
942
+ `),Qa(),process.exit(0)),r(`http server failed to start: ${p.message}`)}await Cu();let s=await Nh({registry:n,log:r});if(i.network.mode!=="lite-follower"){try{let{ensureLocalPostgresRunning:p}=await Promise.resolve().then(()=>(xa(),Kf));(await p()).started&&r("started local sigil-postgres container")}catch{}Y2(r),(async()=>{try{let{probeProviders:p}=await Promise.resolve().then(()=>(pm(),dm)),{setProviderHealth:d}=await Promise.resolve().then(()=>(Fr(),bs)),m=await p();d(m),m.embedding&&!m.embedding.ok&&r(`embedding provider DOWN: ${m.embedding.error}`),m.llm&&!m.llm.ok&&r(`llm provider DOWN: ${m.llm.error}`),m.embedding?.ok&&m.llm?.ok&&r("providers healthy (llm + embedding probed ok)")}catch(p){r(`provider probe failed: ${p.message}`)}})(),(async()=>{try{let{drainStopSpool:p}=await Promise.resolve().then(()=>(Ta(),Ia)),d=await p();d.drained&&r(`stop-spool drained: ${d.drained} turns replayed (${d.replayed} facts, ${d.remaining} remaining)`)}catch(p){r(`stop-spool drain failed: ${p.message}`)}})()}let a=!1;if(i.network.enabled)try{if(i.network.mode==="master"){let{registerProtocol:m}=await Promise.resolve().then(()=>(xr(),ln)),{PAIR_ALPN:h,createPairAcceptor:g}=await Promise.resolve().then(()=>(Ml(),jf)),{RPC_ALPN:w,createRpcAcceptor:_}=await Promise.resolve().then(()=>(ff(),_S));m(h,g({log:r})),m(w,_({registry:n,log:r})),r(`registered accept handlers: ${h}, ${w}`)}let{getNodeInfo:p}=await Promise.resolve().then(()=>(xr(),ln)),d=await p();a=!0,r(`iroh node up: ${d.nodeId}`),d.relayUrl&&r(`iroh relay: ${d.relayUrl}`)}catch(p){r(`iroh failed to start: ${p.message}`)}else r(`iroh disabled (SIGIL_MODE=${i.network.mode})`);if(i.network.mode==="lite-follower")try{let{installLiteProxy:p}=await Promise.resolve().then(()=>(ST(),vT));await p({registry:n,log:r})}catch(p){r(`lite-proxy install failed: ${p.message}`)}let c=await q2(),l=()=>{try{W2(Nr,JSON.stringify({pid:process.pid,version:c,node:process.version,startedAt:fm,ts:Date.now(),supervised:process.env.SIGIL_SUPERVISED==="1"}),"utf8")}catch{}};l();let u=setInterval(l,15e3);u.unref(),ku(async p=>{r(`received ${p}, shutting down`),clearInterval(u);try{V2(Nr,{force:!0})}catch{}if(await s.close(),o&&await o.close(),a)try{let{shutdownEndpoint:d}=await Promise.resolve().then(()=>(xr(),ln));await d()}catch(d){r(`iroh shutdown failed: ${d.message}`)}try{let{default:d}=await Promise.resolve().then(()=>(B(),se));await d.destroy()}catch(d){r(`pool destroy failed: ${d.message}`)}await ja(),Qa(),r("stopped")}),r(`ready in ${Date.now()-fm}ms \u2014 ${n.list().length} methods registered`),e&&process.stdout.write(`sigild ready
943
+ `)}async function q2(){try{let{readFile:e}=await import("node:fs/promises"),{join:t}=await import("node:path"),{PKG_ROOT:r}=await Promise.resolve().then(()=>(K(),Ma));return JSON.parse(await e(t(r,"package.json"),"utf8")).version}catch{return"unknown"}}async function Y2(e){try{let{default:t}=await Promise.resolve().then(()=>(B(),se)),{setDbHealth:r}=await Promise.resolve().then(()=>(Fr(),bs));try{await t.raw("SELECT 1"),r({healthy:!0,error:null,checkedAt:Date.now()})}catch(n){r({healthy:!1,error:n.message,checkedAt:Date.now()}),e(`DB UNREACHABLE: ${n.message} \u2014 memory operations will fail until Postgres is back`)}}catch{}}function z2(){let e;try{e=G2(he,{flags:"a"})}catch{}return t=>{let r=`[${new Date().toISOString()}] ${t}
944
+ `;e?e.write(r):process.stderr.write(r)}}var fm,AT=f(()=>{nt();K();Dn();Rh();Fr();Dh();ox();ET();fm=Date.now();import.meta.url===`file://${process.argv[1]}`&&IT({foreground:!0}).catch(async e=>{try{await K2(he,`[fatal] ${e.stack||e.message}
945
945
  `)}catch{}process.stderr.write(`[sigild] fatal: ${e.message}
946
- `),process.exit(1)})});var DT={};A(DT,{runDaemon:()=>J2});import{existsSync as z2,createReadStream as $T}from"node:fs";import{stat as CT}from"node:fs/promises";import{setTimeout as mm}from"node:timers/promises";async function J2(e){let[t,...r]=e;if(!t||t==="--help"||t==="-h"){console.log(kT);return}switch(t){case"start":return OT(r);case"stop":return NT(r);case"status":return Z2(r);case"restart":return await NT(r),await mm(200),OT(r);case"logs":return X2(r);case"open":return RT({launch:!0});case"url":return RT({launch:!1});default:console.error(`Unknown subcommand: daemon ${t}
947
- `),console.log(kT),process.exit(1)}}async function RT({launch:e}){let t=await ht({quiet:!0});await t.call("ping",{}),await t.close();let{default:r}=await Promise.resolve().then(()=>(N(),de)),{getGuiToken:n}=await Promise.resolve().then(()=>(ys(),Va)),i=await n(),o=`http://${r.http.host}:${r.http.port}/?t=${i}`;if(console.log(o),!e)return;let s=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:a}=await import("node:child_process");a(s,[o],{detached:!0,stdio:"ignore"}).unref()}async function OT(e){let t=e.includes("--foreground")||e.includes("-f"),r=await dr();if(r){console.log(`sigild already running (pid ${r})`);return}if(t){let{startDaemon:n}=await Promise.resolve().then(()=>(AT(),TT));await n({foreground:!0});return}await ht({quiet:!0}).then(async n=>{let{data:i}=await n.call("ping",{});await n.close(),console.log(`sigild started (pid ${i.pid}, version ${i.version})`)})}async function NT(){let e=await hs();if(!e||!Nn(e)){console.log("sigild is not running");return}try{let{isServiceInstalled:r}=await Promise.resolve().then(()=>(Ll(),i0));if(await r()){console.log("sigild is managed by the always-up service \u2014 it will auto-restart after a stop."),console.log("To keep it down, run: sigil service stop (re-enable with `sigil service start`)");return}}catch{}try{process.kill(e,"SIGTERM")}catch(r){console.error(`failed to signal pid ${e}: ${r.message}`),process.exit(1)}let t=Date.now()+5e3;for(;Date.now()<t&&Nn(e);)await mm(50);if(Nn(e)){console.error(`sigild (pid ${e}) did not exit within 5s \u2014 sending SIGKILL`);try{process.kill(e,"SIGKILL")}catch{}}console.log("sigild stopped")}async function Z2(){let e=await hs();if(!e||!Nn(e)){console.log("sigild: not running");return}try{let t=await Hi({timeoutMs:2e3}),{data:r}=await t.call("ping",{});await t.close(),console.log("sigild: running"),console.log(` pid ${r.pid}`),console.log(` version ${r.version}`),console.log(` node ${r.node}`),console.log(` uptime ${Ka(r.uptimeMs)}`),console.log(` socket ${je}`)}catch(t){console.log(`sigild: pid ${e} alive but socket unresponsive (${t.message})`),process.exit(1)}}async function X2(e){let t=e.includes("--follow")||e.includes("-f");if(!z2(he)){console.log(`(no log file yet at ${he})`);return}if(await new Promise((n,i)=>{let o=$T(he,{encoding:"utf8"});o.on("data",s=>process.stdout.write(s)),o.on("end",n),o.on("error",i)}),!t)return;let r=(await CT(he)).size;for(;;){await mm(250);let n=await CT(he).catch(()=>null);if(!n||n.size===r)continue;let i=$T(he,{encoding:"utf8",start:r,end:n.size-1});i.on("data",o=>process.stdout.write(o)),await new Promise((o,s)=>{i.on("end",o),i.on("error",s)}),r=n.size}}var kT,LT=f(()=>{K();Dn();Du();We();Pu();kT=`sigil daemon \u2014 control the Sigil daemon
946
+ `),process.exit(1)})});var DT={};A(DT,{runDaemon:()=>Z2});import{existsSync as J2,createReadStream as $T}from"node:fs";import{stat as CT}from"node:fs/promises";import{setTimeout as mm}from"node:timers/promises";async function Z2(e){let[t,...r]=e;if(!t||t==="--help"||t==="-h"){console.log(kT);return}switch(t){case"start":return OT(r);case"stop":return NT(r);case"status":return X2(r);case"restart":return await NT(r),await mm(200),OT(r);case"logs":return Q2(r);case"open":return RT({launch:!0});case"url":return RT({launch:!1});default:console.error(`Unknown subcommand: daemon ${t}
947
+ `),console.log(kT),process.exit(1)}}async function RT({launch:e}){let t=await ht({quiet:!0});await t.call("ping",{}),await t.close();let{default:r}=await Promise.resolve().then(()=>(N(),de)),{getGuiToken:n}=await Promise.resolve().then(()=>(ys(),Va)),i=await n(),o=`http://${r.http.host}:${r.http.port}/?t=${i}`;if(console.log(o),!e)return;let s=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:a}=await import("node:child_process");a(s,[o],{detached:!0,stdio:"ignore"}).unref()}async function OT(e){let t=e.includes("--foreground")||e.includes("-f"),r=await dr();if(r){console.log(`sigild already running (pid ${r})`);return}if(t){let{startDaemon:n}=await Promise.resolve().then(()=>(AT(),TT));await n({foreground:!0});return}await ht({quiet:!0}).then(async n=>{let{data:i}=await n.call("ping",{});await n.close(),console.log(`sigild started (pid ${i.pid}, version ${i.version})`)})}async function NT(){let e=await hs();if(!e||!Nn(e)){console.log("sigild is not running");return}try{let{isServiceInstalled:r}=await Promise.resolve().then(()=>(Ll(),i0));if(await r()){console.log("sigild is managed by the always-up service \u2014 it will auto-restart after a stop."),console.log("To keep it down, run: sigil service stop (re-enable with `sigil service start`)");return}}catch{}try{process.kill(e,"SIGTERM")}catch(r){console.error(`failed to signal pid ${e}: ${r.message}`),process.exit(1)}let t=Date.now()+5e3;for(;Date.now()<t&&Nn(e);)await mm(50);if(Nn(e)){console.error(`sigild (pid ${e}) did not exit within 5s \u2014 sending SIGKILL`);try{process.kill(e,"SIGKILL")}catch{}}console.log("sigild stopped")}async function X2(){let e=await hs();if(!e||!Nn(e)){console.log("sigild: not running");return}try{let t=await Hi({timeoutMs:2e3}),{data:r}=await t.call("ping",{});await t.close(),console.log("sigild: running"),console.log(` pid ${r.pid}`),console.log(` version ${r.version}`),console.log(` node ${r.node}`),console.log(` uptime ${Ka(r.uptimeMs)}`),console.log(` socket ${je}`)}catch(t){console.log(`sigild: pid ${e} alive but socket unresponsive (${t.message})`),process.exit(1)}}async function Q2(e){let t=e.includes("--follow")||e.includes("-f");if(!J2(he)){console.log(`(no log file yet at ${he})`);return}if(await new Promise((n,i)=>{let o=$T(he,{encoding:"utf8"});o.on("data",s=>process.stdout.write(s)),o.on("end",n),o.on("error",i)}),!t)return;let r=(await CT(he)).size;for(;;){await mm(250);let n=await CT(he).catch(()=>null);if(!n||n.size===r)continue;let i=$T(he,{encoding:"utf8",start:r,end:n.size-1});i.on("data",o=>process.stdout.write(o)),await new Promise((o,s)=>{i.on("end",o),i.on("error",s)}),r=n.size}}var kT,LT=f(()=>{K();Dn();Du();We();Pu();kT=`sigil daemon \u2014 control the Sigil daemon
948
948
 
949
949
  Usage:
950
950
  sigil daemon start [--foreground]
@@ -962,8 +962,8 @@ first use; you only need these commands for explicit lifecycle control.
962
962
  Files:
963
963
  ${je} Unix socket
964
964
  ${Or} PID file
965
- ${he} Append-only log`});var MT={};A(MT,{runService:()=>Q2});async function Q2(e){let[t]=e;if(!t||t==="--help"||t==="-h"){console.log(PT);return}switch(!Df()&&t!=="status"&&(console.error(`No always-up backend for platform "${process.platform}". Sigil still auto-starts on first use.`),process.exit(1)),t){case"install":return eW();case"uninstall":return tW();case"status":return rW();case"start":return hm(Pf,"started");case"stop":return hm(Mf,"stopped");case"restart":return hm(Ff,"restarted");default:console.error(`Unknown subcommand: service ${t}
966
- `),console.log(PT),process.exit(1)}}async function eW(){try{let e=await Lf();console.log(`Sigil service installed (${e.manager}).`),console.log(` unit ${e.unitPath}`),console.log(" Sigil will now start on login and restart automatically if it crashes.")}catch(e){console.error(`service install failed: ${e.message}`),process.exit(1)}}async function tW(){let e=await ma();console.log(`Sigil service removed (${e.manager}). Sigil still auto-starts on first use.`)}async function hm(e,t){let r=await e();r.ok?console.log(`Sigil service ${t} (${r.manager}).`):(console.error(`service ${t} failed (${r.manager}).`),process.exit(1))}async function rW(){let{platform:e,supervisor:t,heartbeat:r}=await ha();if(console.log(`platform ${e}`),t.unsupported?console.log("service unsupported on this platform (auto-spawn only)"):(console.log(`service ${t.installed?"installed":"not installed"} (${t.manager})`),console.log(` ${t.running?"loaded/running":"not loaded"}`),t.unitPath&&console.log(` unit ${t.unitPath}`)),r){let n=r.ageMs==null?"\u2014":`${Math.round(r.ageMs/1e3)}s ago`;console.log(`daemon pid ${r.pid} \xB7 v${r.version} \xB7 up ${Ka(Date.now()-r.startedAt)}`),console.log(`heartbeat ${n}${r.supervised?" \xB7 supervised":""}`)}else console.log("daemon no heartbeat (not running)")}var PT,FT=f(()=>{Ll();Pu();PT=`sigil service \u2014 keep Sigil always running
965
+ ${he} Append-only log`});var MT={};A(MT,{runService:()=>eW});async function eW(e){let[t]=e;if(!t||t==="--help"||t==="-h"){console.log(PT);return}switch(!Df()&&t!=="status"&&(console.error(`No always-up backend for platform "${process.platform}". Sigil still auto-starts on first use.`),process.exit(1)),t){case"install":return tW();case"uninstall":return rW();case"status":return nW();case"start":return hm(Pf,"started");case"stop":return hm(Mf,"stopped");case"restart":return hm(Ff,"restarted");default:console.error(`Unknown subcommand: service ${t}
966
+ `),console.log(PT),process.exit(1)}}async function tW(){try{let e=await Lf();console.log(`Sigil service installed (${e.manager}).`),console.log(` unit ${e.unitPath}`),console.log(" Sigil will now start on login and restart automatically if it crashes.")}catch(e){console.error(`service install failed: ${e.message}`),process.exit(1)}}async function rW(){let e=await ma();console.log(`Sigil service removed (${e.manager}). Sigil still auto-starts on first use.`)}async function hm(e,t){let r=await e();r.ok?console.log(`Sigil service ${t} (${r.manager}).`):(console.error(`service ${t} failed (${r.manager}).`),process.exit(1))}async function nW(){let{platform:e,supervisor:t,heartbeat:r}=await ha();if(console.log(`platform ${e}`),t.unsupported?console.log("service unsupported on this platform (auto-spawn only)"):(console.log(`service ${t.installed?"installed":"not installed"} (${t.manager})`),console.log(` ${t.running?"loaded/running":"not loaded"}`),t.unitPath&&console.log(` unit ${t.unitPath}`)),r){let n=r.ageMs==null?"\u2014":`${Math.round(r.ageMs/1e3)}s ago`;console.log(`daemon pid ${r.pid} \xB7 v${r.version} \xB7 up ${Ka(Date.now()-r.startedAt)}`),console.log(`heartbeat ${n}${r.supervised?" \xB7 supervised":""}`)}else console.log("daemon no heartbeat (not running)")}var PT,FT=f(()=>{Ll();Pu();PT=`sigil service \u2014 keep Sigil always running
967
967
 
968
968
  Usage:
969
969
  sigil service install Install + start the OS service (always-up)
@@ -974,8 +974,8 @@ Usage:
974
974
  sigil service restart
975
975
 
976
976
  Backend: launchd (macOS) \xB7 systemd --user (Linux) \xB7 Scheduled Task (Windows).
977
- Once installed, Sigil starts at login and is auto-restarted if it crashes.`});function Kl(e){let t={};for(let r=0;r<e.length;r++){let n=e[r];if(!n.startsWith("--"))continue;if(n.includes("=")){let[s,a]=n.slice(2).split(/=(.+)/);t[s]=a;continue}let i=n.slice(2),o=e[r+1];t[i]=o&&!o.startsWith("--")?e[++r]:!0}return t}var gm=f(()=>{});var UT={};A(UT,{runPair:()=>nW});async function nW(e){let[t,...r]=e;if(!t||t==="--help"||t==="-h"){console.log(BT);return}switch(t){case"create":return iW(r);case"list":return oW(r);case"revoke":return sW(r);default:console.error(`Unknown subcommand: pair ${t}
978
- `),console.log(BT),process.exit(1)}}async function iW(e){let t=Kl(e);t.name||(console.error("pair create: --name <device-name> is required"),process.exit(1));let r=await ht();try{let{data:n}=await r.call("pair.create",{name:t.name,role:t.role||"writer",namespaces:t.ns?t.ns.split(",").map(i=>i.trim()).filter(Boolean):[],ttlSeconds:t.ttl?Number(t.ttl):void 0});console.log(`Pairing code created \u2014 share this with "${n.name}":`),console.log(""),console.log(` code: ${n.code}`),console.log(` master nodeId: ${n.masterNodeId||"(iroh not running)"}`),console.log(` role: ${n.role}`),console.log(` namespaces: ${n.namespaces.length?n.namespaces.join(", "):"(all)"}`),console.log(` expires at: ${n.expiresAt}`),console.log(""),console.log("On the joining device, run:"),console.log(` sigil join ${n.masterNodeId||"<master-node-id>"} ${n.code} --name ${n.name}`)}finally{await r.close()}}async function oW(){let e=await ht();try{let{data:t}=await e.call("pair.list",{});if(!t.codes.length){console.log("No pairing codes outstanding.");return}for(let r of t.codes){let n=r.consumedBy?`consumed by ${r.consumedBy.name} (${r.consumedBy.nodeId.slice(0,12)}\u2026)`:r.expired?"EXPIRED":"pending";console.log(`${r.id} ${r.name} ${r.role} ${n} expires=${r.expiresAt}`)}}finally{await e.close()}}async function sW(e){let t=e[0];t||(console.error("pair revoke <id>"),process.exit(1));let r=await ht();try{let{data:n}=await r.call("pair.revoke",{id:Number(t)});console.log(n.deleted?`Revoked pairing code ${t}.`:`No pairing code with id=${t}.`)}finally{await r.close()}}var BT,HT=f(()=>{We();gm();BT=`sigil pair \u2014 create and manage device pairing codes
977
+ Once installed, Sigil starts at login and is auto-restarted if it crashes.`});function Kl(e){let t={};for(let r=0;r<e.length;r++){let n=e[r];if(!n.startsWith("--"))continue;if(n.includes("=")){let[s,a]=n.slice(2).split(/=(.+)/);t[s]=a;continue}let i=n.slice(2),o=e[r+1];t[i]=o&&!o.startsWith("--")?e[++r]:!0}return t}var gm=f(()=>{});var UT={};A(UT,{runPair:()=>iW});async function iW(e){let[t,...r]=e;if(!t||t==="--help"||t==="-h"){console.log(BT);return}switch(t){case"create":return oW(r);case"list":return sW(r);case"revoke":return aW(r);default:console.error(`Unknown subcommand: pair ${t}
978
+ `),console.log(BT),process.exit(1)}}async function oW(e){let t=Kl(e);t.name||(console.error("pair create: --name <device-name> is required"),process.exit(1));let r=await ht();try{let{data:n}=await r.call("pair.create",{name:t.name,role:t.role||"writer",namespaces:t.ns?t.ns.split(",").map(i=>i.trim()).filter(Boolean):[],ttlSeconds:t.ttl?Number(t.ttl):void 0});console.log(`Pairing code created \u2014 share this with "${n.name}":`),console.log(""),console.log(` code: ${n.code}`),console.log(` master nodeId: ${n.masterNodeId||"(iroh not running)"}`),console.log(` role: ${n.role}`),console.log(` namespaces: ${n.namespaces.length?n.namespaces.join(", "):"(all)"}`),console.log(` expires at: ${n.expiresAt}`),console.log(""),console.log("On the joining device, run:"),console.log(` sigil join ${n.masterNodeId||"<master-node-id>"} ${n.code} --name ${n.name}`)}finally{await r.close()}}async function sW(){let e=await ht();try{let{data:t}=await e.call("pair.list",{});if(!t.codes.length){console.log("No pairing codes outstanding.");return}for(let r of t.codes){let n=r.consumedBy?`consumed by ${r.consumedBy.name} (${r.consumedBy.nodeId.slice(0,12)}\u2026)`:r.expired?"EXPIRED":"pending";console.log(`${r.id} ${r.name} ${r.role} ${n} expires=${r.expiresAt}`)}}finally{await e.close()}}async function aW(e){let t=e[0];t||(console.error("pair revoke <id>"),process.exit(1));let r=await ht();try{let{data:n}=await r.call("pair.revoke",{id:Number(t)});console.log(n.deleted?`Revoked pairing code ${t}.`:`No pairing code with id=${t}.`)}finally{await r.close()}}var BT,HT=f(()=>{We();gm();BT=`sigil pair \u2014 create and manage device pairing codes
979
979
 
980
980
  Usage:
981
981
  sigil pair create --name <device-name> [--role <role>] [--ns ns1,ns2] [--ttl <seconds>]
@@ -988,11 +988,11 @@ Roles:
988
988
  admin \u2014 full access including device management
989
989
 
990
990
  The plaintext code is printed once at creation time and never stored.
991
- Hand it to the device you want to pair, along with the master node id.`});var jT={};A(jT,{runJoin:()=>dW});import{hostname as aW}from"node:os";import{readFileSync as cW}from"node:fs";import{join as lW}from"node:path";async function dW(e){if(!e.length||e.includes("--help")||e.includes("-h")){console.log(uW);return}let t=e.filter(d=>!d.startsWith("--"));t.length<2&&(console.error("Usage: sigil join <master-node-id> <pairing-code> [options]"),process.exit(1));let[r,n]=t,i=Kl(e),o=i.name||aW(),s=i.addresses?i.addresses.split(",").map(d=>d.trim()):void 0,a=i.relay||void 0,c=!!i.lite;(process.env.SIGIL_MODE===void 0||process.env.SIGIL_MODE==="solo")&&(process.env.SIGIL_MODE=c?"lite-follower":"follower",process.env.SIGIL_NETWORK_ENABLED="true");let{joinMaster:l}=await Promise.resolve().then(()=>(Ml(),jf)),u=pW();console.log(`[sigil] joining master ${r.slice(0,12)}\u2026`);let p=await l({masterAddr:{nodeId:r,relayUrl:a,addresses:s},code:n,name:o,sigilVersion:u});if(p.ok||(console.error(`Pairing rejected: ${p.error?.code} \u2014 ${p.error?.message}`),process.exit(1)),console.log("\u2713 paired successfully"),console.log(` device id: ${p.device.id}`),console.log(` role: ${p.device.role}`),console.log(` namespaces: ${(p.device.namespaces||[]).join(", ")||"(all)"}`),console.log(` master nodeId: ${p.masterNodeId}`),p.manifest){let{produceManifest:d,verifyManifest:m}=await Promise.resolve().then(()=>(wa(),ya)),h=await d(),g=m(h,p.manifest);if(g.warnings.length){console.log(`
991
+ Hand it to the device you want to pair, along with the master node id.`});var jT={};A(jT,{runJoin:()=>pW});import{hostname as cW}from"node:os";import{readFileSync as lW}from"node:fs";import{join as uW}from"node:path";async function pW(e){if(!e.length||e.includes("--help")||e.includes("-h")){console.log(dW);return}let t=e.filter(d=>!d.startsWith("--"));t.length<2&&(console.error("Usage: sigil join <master-node-id> <pairing-code> [options]"),process.exit(1));let[r,n]=t,i=Kl(e),o=i.name||cW(),s=i.addresses?i.addresses.split(",").map(d=>d.trim()):void 0,a=i.relay||void 0,c=!!i.lite;(process.env.SIGIL_MODE===void 0||process.env.SIGIL_MODE==="solo")&&(process.env.SIGIL_MODE=c?"lite-follower":"follower",process.env.SIGIL_NETWORK_ENABLED="true");let{joinMaster:l}=await Promise.resolve().then(()=>(Ml(),jf)),u=fW();console.log(`[sigil] joining master ${r.slice(0,12)}\u2026`);let p=await l({masterAddr:{nodeId:r,relayUrl:a,addresses:s},code:n,name:o,sigilVersion:u});if(p.ok||(console.error(`Pairing rejected: ${p.error?.code} \u2014 ${p.error?.message}`),process.exit(1)),console.log("\u2713 paired successfully"),console.log(` device id: ${p.device.id}`),console.log(` role: ${p.device.role}`),console.log(` namespaces: ${(p.device.namespaces||[]).join(", ")||"(all)"}`),console.log(` master nodeId: ${p.masterNodeId}`),p.manifest){let{produceManifest:d,verifyManifest:m}=await Promise.resolve().then(()=>(wa(),ya)),h=await d(),g=m(h,p.manifest);if(g.warnings.length){console.log(`
992
992
  Manifest warnings:`);for(let w of g.warnings)console.log(` \u26A0 ${w}`)}if(g.ok)console.log("\u2713 schema manifest matches master");else{console.error(`
993
993
  Manifest errors:`);for(let w of g.errors)console.error(` \u2717 ${w}`);c?(console.error(`
994
994
  Proceeding as lite-follower \u2014 manifest drift OK because lite-follower`),console.error("devices never store facts locally.")):(console.error(`
995
- Follower mode requires a matching manifest. Either align the config on`),console.error("this device (embedding model/dim, chunker, migrations) or join as a"),console.error("lite-follower (which never stores facts locally): retry with --lite"),process.exit(1))}}try{let{connectOrStartDaemon:d}=await Promise.resolve().then(()=>(We(),Rt)),m=await d({quiet:!0});await m.call("writeEnv",{patch:{SIGIL_MODE:c?"lite-follower":"follower",SIGIL_MASTER_NODE_ID:p.masterNodeId,SIGIL_NETWORK_ENABLED:"true"}}),await m.close(),console.log("\u2713 updated ~/.sigil/.env (SIGIL_MODE, SIGIL_MASTER_NODE_ID)")}catch(d){console.error(`(warning: failed to persist mode to .env: ${d.message})`)}}function pW(){try{return JSON.parse(cW(lW(ue,"package.json"),"utf8")).version}catch{return"unknown"}}var uW,GT=f(()=>{K();gm();uW=`sigil join \u2014 pair this device with a Sigil master
995
+ Follower mode requires a matching manifest. Either align the config on`),console.error("this device (embedding model/dim, chunker, migrations) or join as a"),console.error("lite-follower (which never stores facts locally): retry with --lite"),process.exit(1))}}try{let{connectOrStartDaemon:d}=await Promise.resolve().then(()=>(We(),Rt)),m=await d({quiet:!0});await m.call("writeEnv",{patch:{SIGIL_MODE:c?"lite-follower":"follower",SIGIL_MASTER_NODE_ID:p.masterNodeId,SIGIL_NETWORK_ENABLED:"true"}}),await m.close(),console.log("\u2713 updated ~/.sigil/.env (SIGIL_MODE, SIGIL_MASTER_NODE_ID)")}catch(d){console.error(`(warning: failed to persist mode to .env: ${d.message})`)}}function fW(){try{return JSON.parse(lW(uW(ue,"package.json"),"utf8")).version}catch{return"unknown"}}var dW,GT=f(()=>{K();gm();dW=`sigil join \u2014 pair this device with a Sigil master
996
996
 
997
997
  Usage:
998
998
  sigil join <master-node-id> <pairing-code> [--name <name>]
@@ -1001,15 +1001,15 @@ Usage:
1001
1001
  [--lite]
1002
1002
 
1003
1003
  The master prints both the node id and the pairing code when you run
1004
- \`sigil pair create\` on it.`});var YT={};A(YT,{runSetup:()=>mW});import{userInfo as fW}from"node:os";function WT(e,t){let r=e.findIndex(i=>i===`--${t}`||i.startsWith(`--${t}=`));if(r===-1)return;let n=e[r];return n.includes("=")?n.split("=").slice(1).join("="):e[r+1]}async function mW(e=[]){if(e.includes("--help")||e.includes("-h"))return gW();if(!e.includes("--quickstart")){console.log(`${ae.bold("sigil setup")} \u2014 choose a path:
1004
+ \`sigil pair create\` on it.`});var YT={};A(YT,{runSetup:()=>hW});import{userInfo as mW}from"node:os";function WT(e,t){let r=e.findIndex(i=>i===`--${t}`||i.startsWith(`--${t}=`));if(r===-1)return;let n=e[r];return n.includes("=")?n.split("=").slice(1).join("="):e[r+1]}async function hW(e=[]){if(e.includes("--help")||e.includes("-h"))return yW();if(!e.includes("--quickstart")){console.log(`${ae.bold("sigil setup")} \u2014 choose a path:
1005
1005
  `),console.log(` ${ae.bold("sigil setup --quickstart")} ${ae.dim("zero-config: embedded DB + local embedder")}`),console.log(` ${ae.bold("sigil init")} ${ae.dim("interactive wizard (full control)")}`),console.log(` ${ae.bold("sigil")} ${ae.dim("open the web setup wizard in your browser")}
1006
- `);return}return hW(e)}async function hW(e){console.log(`
1006
+ `);return}return gW(e)}async function gW(e){console.log(`
1007
1007
  ${ae.bold("Sigil QuickStart")} ${ae.dim("\u2014 zero-config setup")}
1008
1008
  `);let t=await dr();if(t){qT(`A Sigil daemon is already running (pid ${t}).`),console.log(` ${ae.dim("Embedded mode is single-process. Stop it first:")} ${ae.bold("sigil daemon stop")}
1009
1009
  `),process.exitCode=1;return}Ge("database",{mode:"embedded"});let{runStep:r,detectStep:n,getSetupState:i}=await Promise.resolve().then(()=>(lm(),uT)),o=d=>d?.label&&process.stdout.write(` ${ae.dim(d.label)}\r`),s=await r("database",{mode:"embedded"});if(process.stdout.write("\r\x1B[K"),!s.ok)return ym("Database",s);Aa("Embedded database ready",`${s.result.migrationsRan} migrations \xB7 ${s.result.dataDir}`);let a=await r("llm",{provider:"claude-cli"});process.stdout.write("\r\x1B[K"),a.ok?Aa("LLM provider","Claude Code (no API key)"):VT(`LLM step skipped (${a.error}) \u2014 set one later in the GUI`);let c=WT(e,"embedding-key"),l;if(c)l=await r("embedding",{provider:"openai",apiKey:c});else if((await n("embedding"))?.ollama?.reachable)l=await r("embedding",{provider:"ollama"});else{process.stdout.write("\r\x1B[K"),VT("No embedder configured \u2014 Ollama not reachable and no --embedding-key given."),console.log(` ${ae.dim("Finish with either:")}`),console.log(` ${ae.bold("ollama serve")} ${ae.dim("then re-run")} ${ae.bold("sigil setup --quickstart")}`),console.log(` ${ae.bold("sigil setup --quickstart --embedding-key sk-...")} ${ae.dim("(OpenAI)")}
1010
- `),KT(i());return}if(process.stdout.write("\r\x1B[K"),!l.ok)return ym("Embeddings",l);Aa("Embedder ready",`${l.result.provider}/${l.result.model} \xB7 ${l.result.dim}d`),await r("connectors",{}),Aa("Coding agents","connect them anytime in the dashboard");let u=(WT(e,"name")||fW().username||"").trim(),p=await r("identity",{name:u});if(process.stdout.write("\r\x1B[K"),!p.ok)return ym("Identity",p);Aa("First memory written",`as "${u}" \xB7 full pipeline verified`),console.log(""),KT(i())}function ym(e,t){process.stdout.write("\r\x1B[K"),qT(`${e} failed: ${t.error||JSON.stringify(t.errors)}`),t.hint&&console.log(` ${ae.dim("\u2192 "+t.hint)}`),process.exitCode=1}function KT(e){let t=e.steps.filter(r=>r.status==="done").length;if(e.complete)console.log(`${ae.green(ae.bold("\u2713 Sigil is ready."))} Run ${ae.bold("sigil")} to open the dashboard.
1010
+ `),KT(i());return}if(process.stdout.write("\r\x1B[K"),!l.ok)return ym("Embeddings",l);Aa("Embedder ready",`${l.result.provider}/${l.result.model} \xB7 ${l.result.dim}d`),await r("connectors",{}),Aa("Coding agents","connect them anytime in the dashboard");let u=(WT(e,"name")||mW().username||"").trim(),p=await r("identity",{name:u});if(process.stdout.write("\r\x1B[K"),!p.ok)return ym("Identity",p);Aa("First memory written",`as "${u}" \xB7 full pipeline verified`),console.log(""),KT(i())}function ym(e,t){process.stdout.write("\r\x1B[K"),qT(`${e} failed: ${t.error||JSON.stringify(t.errors)}`),t.hint&&console.log(` ${ae.dim("\u2192 "+t.hint)}`),process.exitCode=1}function KT(e){let t=e.steps.filter(r=>r.status==="done").length;if(e.complete)console.log(`${ae.green(ae.bold("\u2713 Sigil is ready."))} Run ${ae.bold("sigil")} to open the dashboard.
1011
1011
  `);else{let r=e.steps.filter(n=>n.status!=="done").map(n=>n.title);console.log(`${ae.yellow(`${t}/${e.steps.length} steps done.`)} Remaining: ${r.join(", ")}.`),console.log(`Finish in the browser: ${ae.bold("sigil")}
1012
- `)}}function gW(){console.log(`sigil setup \u2014 first-run onboarding
1012
+ `)}}function yW(){console.log(`sigil setup \u2014 first-run onboarding
1013
1013
 
1014
1014
  Usage:
1015
1015
  sigil setup Show the QuickStart vs interactive choice
@@ -1025,57 +1025,57 @@ QuickStart defaults:
1025
1025
 
1026
1026
  Notes:
1027
1027
  Embedded mode is single-process \u2014 stop a running daemon first (sigil daemon stop).
1028
- For full control over every choice, use the interactive wizard: sigil init`)}var ae,Aa,VT,qT,zT=f(()=>{nt();Dn();ae={dim:e=>`\x1B[2m${e}\x1B[0m`,green:e=>`\x1B[32m${e}\x1B[0m`,yellow:e=>`\x1B[33m${e}\x1B[0m`,red:e=>`\x1B[31m${e}\x1B[0m`,bold:e=>`\x1B[1m${e}\x1B[0m`};Aa=(e,t="")=>console.log(` ${ae.green("\u2713")} ${e}${t?ae.dim(` ${t}`):""}`),VT=e=>console.log(` ${ae.yellow("!")} ${e}`),qT=e=>console.log(` ${ae.red("\u2717")} ${e}`)});var JT,ZT,XT,QT=f(()=>{JT=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let r=0;for(e.lastIndex=0;e.test(t);)r+=1;return t.length-r}})(),ZT=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,XT=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141});var yW,wW,eA,_W,tA,bW,xW,EW,rA,nA,iA=f(()=>{QT();yW=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,wW=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,eA=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,_W=/\t{1,1000}/y,tA=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),bW=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,xW=new RegExp("\\p{M}+","gu"),EW={limit:1/0,ellipsis:""},rA=(e,t={},r={})=>{let n=t.limit??1/0,i=t.ellipsis??"",o=t?.ellipsisWidth??(i?rA(i,EW,r).width:0),s=0,a=r.controlWidth??0,c=r.tabWidth??8,l=r.emojiWidth??2,u=2,p=r.regularWidth??1,d=r.wideWidth??u,m=[[bW,p],[yW,s],[wW,a],[_W,c],[tA,l],[eA,d]],h=0,g=0,w=e.length,_=0,E=!1,I=w,$=Math.max(0,n-o),v=0,S=0,L=0,F=0;e:for(;;){if(S>v||g>=w&&g>h){let D=e.slice(v,S)||e.slice(h,g);_=0;for(let J of D.replaceAll(xW,"")){let G=J.codePointAt(0)||0;if(ZT(G)?F=u:XT(G)?F=d:F=p,L+F>$&&(I=Math.min(I,Math.max(v,h)+_)),L+F>n){E=!0;break e}_+=J.length,L+=F}v=S=0}if(g>=w)break e;for(let D=0,J=m.length;D<J;D++){let[G,pe]=m[D];if(G.lastIndex=g,G.test(e)){if(_=G===eA?JT(e.slice(g,G.lastIndex)):G===tA?1:G.lastIndex-g,F=_*pe,L+F>$&&(I=Math.min(I,g+Math.floor(($-L)/pe))),L+F>n){E=!0;break e}L+=F,v=h,S=g,g=h=G.lastIndex;continue e}}g+=1}return{width:E?$:L,index:E?I:w,truncated:E,ellipsed:E&&n>=o}},nA=rA});var vW,SW,Ae,wm=f(()=>{iA();vW={limit:1/0,ellipsis:"",ellipsisWidth:0},SW=(e,t={})=>nA(e,vW,t).width,Ae=SW});function Vt(e,t,r){return String(e).normalize().split(CW).map(n=>$W(n,t,r)).join(`
1029
- `)}var ql,lA,IW,bm,uA,TW,dA,xm,oA,sA,aA,cA,_m,AW,$W,CW,Em=f(()=>{wm();ql="\x1B",lA="\x9B",IW=39,bm="\x07",uA="[",TW="]",dA="m",xm=`${TW}8;;`,oA=new RegExp(`(?:\\${uA}(?<code>\\d+)m|\\${xm}(?<uri>.*)${bm})`,"y"),sA=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},aA=e=>`${ql}${uA}${e}${dA}`,cA=e=>`${ql}${xm}${e}${bm}`,_m=(e,t,r)=>{let n=t[Symbol.iterator](),i=!1,o=!1,s=e.at(-1),a=s===void 0?0:Ae(s),c=n.next(),l=n.next(),u=0;for(;!c.done;){let p=c.value,d=Ae(p);a+d<=r?e[e.length-1]+=p:(e.push(p),a=0),(p===ql||p===lA)&&(i=!0,o=t.startsWith(xm,u+1)),i?o?p===bm&&(i=!1,o=!1):p===dA&&(i=!1):(a+=d,a===r&&!l.done&&(e.push(""),a=0)),c=l,l=n.next(),u+=p.length}s=e.at(-1),!a&&s!==void 0&&s.length&&e.length>1&&(e[e.length-2]+=e.pop())},AW=e=>{let t=e.split(" "),r=t.length;for(;r&&!Ae(t[r-1]);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},$W=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=e.split(" "),a=[""],c=0;for(let p=0;p<s.length;p++){let d=s[p];if(r.trim!==!1){let h=a.at(-1)??"",g=h.trimStart();h.length!==g.length&&(a[a.length-1]=g,c=Ae(g))}p!==0&&(c>=t&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let m=Ae(d);if(r.hard&&m>t){let h=t-c,g=1+Math.floor((m-h-1)/t);Math.floor((m-1)/t)<g&&a.push(""),_m(a,d,t),c=Ae(a.at(-1)??"");continue}if(c+m>t&&c&&m){if(r.wordWrap===!1&&c<t){_m(a,d,t),c=Ae(a.at(-1)??"");continue}a.push(""),c=0}if(c+m>t&&r.wordWrap===!1){_m(a,d,t),c=Ae(a.at(-1)??"");continue}a[a.length-1]+=d,c+=m}r.trim!==!1&&(a=a.map(p=>AW(p)));let l=a.join(`
1030
- `),u=!1;for(let p=0;p<l.length;p++){let d=l[p];if(n+=d,u)u=!1;else if(u=d>="\uD800"&&d<="\uDBFF",u)continue;if(d===ql||d===lA){oA.lastIndex=p+1;let h=oA.exec(l)?.groups;if(h?.code!==void 0){let g=Number.parseFloat(h.code);i=g===IW?void 0:g}else h?.uri!==void 0&&(o=h.uri.length===0?void 0:h.uri)}if(l[p+1]===`
1028
+ For full control over every choice, use the interactive wizard: sigil init`)}var ae,Aa,VT,qT,zT=f(()=>{nt();Dn();ae={dim:e=>`\x1B[2m${e}\x1B[0m`,green:e=>`\x1B[32m${e}\x1B[0m`,yellow:e=>`\x1B[33m${e}\x1B[0m`,red:e=>`\x1B[31m${e}\x1B[0m`,bold:e=>`\x1B[1m${e}\x1B[0m`};Aa=(e,t="")=>console.log(` ${ae.green("\u2713")} ${e}${t?ae.dim(` ${t}`):""}`),VT=e=>console.log(` ${ae.yellow("!")} ${e}`),qT=e=>console.log(` ${ae.red("\u2717")} ${e}`)});var JT,ZT,XT,QT=f(()=>{JT=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let r=0;for(e.lastIndex=0;e.test(t);)r+=1;return t.length-r}})(),ZT=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,XT=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141});var wW,_W,eA,bW,tA,xW,EW,vW,rA,nA,iA=f(()=>{QT();wW=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,_W=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,eA=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,bW=/\t{1,1000}/y,tA=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),xW=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,EW=new RegExp("\\p{M}+","gu"),vW={limit:1/0,ellipsis:""},rA=(e,t={},r={})=>{let n=t.limit??1/0,i=t.ellipsis??"",o=t?.ellipsisWidth??(i?rA(i,vW,r).width:0),s=0,a=r.controlWidth??0,c=r.tabWidth??8,l=r.emojiWidth??2,u=2,p=r.regularWidth??1,d=r.wideWidth??u,m=[[xW,p],[wW,s],[_W,a],[bW,c],[tA,l],[eA,d]],h=0,g=0,w=e.length,_=0,E=!1,I=w,$=Math.max(0,n-o),v=0,S=0,L=0,F=0;e:for(;;){if(S>v||g>=w&&g>h){let D=e.slice(v,S)||e.slice(h,g);_=0;for(let J of D.replaceAll(EW,"")){let G=J.codePointAt(0)||0;if(ZT(G)?F=u:XT(G)?F=d:F=p,L+F>$&&(I=Math.min(I,Math.max(v,h)+_)),L+F>n){E=!0;break e}_+=J.length,L+=F}v=S=0}if(g>=w)break e;for(let D=0,J=m.length;D<J;D++){let[G,pe]=m[D];if(G.lastIndex=g,G.test(e)){if(_=G===eA?JT(e.slice(g,G.lastIndex)):G===tA?1:G.lastIndex-g,F=_*pe,L+F>$&&(I=Math.min(I,g+Math.floor(($-L)/pe))),L+F>n){E=!0;break e}L+=F,v=h,S=g,g=h=G.lastIndex;continue e}}g+=1}return{width:E?$:L,index:E?I:w,truncated:E,ellipsed:E&&n>=o}},nA=rA});var SW,IW,Ae,wm=f(()=>{iA();SW={limit:1/0,ellipsis:"",ellipsisWidth:0},IW=(e,t={})=>nA(e,SW,t).width,Ae=IW});function Vt(e,t,r){return String(e).normalize().split(kW).map(n=>CW(n,t,r)).join(`
1029
+ `)}var ql,lA,TW,bm,uA,AW,dA,xm,oA,sA,aA,cA,_m,$W,CW,kW,Em=f(()=>{wm();ql="\x1B",lA="\x9B",TW=39,bm="\x07",uA="[",AW="]",dA="m",xm=`${AW}8;;`,oA=new RegExp(`(?:\\${uA}(?<code>\\d+)m|\\${xm}(?<uri>.*)${bm})`,"y"),sA=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},aA=e=>`${ql}${uA}${e}${dA}`,cA=e=>`${ql}${xm}${e}${bm}`,_m=(e,t,r)=>{let n=t[Symbol.iterator](),i=!1,o=!1,s=e.at(-1),a=s===void 0?0:Ae(s),c=n.next(),l=n.next(),u=0;for(;!c.done;){let p=c.value,d=Ae(p);a+d<=r?e[e.length-1]+=p:(e.push(p),a=0),(p===ql||p===lA)&&(i=!0,o=t.startsWith(xm,u+1)),i?o?p===bm&&(i=!1,o=!1):p===dA&&(i=!1):(a+=d,a===r&&!l.done&&(e.push(""),a=0)),c=l,l=n.next(),u+=p.length}s=e.at(-1),!a&&s!==void 0&&s.length&&e.length>1&&(e[e.length-2]+=e.pop())},$W=e=>{let t=e.split(" "),r=t.length;for(;r&&!Ae(t[r-1]);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},CW=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=e.split(" "),a=[""],c=0;for(let p=0;p<s.length;p++){let d=s[p];if(r.trim!==!1){let h=a.at(-1)??"",g=h.trimStart();h.length!==g.length&&(a[a.length-1]=g,c=Ae(g))}p!==0&&(c>=t&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let m=Ae(d);if(r.hard&&m>t){let h=t-c,g=1+Math.floor((m-h-1)/t);Math.floor((m-1)/t)<g&&a.push(""),_m(a,d,t),c=Ae(a.at(-1)??"");continue}if(c+m>t&&c&&m){if(r.wordWrap===!1&&c<t){_m(a,d,t),c=Ae(a.at(-1)??"");continue}a.push(""),c=0}if(c+m>t&&r.wordWrap===!1){_m(a,d,t),c=Ae(a.at(-1)??"");continue}a[a.length-1]+=d,c+=m}r.trim!==!1&&(a=a.map(p=>$W(p)));let l=a.join(`
1030
+ `),u=!1;for(let p=0;p<l.length;p++){let d=l[p];if(n+=d,u)u=!1;else if(u=d>="\uD800"&&d<="\uDBFF",u)continue;if(d===ql||d===lA){oA.lastIndex=p+1;let h=oA.exec(l)?.groups;if(h?.code!==void 0){let g=Number.parseFloat(h.code);i=g===TW?void 0:g}else h?.uri!==void 0&&(o=h.uri.length===0?void 0:h.uri)}if(l[p+1]===`
1031
1031
  `){o&&(n+=cA(""));let m=i?sA(i):void 0;i&&m&&(n+=aA(m))}else d===`
1032
- `&&(i&&sA(i)&&(n+=aA(i)),o&&(n+=cA(o)))}return n},CW=/\r?\n/});var Sm=He((Kse,pA)=>{"use strict";var vm={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let r="";return e<0?r+=`\x1B[${-e}D`:e>0&&(r+=`\x1B[${e}C`),t<0?r+=`\x1B[${-t}A`:t>0&&(r+=`\x1B[${t}B`),r},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},kW={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},RW={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let r=0;r<e;r++)t+=this.line+(r<e-1?vm.up():"");return e&&(t+=vm.left),t}};pA.exports={cursor:vm,scroll:kW,erase:RW,beep:"\x07"}});import{styleText as os}from"node:util";import{stdout as $m,stdin as gA}from"node:process";import*as Sn from"node:readline";import OW from"node:readline";import{ReadStream as fA}from"node:tty";function $r(e,t,r){if(!r.some(s=>!s.disabled))return e;let n=e+t,i=Math.max(r.length-1,0),o=n<0?i:n>i?0:n;return r[o].disabled?$r(o,t<0?-1:1,r):o}function Yl(e,t,r,n){let i=n.split(`
1033
- `),o=0,s=e;for(let c of i){if(s<=c.length)break;s-=c.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+r)),s=Math.min(s,i[o].length)+t;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let a=0;for(let c=0;c<o;c++)a+=i[c].length+1;return a+s}function yA(e){if(e.aliases!==void 0){let t=e.aliases;for(let r in t){if(!Object.hasOwn(t,r))continue;let n=t[r];j.actions.has(n)&&(j.aliases.has(r)||j.aliases.set(r,n))}}if(e.messages!==void 0){let t=e.messages;t.cancel!==void 0&&(j.messages.cancel=t.cancel),t.error!==void 0&&(j.messages.error=t.error)}if(e.withGuide!==void 0&&(j.withGuide=e.withGuide!==!1),e.date!==void 0){let t=e.date;t.monthNames!==void 0&&(j.date.monthNames=[...t.monthNames]),t.messages!==void 0&&(t.messages.required!==void 0&&(j.date.messages.required=t.messages.required),t.messages.invalidMonth!==void 0&&(j.date.messages.invalidMonth=t.messages.invalidMonth),t.messages.invalidDay!==void 0&&(j.date.messages.invalidDay=t.messages.invalidDay),t.messages.afterMin!==void 0&&(j.date.messages.afterMin=t.messages.afterMin),t.messages.beforeMax!==void 0&&(j.date.messages.beforeMax=t.messages.beforeMax))}}function Cm(e,t){if(typeof e=="string")return j.aliases.get(e)===t;for(let r of e)if(r!==void 0&&Cm(r,t))return!0;return!1}function LW(e,t){if(e===t)return;let r=e.split(`
1032
+ `&&(i&&sA(i)&&(n+=aA(i)),o&&(n+=cA(o)))}return n},kW=/\r?\n/});var Sm=He((qse,pA)=>{"use strict";var vm={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let r="";return e<0?r+=`\x1B[${-e}D`:e>0&&(r+=`\x1B[${e}C`),t<0?r+=`\x1B[${-t}A`:t>0&&(r+=`\x1B[${t}B`),r},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},RW={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},OW={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let r=0;r<e;r++)t+=this.line+(r<e-1?vm.up():"");return e&&(t+=vm.left),t}};pA.exports={cursor:vm,scroll:RW,erase:OW,beep:"\x07"}});import{styleText as os}from"node:util";import{stdout as $m,stdin as gA}from"node:process";import*as Sn from"node:readline";import NW from"node:readline";import{ReadStream as fA}from"node:tty";function $r(e,t,r){if(!r.some(s=>!s.disabled))return e;let n=e+t,i=Math.max(r.length-1,0),o=n<0?i:n>i?0:n;return r[o].disabled?$r(o,t<0?-1:1,r):o}function Yl(e,t,r,n){let i=n.split(`
1033
+ `),o=0,s=e;for(let c of i){if(s<=c.length)break;s-=c.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+r)),s=Math.min(s,i[o].length)+t;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let a=0;for(let c=0;c<o;c++)a+=i[c].length+1;return a+s}function yA(e){if(e.aliases!==void 0){let t=e.aliases;for(let r in t){if(!Object.hasOwn(t,r))continue;let n=t[r];j.actions.has(n)&&(j.aliases.has(r)||j.aliases.set(r,n))}}if(e.messages!==void 0){let t=e.messages;t.cancel!==void 0&&(j.messages.cancel=t.cancel),t.error!==void 0&&(j.messages.error=t.error)}if(e.withGuide!==void 0&&(j.withGuide=e.withGuide!==!1),e.date!==void 0){let t=e.date;t.monthNames!==void 0&&(j.date.monthNames=[...t.monthNames]),t.messages!==void 0&&(t.messages.required!==void 0&&(j.date.messages.required=t.messages.required),t.messages.invalidMonth!==void 0&&(j.date.messages.invalidMonth=t.messages.invalidMonth),t.messages.invalidDay!==void 0&&(j.date.messages.invalidDay=t.messages.invalidDay),t.messages.afterMin!==void 0&&(j.date.messages.afterMin=t.messages.afterMin),t.messages.beforeMax!==void 0&&(j.date.messages.beforeMax=t.messages.beforeMax))}}function Cm(e,t){if(typeof e=="string")return j.aliases.get(e)===t;for(let r of e)if(r!==void 0&&Cm(r,t))return!0;return!1}function PW(e,t){if(e===t)return;let r=e.split(`
1034
1034
  `),n=t.split(`
1035
- `),i=Math.max(r.length,n.length),o=[];for(let s=0;s<i;s++)r[s]!==n[s]&&o.push(s);return{lines:o,numLinesBefore:r.length,numLinesAfter:n.length,numLines:i}}function ou(e){return e===Tm}function zl(e,t){let r=e;r.isTTY&&r.setRawMode(t)}function wA({input:e=gA,output:t=$m,overwrite:r=!0,hideCursor:n=!0}={}){let i=Sn.createInterface({input:e,output:t,prompt:"",tabSize:1});Sn.emitKeypressEvents(e,i),e instanceof fA&&e.isTTY&&e.setRawMode(!0);let o=(s,{name:a,sequence:c})=>{let l=String(s);if(Cm([l,a,c],"cancel")){n&&t.write(Be.cursor.show),process.exit(0);return}if(!r)return;Sn.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{Sn.clearLine(t,1,()=>{e.once("keypress",o)})})};return n&&t.write(Be.cursor.hide),e.once("keypress",o),()=>{e.off("keypress",o),n&&t.write(Be.cursor.show),e instanceof fA&&e.isTTY&&!PW&&e.setRawMode(!1),i.terminal=!1,i.close()}}function Ie(e,t,r,n=r,i=r,o){let s=ki(e??$m);return Vt(t,s-r.length,{hard:!0,trim:!1}).split(`
1035
+ `),i=Math.max(r.length,n.length),o=[];for(let s=0;s<i;s++)r[s]!==n[s]&&o.push(s);return{lines:o,numLinesBefore:r.length,numLinesAfter:n.length,numLines:i}}function ou(e){return e===Tm}function zl(e,t){let r=e;r.isTTY&&r.setRawMode(t)}function wA({input:e=gA,output:t=$m,overwrite:r=!0,hideCursor:n=!0}={}){let i=Sn.createInterface({input:e,output:t,prompt:"",tabSize:1});Sn.emitKeypressEvents(e,i),e instanceof fA&&e.isTTY&&e.setRawMode(!0);let o=(s,{name:a,sequence:c})=>{let l=String(s);if(Cm([l,a,c],"cancel")){n&&t.write(Be.cursor.show),process.exit(0);return}if(!r)return;Sn.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{Sn.clearLine(t,1,()=>{e.once("keypress",o)})})};return n&&t.write(Be.cursor.hide),e.once("keypress",o),()=>{e.off("keypress",o),n&&t.write(Be.cursor.show),e instanceof fA&&e.isTTY&&!MW&&e.setRawMode(!1),i.terminal=!1,i.close()}}function Ie(e,t,r,n=r,i=r,o){let s=ki(e??$m);return Vt(t,s-r.length,{hard:!0,trim:!1}).split(`
1036
1036
  `).map((a,c,l)=>{let u=o?o(a,c):a;return c===0?`${n}${u}`:c===l.length-1?`${i}${u}`:`${r}${u}`}).join(`
1037
- `)}function MW(e,t){if(e===void 0||t.length===0)return 0;let r=t.findIndex(n=>n.value===e);return r!==-1?r:0}function FW(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function BW(e,t){if(t)return e?t:t[0]}function mA(e){return[...e].map(t=>UW[t])}function HW(e){let t=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2e3,0,15)),r=[],n="/";for(let i of t)i.type==="literal"?n=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&r.push({type:i.type,len:i.type==="year"?4:2});return{segments:r,separator:n}}function Im(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Jl(e){return{year:Im(e.year),month:Im(e.month),day:Im(e.day)}}function Am(e,t){return new Date(e||2001,t||1,0).getDate()}function _A(e){let{year:t,month:r,day:n}=Jl(e);if(!t||t<0||t>9999||!r||r<1||r>12||!n||n<1)return;let i=new Date(Date.UTC(t,r-1,n));if(!(i.getUTCFullYear()!==t||i.getUTCMonth()!==r-1||i.getUTCDate()!==n))return{year:t,month:r,day:n}}function hA(e){let t=_A(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function jW(e,t,r,n){let i=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null,o=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:o?.year??9999}:e==="month"?{min:i&&t.year===i.year?i.month:1,max:o&&t.year===o.year?o.month:12}:{min:i&&t.year===i.year&&t.month===i.month?i.day:1,max:o&&t.year===o.year&&t.month===o.month?o.day:Am(t.year,t.month)}}var Be,NW,DW,j,PW,Tm,ki,km,sr,Rm,Zl,UW,Xl,Ql,eu,bA,tu,ru,nu,iu,Om=f(()=>{Em();Be=yu(Sm(),1);NW=["up","down","left","right","space","enter","cancel"],DW=["January","February","March","April","May","June","July","August","September","October","November","December"],j={actions:new Set(NW),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...DW],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:e=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:e=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};PW=globalThis.process.platform.startsWith("win"),Tm=Symbol("clack:cancel");ki=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,km=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;sr=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:r=gA,output:n=$m,render:i,signal:o,...s}=e;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=o,this.input=r,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let r=this._subscribers.get(e)??[];r.push(t),this._subscribers.set(e,r)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let r=this._subscribers.get(e)??[],n=[];for(let i of r)i.cb(...t),i.once&&n.push(()=>r.splice(r.indexOf(i),1));for(let i of n)i()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Tm);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=OW.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),zl(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Be.cursor.show),this.output.off("resize",this.render),zl(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(Be.cursor.show),this.output.off("resize",this.render),zl(this.input,!1),e(Tm)})})}_isActionKey(e,t){return e===" "}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),t?.name&&(!this._track&&j.aliases.has(t.name)&&this.emit("cursor",j.aliases.get(t.name)),j.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e?.toLowerCase(),t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let r=this.opts.validate(this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Cm([e,t?.name,t?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
1037
+ `)}function FW(e,t){if(e===void 0||t.length===0)return 0;let r=t.findIndex(n=>n.value===e);return r!==-1?r:0}function BW(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function UW(e,t){if(t)return e?t:t[0]}function mA(e){return[...e].map(t=>HW[t])}function jW(e){let t=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2e3,0,15)),r=[],n="/";for(let i of t)i.type==="literal"?n=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&r.push({type:i.type,len:i.type==="year"?4:2});return{segments:r,separator:n}}function Im(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Jl(e){return{year:Im(e.year),month:Im(e.month),day:Im(e.day)}}function Am(e,t){return new Date(e||2001,t||1,0).getDate()}function _A(e){let{year:t,month:r,day:n}=Jl(e);if(!t||t<0||t>9999||!r||r<1||r>12||!n||n<1)return;let i=new Date(Date.UTC(t,r-1,n));if(!(i.getUTCFullYear()!==t||i.getUTCMonth()!==r-1||i.getUTCDate()!==n))return{year:t,month:r,day:n}}function hA(e){let t=_A(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function GW(e,t,r,n){let i=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null,o=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:o?.year??9999}:e==="month"?{min:i&&t.year===i.year?i.month:1,max:o&&t.year===o.year?o.month:12}:{min:i&&t.year===i.year&&t.month===i.month?i.day:1,max:o&&t.year===o.year&&t.month===o.month?o.day:Am(t.year,t.month)}}var Be,DW,LW,j,MW,Tm,ki,km,sr,Rm,Zl,HW,Xl,Ql,eu,bA,tu,ru,nu,iu,Om=f(()=>{Em();Be=yu(Sm(),1);DW=["up","down","left","right","space","enter","cancel"],LW=["January","February","March","April","May","June","July","August","September","October","November","December"],j={actions:new Set(DW),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...LW],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:e=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:e=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};MW=globalThis.process.platform.startsWith("win"),Tm=Symbol("clack:cancel");ki=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,km=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;sr=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:r=gA,output:n=$m,render:i,signal:o,...s}=e;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=o,this.input=r,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let r=this._subscribers.get(e)??[];r.push(t),this._subscribers.set(e,r)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let r=this._subscribers.get(e)??[],n=[];for(let i of r)i.cb(...t),i.once&&n.push(()=>r.splice(r.indexOf(i),1));for(let i of n)i()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Tm);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=NW.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),zl(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Be.cursor.show),this.output.off("resize",this.render),zl(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(Be.cursor.show),this.output.off("resize",this.render),zl(this.input,!1),e(Tm)})})}_isActionKey(e,t){return e===" "}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),t?.name&&(!this._track&&j.aliases.has(t.name)&&this.emit("cursor",j.aliases.get(t.name)),j.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e?.toLowerCase(),t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let r=this.opts.validate(this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Cm([e,t?.name,t?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
1038
1038
  `),zl(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Vt(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
1039
- `).length-1;this.output.write(Be.cursor.move(-999,e*-1))}render(){let e=Vt(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(Be.cursor.hide);else{let t=LW(this._prevFrame,e),r=km(this.output);if(this.restoreCursor(),t){let n=Math.max(0,t.numLinesAfter-r),i=Math.max(0,t.numLinesBefore-r),o=t.lines.find(s=>s>=n);if(o===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(Be.cursor.move(0,o-i)),this.output.write(Be.erase.lines(1));let s=e.split(`
1039
+ `).length-1;this.output.write(Be.cursor.move(-999,e*-1))}render(){let e=Vt(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(Be.cursor.hide);else{let t=PW(this._prevFrame,e),r=km(this.output);if(this.restoreCursor(),t){let n=Math.max(0,t.numLinesAfter-r),i=Math.max(0,t.numLinesBefore-r),o=t.lines.find(s=>s>=n);if(o===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(Be.cursor.move(0,o-i)),this.output.write(Be.erase.lines(1));let s=e.split(`
1040
1040
  `);this.output.write(s[o]),this._prevFrame=e,this.output.write(Be.cursor.move(0,s.length-o-1));return}else if(t.lines.length>1){if(n<i)o=n;else{let a=o-i;a>0&&this.output.write(Be.cursor.move(0,a))}this.output.write(Be.erase.down());let s=e.split(`
1041
1041
  `).slice(o);this.output.write(s.join(`
1042
- `)),this._prevFrame=e;return}}this.output.write(Be.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};Rm=class extends sr{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#o;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return os(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let e=this.userInput.slice(0,this._cursor),[t,...r]=this.userInput.slice(this._cursor);return`${e}${os("inverse",t)}${r.join("")}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(e){super(e),this.#o=e.options,this.#a=e.placeholder;let t=this.options;this.filteredOptions=[...t],this.multiple=e.multiple===!0,this.#e=typeof e.options=="function"?e.filter:e.filter??FW;let r;if(e.initialValue&&Array.isArray(e.initialValue)?this.multiple?r=e.initialValue:r=e.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0].value]),r)for(let n of r){let i=t.findIndex(o=>o.value===n);i!==-1&&(this.toggleSelected(n),this.#t=i)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(n,i)=>this.#r(n,i)),this.on("userInput",n=>this.#i(n))}_isActionKey(e,t){return e===" "||this.multiple&&this.isNavigating&&t.name==="space"&&e!==void 0&&e!==""}#r(e,t){let r=t.name==="up",n=t.name==="down",i=t.name==="return",o=this.userInput===""||this.userInput===" ",s=this.#a,a=this.options,c=s!==void 0&&s!==""&&a.some(l=>!l.disabled&&(this.#e?this.#e(s,l):!0));if(t.name==="tab"&&o&&c){this.userInput===" "&&this._clearUserInput(),this._setUserInput(s,!0),this.isNavigating=!1;return}r||n?(this.#t=$r(this.#t,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):i?this.value=BW(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(t.name==="tab"||this.isNavigating&&t.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(e){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(e)?this.selectedValues=this.selectedValues.filter(t=>t!==e):this.selectedValues=[...this.selectedValues,e]:this.selectedValues=[e])}#i(e){if(e!==this.#n){this.#n=e;let t=this.options;e&&this.#e?this.filteredOptions=t.filter(i=>this.#e?.(e,i)):this.filteredOptions=[...t];let r=MW(this.focusedValue,this.filteredOptions);this.#t=$r(r,0,this.filteredOptions);let n=this.filteredOptions[this.#t];n&&!n.disabled?this.focusedValue=n.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}},Zl=class extends sr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",r=>{this.output.write(Be.cursor.move(0,-1)),this.value=r,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},UW={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};Xl=class extends sr{#t;#n;#e;#o;#a;#r={segmentIndex:0,positionInSegment:0};#i=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#n}get formattedValue(){return this.#d(this.#e)}#d(t){return this.#t.map(r=>t[r.type]).join(this.#n)}#c(){this._setUserInput(this.#d(this.#e)),this._setValue(hA(this.#e)??void 0)}constructor(t){let r=t.format?{segments:mA(t.format),separator:t.separator??"/"}:HW(t.locale),n=t.separator??r.separator,i=t.format?mA(t.format):r.segments,o=t.initialValue??t.defaultValue,s=o?{year:String(o.getUTCFullYear()).padStart(4,"0"),month:String(o.getUTCMonth()+1).padStart(2,"0"),day:String(o.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},a=i.map(c=>s[c.type]).join(n);super({...t,initialUserInput:a},!1),this.#t=i,this.#n=n,this.#e=s,this.#o=t.minDate,this.#a=t.maxDate,this.#c(),this.on("cursor",c=>this.#m(c)),this.on("key",(c,l)=>this.#h(c,l)),this.on("finalize",()=>this.#g(t))}#l(){let t=Math.max(0,Math.min(this.#r.segmentIndex,this.#t.length-1)),r=this.#t[t];if(r)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,r.len-1)),{segment:r,index:t}}#u(t){this.inlineError="",this.#s=null;let r=this.#l();r&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#t.length-1,r.index+t)),this.#r.positionInSegment=0,this.#i=!0)}#p(t){let r=this.#l();if(!r)return;let{segment:n}=r,i=this.#e[n.type],o=!i||i.replace(/_/g,"")==="",s=Number.parseInt((i||"0").replace(/_/g,"0"),10)||0,a=jW(n.type,Jl(this.#e),this.#o,this.#a),c;o?c=t===1?a.min:a.max:c=Math.max(Math.min(a.max,s+t),a.min),this.#e={...this.#e,[n.type]:c.toString().padStart(n.len,"0")},this.#i=!0,this.#s=null,this.#c()}#m(t){if(t)switch(t){case"right":return this.#u(1);case"left":return this.#u(-1);case"up":return this.#p(1);case"down":return this.#p(-1)}}#h(t,r){if(r?.name==="backspace"||r?.sequence==="\x7F"||r?.sequence==="\b"||t==="\x7F"||t==="\b"){this.inlineError="";let n=this.#l();if(!n)return;if(!this.#e[n.segment.type].replace(/_/g,"")){this.#u(-1);return}this.#e[n.segment.type]="_".repeat(n.segment.len),this.#i=!0,this.#r.positionInSegment=0,this.#c();return}if(r?.name==="tab"){this.inlineError="";let n=this.#l();if(!n)return;let i=r.shift?-1:1,o=n.index+i;o>=0&&o<this.#t.length&&(this.#r.segmentIndex=o,this.#r.positionInSegment=0,this.#i=!0);return}if(t&&/^[0-9]$/.test(t)){let n=this.#l();if(!n)return;let{segment:i}=n,o=!this.#e[i.type].replace(/_/g,"");if(this.#i&&this.#s!==null&&!o){let m=this.#s+t,h={...this.#e,[i.type]:m},g=this.#f(h,i);if(g){this.inlineError=g,this.#s=null,this.#i=!1;return}this.inlineError="",this.#e[i.type]=m,this.#s=null,this.#i=!1,this.#c(),n.index<this.#t.length-1&&(this.#r.segmentIndex=n.index+1,this.#r.positionInSegment=0,this.#i=!0);return}this.#i&&!o&&(this.#e[i.type]="_".repeat(i.len),this.#r.positionInSegment=0),this.#i=!1,this.#s=null;let s=this.#e[i.type],a=s.indexOf("_"),c=a>=0?a:Math.min(this.#r.positionInSegment,i.len-1);if(c<0||c>=i.len)return;let l=s.slice(0,c)+t+s.slice(c+1),u=!1;if(c===0&&s==="__"&&(i.type==="month"||i.type==="day")){let m=Number.parseInt(t,10);l=`0${t}`,u=m<=(i.type==="month"?1:2)}if(i.type==="year"&&(l=(s.replace(/_/g,"")+t).padStart(i.len,"_")),!l.includes("_")){let m={...this.#e,[i.type]:l},h=this.#f(m,i);if(h){this.inlineError=h;return}}this.inlineError="",this.#e[i.type]=l;let p=l.includes("_")?void 0:_A(this.#e);if(p){let{year:m,month:h}=p,g=Am(m,h);this.#e={year:String(Math.max(0,Math.min(9999,m))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,h))).padStart(2,"0"),day:String(Math.max(1,Math.min(g,p.day))).padStart(2,"0")}}this.#c();let d=l.indexOf("_");u?(this.#i=!0,this.#s=t):d>=0?this.#r.positionInSegment=d:a>=0&&n.index<this.#t.length-1?(this.#r.segmentIndex=n.index+1,this.#r.positionInSegment=0,this.#i=!0):this.#r.positionInSegment=Math.min(c+1,i.len-1)}}#f(t,r){let{month:n,day:i}=Jl(t);if(r.type==="month"&&(n<0||n>12))return j.date.messages.invalidMonth;if(r.type==="day"&&(i<0||i>31))return j.date.messages.invalidDay(31,"any month")}#g(t){let{year:r,month:n,day:i}=Jl(this.#e);if(r&&n&&i){let o=Am(r,n);this.#e={...this.#e,day:String(Math.min(i,o)).padStart(2,"0")}}this.value=hA(this.#e)??t.defaultValue??void 0}},Ql=class extends sr{options;cursor=0;#t;getGroupItems(t){return this.options.filter(r=>r.group===t)}isGroupSelected(t){let r=this.getGroupItems(t),n=this.value;return n===void 0?!1:r.every(i=>n.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),t.group===!0){let r=t.value,n=this.getGroupItems(r);this.isGroupSelected(r)?this.value=this.value.filter(i=>n.findIndex(o=>o.value===i)===-1):this.value=[...this.value,...n.map(i=>i.value)],this.value=Array.from(new Set(this.value))}else{let r=this.value.includes(t.value);this.value=r?this.value.filter(n=>n!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:r}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(r).flatMap(([n,i])=>[{value:n,group:!0,label:n},...i.map(o=>({...o,group:n}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:n})=>n===t.cursorAt),this.#t?0:1),this.on("cursor",n=>{switch(n){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},eu=class extends sr{#t=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${t}\u2588`;let r=t.slice(0,this.cursor),n=t[this.cursor],i=t.slice(this.cursor+1);return n===`
1042
+ `)),this._prevFrame=e;return}}this.output.write(Be.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};Rm=class extends sr{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#o;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return os(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let e=this.userInput.slice(0,this._cursor),[t,...r]=this.userInput.slice(this._cursor);return`${e}${os("inverse",t)}${r.join("")}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(e){super(e),this.#o=e.options,this.#a=e.placeholder;let t=this.options;this.filteredOptions=[...t],this.multiple=e.multiple===!0,this.#e=typeof e.options=="function"?e.filter:e.filter??BW;let r;if(e.initialValue&&Array.isArray(e.initialValue)?this.multiple?r=e.initialValue:r=e.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0].value]),r)for(let n of r){let i=t.findIndex(o=>o.value===n);i!==-1&&(this.toggleSelected(n),this.#t=i)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(n,i)=>this.#r(n,i)),this.on("userInput",n=>this.#i(n))}_isActionKey(e,t){return e===" "||this.multiple&&this.isNavigating&&t.name==="space"&&e!==void 0&&e!==""}#r(e,t){let r=t.name==="up",n=t.name==="down",i=t.name==="return",o=this.userInput===""||this.userInput===" ",s=this.#a,a=this.options,c=s!==void 0&&s!==""&&a.some(l=>!l.disabled&&(this.#e?this.#e(s,l):!0));if(t.name==="tab"&&o&&c){this.userInput===" "&&this._clearUserInput(),this._setUserInput(s,!0),this.isNavigating=!1;return}r||n?(this.#t=$r(this.#t,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):i?this.value=UW(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(t.name==="tab"||this.isNavigating&&t.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(e){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(e)?this.selectedValues=this.selectedValues.filter(t=>t!==e):this.selectedValues=[...this.selectedValues,e]:this.selectedValues=[e])}#i(e){if(e!==this.#n){this.#n=e;let t=this.options;e&&this.#e?this.filteredOptions=t.filter(i=>this.#e?.(e,i)):this.filteredOptions=[...t];let r=FW(this.focusedValue,this.filteredOptions);this.#t=$r(r,0,this.filteredOptions);let n=this.filteredOptions[this.#t];n&&!n.disabled?this.focusedValue=n.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}},Zl=class extends sr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",r=>{this.output.write(Be.cursor.move(0,-1)),this.value=r,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},HW={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};Xl=class extends sr{#t;#n;#e;#o;#a;#r={segmentIndex:0,positionInSegment:0};#i=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#n}get formattedValue(){return this.#d(this.#e)}#d(t){return this.#t.map(r=>t[r.type]).join(this.#n)}#c(){this._setUserInput(this.#d(this.#e)),this._setValue(hA(this.#e)??void 0)}constructor(t){let r=t.format?{segments:mA(t.format),separator:t.separator??"/"}:jW(t.locale),n=t.separator??r.separator,i=t.format?mA(t.format):r.segments,o=t.initialValue??t.defaultValue,s=o?{year:String(o.getUTCFullYear()).padStart(4,"0"),month:String(o.getUTCMonth()+1).padStart(2,"0"),day:String(o.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},a=i.map(c=>s[c.type]).join(n);super({...t,initialUserInput:a},!1),this.#t=i,this.#n=n,this.#e=s,this.#o=t.minDate,this.#a=t.maxDate,this.#c(),this.on("cursor",c=>this.#m(c)),this.on("key",(c,l)=>this.#h(c,l)),this.on("finalize",()=>this.#g(t))}#l(){let t=Math.max(0,Math.min(this.#r.segmentIndex,this.#t.length-1)),r=this.#t[t];if(r)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,r.len-1)),{segment:r,index:t}}#u(t){this.inlineError="",this.#s=null;let r=this.#l();r&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#t.length-1,r.index+t)),this.#r.positionInSegment=0,this.#i=!0)}#p(t){let r=this.#l();if(!r)return;let{segment:n}=r,i=this.#e[n.type],o=!i||i.replace(/_/g,"")==="",s=Number.parseInt((i||"0").replace(/_/g,"0"),10)||0,a=GW(n.type,Jl(this.#e),this.#o,this.#a),c;o?c=t===1?a.min:a.max:c=Math.max(Math.min(a.max,s+t),a.min),this.#e={...this.#e,[n.type]:c.toString().padStart(n.len,"0")},this.#i=!0,this.#s=null,this.#c()}#m(t){if(t)switch(t){case"right":return this.#u(1);case"left":return this.#u(-1);case"up":return this.#p(1);case"down":return this.#p(-1)}}#h(t,r){if(r?.name==="backspace"||r?.sequence==="\x7F"||r?.sequence==="\b"||t==="\x7F"||t==="\b"){this.inlineError="";let n=this.#l();if(!n)return;if(!this.#e[n.segment.type].replace(/_/g,"")){this.#u(-1);return}this.#e[n.segment.type]="_".repeat(n.segment.len),this.#i=!0,this.#r.positionInSegment=0,this.#c();return}if(r?.name==="tab"){this.inlineError="";let n=this.#l();if(!n)return;let i=r.shift?-1:1,o=n.index+i;o>=0&&o<this.#t.length&&(this.#r.segmentIndex=o,this.#r.positionInSegment=0,this.#i=!0);return}if(t&&/^[0-9]$/.test(t)){let n=this.#l();if(!n)return;let{segment:i}=n,o=!this.#e[i.type].replace(/_/g,"");if(this.#i&&this.#s!==null&&!o){let m=this.#s+t,h={...this.#e,[i.type]:m},g=this.#f(h,i);if(g){this.inlineError=g,this.#s=null,this.#i=!1;return}this.inlineError="",this.#e[i.type]=m,this.#s=null,this.#i=!1,this.#c(),n.index<this.#t.length-1&&(this.#r.segmentIndex=n.index+1,this.#r.positionInSegment=0,this.#i=!0);return}this.#i&&!o&&(this.#e[i.type]="_".repeat(i.len),this.#r.positionInSegment=0),this.#i=!1,this.#s=null;let s=this.#e[i.type],a=s.indexOf("_"),c=a>=0?a:Math.min(this.#r.positionInSegment,i.len-1);if(c<0||c>=i.len)return;let l=s.slice(0,c)+t+s.slice(c+1),u=!1;if(c===0&&s==="__"&&(i.type==="month"||i.type==="day")){let m=Number.parseInt(t,10);l=`0${t}`,u=m<=(i.type==="month"?1:2)}if(i.type==="year"&&(l=(s.replace(/_/g,"")+t).padStart(i.len,"_")),!l.includes("_")){let m={...this.#e,[i.type]:l},h=this.#f(m,i);if(h){this.inlineError=h;return}}this.inlineError="",this.#e[i.type]=l;let p=l.includes("_")?void 0:_A(this.#e);if(p){let{year:m,month:h}=p,g=Am(m,h);this.#e={year:String(Math.max(0,Math.min(9999,m))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,h))).padStart(2,"0"),day:String(Math.max(1,Math.min(g,p.day))).padStart(2,"0")}}this.#c();let d=l.indexOf("_");u?(this.#i=!0,this.#s=t):d>=0?this.#r.positionInSegment=d:a>=0&&n.index<this.#t.length-1?(this.#r.segmentIndex=n.index+1,this.#r.positionInSegment=0,this.#i=!0):this.#r.positionInSegment=Math.min(c+1,i.len-1)}}#f(t,r){let{month:n,day:i}=Jl(t);if(r.type==="month"&&(n<0||n>12))return j.date.messages.invalidMonth;if(r.type==="day"&&(i<0||i>31))return j.date.messages.invalidDay(31,"any month")}#g(t){let{year:r,month:n,day:i}=Jl(this.#e);if(r&&n&&i){let o=Am(r,n);this.#e={...this.#e,day:String(Math.min(i,o)).padStart(2,"0")}}this.value=hA(this.#e)??t.defaultValue??void 0}},Ql=class extends sr{options;cursor=0;#t;getGroupItems(t){return this.options.filter(r=>r.group===t)}isGroupSelected(t){let r=this.getGroupItems(t),n=this.value;return n===void 0?!1:r.every(i=>n.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),t.group===!0){let r=t.value,n=this.getGroupItems(r);this.isGroupSelected(r)?this.value=this.value.filter(i=>n.findIndex(o=>o.value===i)===-1):this.value=[...this.value,...n.map(i=>i.value)],this.value=Array.from(new Set(this.value))}else{let r=this.value.includes(t.value);this.value=r?this.value.filter(n=>n!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:r}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(r).flatMap(([n,i])=>[{value:n,group:!0,label:n},...i.map(o=>({...o,group:n}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:n})=>n===t.cursorAt),this.#t?0:1),this.on("cursor",n=>{switch(n){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},eu=class extends sr{#t=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${t}\u2588`;let r=t.slice(0,this.cursor),n=t[this.cursor],i=t.slice(this.cursor+1);return n===`
1043
1043
  `?`${r}\u2588
1044
1044
  ${i}`:`${r}${os("inverse",n)}${i}`}get cursor(){return this._cursor}#e(t){if(this.userInput.length===0){this._setUserInput(t);return}this._setUserInput(this.userInput.slice(0,this.cursor)+t+this.userInput.slice(this.cursor))}#o(t){let r=this.value??"";switch(t){case"up":this._cursor=Yl(this._cursor,0,-1,r);return;case"down":this._cursor=Yl(this._cursor,0,1,r);return;case"left":this._cursor=Yl(this._cursor,-1,0,r);return;case"right":this._cursor=Yl(this._cursor,1,0,r);return}}_shouldSubmit(t,r){if(this.#n)return this.focused==="submit"?!0:(this.#e(`
1045
1045
  `),this._cursor++,!1);let n=this.#t;return this.#t=!0,n?(this.userInput[this.cursor-1]===`
1046
1046
  `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#e(`
1047
- `),this._cursor++,!1)}constructor(t){super(t,!1),this.#n=t.showSubmit??!1,this.on("key",(r,n)=>{if(n?.name&&j.actions.has(n.name)){this.#o(n.name);return}if(r===" "&&this.#n){this.focused=this.focused==="editor"?"submit":"editor";return}if(n?.name!=="return"){if(this.#t=!1,n?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(n?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}r&&(this.#n&&this.focused==="submit"&&(this.focused="editor"),this.#e(r??""),this._cursor++)}}),this.on("userInput",r=>{this._setValue(r)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}},bA=class extends sr{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map(r=>r.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter(r=>!e.includes(r.value));this.value=t.map(r=>r.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(t=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:r})=>r===e.cursorAt),0);this.cursor=this.options[t].disabled?$r(t,1,this.options):t,this.on("key",r=>{r==="a"&&this.toggleAll(),r==="i"&&this.toggleInvert()}),this.on("cursor",r=>{switch(r){case"left":case"up":this.cursor=$r(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=$r(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},tu=class extends sr{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t=this.userInput;if(this.cursor>=t.length)return`${this.masked}${os(["inverse","hidden"],"_")}`;let r=this.masked,n=r.slice(0,this.cursor),i=r.slice(this.cursor);return`${n}${os("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t,...r}){super(r),this._mask=t??"\u2022",this.on("userInput",n=>{this._setValue(n)})}},ru=class extends sr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t){super(t,!1),this.options=t.options;let r=this.options.findIndex(({value:i})=>i===t.initialValue),n=r===-1?0:r;this.cursor=this.options[n].disabled?$r(n,1,this.options):n,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=$r(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=$r(this.cursor,1,this.options);break}this.changeValue()})}},nu=class extends sr{options;cursor=0;constructor(t){super(t,!1),this.options=t.options;let r=t.caseSensitive===!0,n=this.options.map(({value:[i]})=>r?i:i?.toLowerCase());this.cursor=Math.max(n.indexOf(t.initialValue),0),this.on("key",(i,o)=>{if(!i)return;let s=r&&o.shift?i.toUpperCase():i;if(!n.includes(s))return;let a=this.options.find(({value:[c]})=>r?c===s:c?.toLowerCase()===i);a&&(this.value=a.value,this.state="submit",this.emit("submit"))})}},iu=class extends sr{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let r=t.slice(0,this.cursor),[n,...i]=t.slice(this.cursor);return`${r}${os("inverse",n)}${i.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",r=>{this._setValue(r)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}});var ka={};A(ka,{S_BAR:()=>C,S_BAR_END:()=>ve,S_BAR_END_RIGHT:()=>RA,S_BAR_H:()=>lu,S_BAR_START:()=>Mm,S_BAR_START_RIGHT:()=>kA,S_CHECKBOX_ACTIVE:()=>cu,S_CHECKBOX_INACTIVE:()=>as,S_CHECKBOX_SELECTED:()=>Oi,S_CONNECT_LEFT:()=>NA,S_CORNER_BOTTOM_LEFT:()=>Um,S_CORNER_BOTTOM_RIGHT:()=>Bm,S_CORNER_TOP_LEFT:()=>DA,S_CORNER_TOP_RIGHT:()=>Fm,S_ERROR:()=>Wm,S_INFO:()=>Hm,S_PASSWORD_MASK:()=>OA,S_RADIO_ACTIVE:()=>Ca,S_RADIO_INACTIVE:()=>Ni,S_STEP_ACTIVE:()=>CA,S_STEP_CANCEL:()=>Lm,S_STEP_ERROR:()=>Pm,S_STEP_SUBMIT:()=>Di,S_SUCCESS:()=>jm,S_WARN:()=>Gm,autocomplete:()=>PA,autocompleteMultiselect:()=>YW,box:()=>XW,cancel:()=>sV,confirm:()=>QW,date:()=>eV,group:()=>iV,groupMultiselect:()=>oV,intro:()=>aV,isCI:()=>Dm,isCancel:()=>ou,isTTY:()=>$A,limitOptions:()=>In,log:()=>pt,multiline:()=>lV,multiselect:()=>uV,note:()=>fV,outro:()=>cV,password:()=>mV,path:()=>hV,progress:()=>yV,select:()=>wV,selectKey:()=>_V,settings:()=>j,spinner:()=>Km,stream:()=>Ri,symbol:()=>ft,symbolBar:()=>Vm,taskLog:()=>EV,tasks:()=>bV,text:()=>vV,unicode:()=>au,unicodeOr:()=>ne,updateSettings:()=>yA});import{styleText as y,stripVTControlCharacters as Nm}from"node:util";import Ct from"node:process";import{existsSync as GW,lstatSync as xA,readdirSync as WW}from"node:fs";import{dirname as EA,join as VW}from"node:path";function KW(){return Ct.platform!=="win32"?Ct.env.TERM!=="linux":!!Ct.env.CI||!!Ct.env.WT_SESSION||!!Ct.env.TERMINUS_SUBLIME||Ct.env.ConEmuTask==="{cmd::Cmder}"||Ct.env.TERM_PROGRAM==="Terminus-Sublime"||Ct.env.TERM_PROGRAM==="vscode"||Ct.env.TERM==="xterm-256color"||Ct.env.TERM==="alacritty"||Ct.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function SA(e){return e.label??String(e.value??"")}function LA(e,t){if(!e)return!0;let r=(t.label??String(t.value??"")).toLowerCase(),n=(t.hint??"").toLowerCase(),i=String(t.value).toLowerCase(),o=e.toLowerCase();return r.includes(o)||n.includes(o)||i.includes(o)}function qW(e,t){let r=[];for(let n of t)e.includes(n.value)&&r.push(n);return r}function IA(e,t,r,n){let i=r,o=r;return n==="center"?i=Math.floor((t-e)/2):n==="right"&&(i=t-e-r),o=t-i-e,[i,o]}function tV(e,t){let r=e.segmentValues,n=e.segmentCursor;if(t==="submit"||t==="cancel")return e.formattedValue;let i=y("gray",e.separator);return e.segments.map((o,s)=>{let a=s===n.segmentIndex&&!["submit","cancel"].includes(t),c=nV[o.type];return rV(r[o.type],{isActive:a,label:c})}).join(i)}function rV(e,t){let r=!e||e.replace(/_/g,"")==="";return t.isActive?y("inverse",r?t.label:e.replace(/_/g," ")):r?y("dim",t.label):e.replace(/_/g,y("dim"," "))}function yV({style:e="heavy",max:t=100,size:r=40,...n}={}){let i=Km(n),o=0,s="",a=Math.max(1,t),c=Math.max(1,r),l=m=>{switch(m){case"initial":case"active":return h=>y("magenta",h);case"error":case"cancel":return h=>y("red",h);case"submit":return h=>y("green",h);default:return h=>y("magenta",h)}},u=(m,h)=>{let g=Math.floor(o/a*c);return`${l(m)(TA[e].repeat(g))}${y("dim",TA[e].repeat(c-g))} ${h}`},p=(m="")=>{s=m,i.start(u("initial",m))},d=(m=1,h)=>{o=Math.min(a,m+o),i.message(u("active",h??s)),s=h??s};return{start:p,stop:i.stop,cancel:i.cancel,error:i.error,clear:i.clear,advance:d,isCancelled:i.isCancelled,message:m=>d(0,m)}}var ss,au,Dm,$A,ne,CA,Lm,Pm,Di,Mm,C,ve,kA,RA,Ca,Ni,cu,Oi,as,OA,lu,Fm,NA,Bm,Um,DA,Hm,jm,Gm,Wm,ft,Vm,vA,In,PA,YW,zW,JW,ZW,XW,QW,eV,nV,iV,oV,pt,sV,aV,cV,lV,$a,uV,dV,pV,fV,mV,hV,gV,Km,TA,su,wV,_V,AA,Ri,bV,xV,EV,vV,Ra=f(()=>{Om();Om();Em();wm();ss=yu(Sm(),1);au=KW(),Dm=()=>process.env.CI==="true",$A=e=>e.isTTY===!0,ne=(e,t)=>au?e:t,CA=ne("\u25C6","*"),Lm=ne("\u25A0","x"),Pm=ne("\u25B2","x"),Di=ne("\u25C7","o"),Mm=ne("\u250C","T"),C=ne("\u2502","|"),ve=ne("\u2514","\u2014"),kA=ne("\u2510","T"),RA=ne("\u2518","\u2014"),Ca=ne("\u25CF",">"),Ni=ne("\u25CB"," "),cu=ne("\u25FB","[\u2022]"),Oi=ne("\u25FC","[+]"),as=ne("\u25FB","[ ]"),OA=ne("\u25AA","\u2022"),lu=ne("\u2500","-"),Fm=ne("\u256E","+"),NA=ne("\u251C","+"),Bm=ne("\u256F","+"),Um=ne("\u2570","+"),DA=ne("\u256D","+"),Hm=ne("\u25CF","\u2022"),jm=ne("\u25C6","*"),Gm=ne("\u25B2","!"),Wm=ne("\u25A0","x"),ft=e=>{switch(e){case"initial":case"active":return y("cyan",CA);case"cancel":return y("red",Lm);case"error":return y("yellow",Pm);case"submit":return y("green",Di)}},Vm=e=>{switch(e){case"initial":case"active":return y("cyan",C);case"cancel":return y("red",C);case"error":return y("yellow",C);case"submit":return y("green",C)}},vA=(e,t,r,n,i,o=!1)=>{let s=t,a=0;if(o)for(let c=n-1;c>=r&&(s-=e[c].length,a++,!(s<=i));c--);else for(let c=r;c<n&&(s-=e[c].length,a++,!(s<=i));c++);return{lineCount:s,removals:a}},In=({cursor:e,options:t,style:r,output:n=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let a=ki(n)-o,c=km(n),l=y("dim","..."),u=Math.max(c-s,0),p=Math.max(Math.min(i,u),5),d=0;e>=p-3&&(d=Math.max(Math.min(e-p+3,t.length-p),0));let m=p<t.length&&d>0,h=p<t.length&&d+p<t.length,g=Math.min(d+p,t.length),w=[],_=0;m&&_++,h&&_++;let E=d+(m?1:0),I=g-(h?1:0);for(let v=E;v<I;v++){let S=Vt(r(t[v],v===e),a,{hard:!0,trim:!1}).split(`
1048
- `);w.push(S),_+=S.length}if(_>u){let v=0,S=0,L=_,F=e-E,D=u,J=()=>vA(w,L,0,F,D),G=()=>vA(w,L,F+1,w.length,D,!0);m?({lineCount:L,removals:v}=J(),L>D&&(h||(D-=1),{lineCount:L,removals:S}=G())):(h||(D-=1),{lineCount:L,removals:S}=G(),L>D&&(D-=1,{lineCount:L,removals:v}=J())),v>0&&(m=!0,w.splice(0,v)),S>0&&(h=!0,w.splice(w.length-S,S))}let $=[];m&&$.push(l);for(let v of w)for(let S of v)$.push(S);return h&&$.push(l),$};PA=e=>new Rm({options:e.options,initialValue:e.initialValue?[e.initialValue]:void 0,initialUserInput:e.initialUserInput,placeholder:e.placeholder,filter:e.filter??((t,r)=>LA(t,r)),signal:e.signal,input:e.input,output:e.output,validate:e.validate,render(){let t=e.withGuide??j.withGuide,r=t?[`${y("gray",C)}`,`${ft(this.state)} ${e.message}`]:[`${ft(this.state)} ${e.message}`],n=this.userInput,i=this.options,o=e.placeholder,s=n===""&&o!==void 0,a=(c,l)=>{let u=SA(c),p=c.hint&&c.value===this.focusedValue?y("dim",` (${c.hint})`):"";switch(l){case"active":return`${y("green",Ca)} ${u}${p}`;case"inactive":return`${y("dim",Ni)} ${y("dim",u)}`;case"disabled":return`${y("gray",Ni)} ${y(["strikethrough","gray"],u)}`}};switch(this.state){case"submit":{let c=qW(this.selectedValues,i),l=c.length>0?` ${y("dim",c.map(SA).join(", "))}`:"",u=t?y("gray",C):"";return`${r.join(`
1047
+ `),this._cursor++,!1)}constructor(t){super(t,!1),this.#n=t.showSubmit??!1,this.on("key",(r,n)=>{if(n?.name&&j.actions.has(n.name)){this.#o(n.name);return}if(r===" "&&this.#n){this.focused=this.focused==="editor"?"submit":"editor";return}if(n?.name!=="return"){if(this.#t=!1,n?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(n?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}r&&(this.#n&&this.focused==="submit"&&(this.focused="editor"),this.#e(r??""),this._cursor++)}}),this.on("userInput",r=>{this._setValue(r)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}},bA=class extends sr{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map(r=>r.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter(r=>!e.includes(r.value));this.value=t.map(r=>r.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(t=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:r})=>r===e.cursorAt),0);this.cursor=this.options[t].disabled?$r(t,1,this.options):t,this.on("key",r=>{r==="a"&&this.toggleAll(),r==="i"&&this.toggleInvert()}),this.on("cursor",r=>{switch(r){case"left":case"up":this.cursor=$r(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=$r(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},tu=class extends sr{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t=this.userInput;if(this.cursor>=t.length)return`${this.masked}${os(["inverse","hidden"],"_")}`;let r=this.masked,n=r.slice(0,this.cursor),i=r.slice(this.cursor);return`${n}${os("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t,...r}){super(r),this._mask=t??"\u2022",this.on("userInput",n=>{this._setValue(n)})}},ru=class extends sr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t){super(t,!1),this.options=t.options;let r=this.options.findIndex(({value:i})=>i===t.initialValue),n=r===-1?0:r;this.cursor=this.options[n].disabled?$r(n,1,this.options):n,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=$r(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=$r(this.cursor,1,this.options);break}this.changeValue()})}},nu=class extends sr{options;cursor=0;constructor(t){super(t,!1),this.options=t.options;let r=t.caseSensitive===!0,n=this.options.map(({value:[i]})=>r?i:i?.toLowerCase());this.cursor=Math.max(n.indexOf(t.initialValue),0),this.on("key",(i,o)=>{if(!i)return;let s=r&&o.shift?i.toUpperCase():i;if(!n.includes(s))return;let a=this.options.find(({value:[c]})=>r?c===s:c?.toLowerCase()===i);a&&(this.value=a.value,this.state="submit",this.emit("submit"))})}},iu=class extends sr{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let r=t.slice(0,this.cursor),[n,...i]=t.slice(this.cursor);return`${r}${os("inverse",n)}${i.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",r=>{this._setValue(r)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}});var ka={};A(ka,{S_BAR:()=>C,S_BAR_END:()=>ve,S_BAR_END_RIGHT:()=>RA,S_BAR_H:()=>lu,S_BAR_START:()=>Mm,S_BAR_START_RIGHT:()=>kA,S_CHECKBOX_ACTIVE:()=>cu,S_CHECKBOX_INACTIVE:()=>as,S_CHECKBOX_SELECTED:()=>Oi,S_CONNECT_LEFT:()=>NA,S_CORNER_BOTTOM_LEFT:()=>Um,S_CORNER_BOTTOM_RIGHT:()=>Bm,S_CORNER_TOP_LEFT:()=>DA,S_CORNER_TOP_RIGHT:()=>Fm,S_ERROR:()=>Wm,S_INFO:()=>Hm,S_PASSWORD_MASK:()=>OA,S_RADIO_ACTIVE:()=>Ca,S_RADIO_INACTIVE:()=>Ni,S_STEP_ACTIVE:()=>CA,S_STEP_CANCEL:()=>Lm,S_STEP_ERROR:()=>Pm,S_STEP_SUBMIT:()=>Di,S_SUCCESS:()=>jm,S_WARN:()=>Gm,autocomplete:()=>PA,autocompleteMultiselect:()=>zW,box:()=>QW,cancel:()=>aV,confirm:()=>eV,date:()=>tV,group:()=>oV,groupMultiselect:()=>sV,intro:()=>cV,isCI:()=>Dm,isCancel:()=>ou,isTTY:()=>$A,limitOptions:()=>In,log:()=>pt,multiline:()=>uV,multiselect:()=>dV,note:()=>mV,outro:()=>lV,password:()=>hV,path:()=>gV,progress:()=>wV,select:()=>_V,selectKey:()=>bV,settings:()=>j,spinner:()=>Km,stream:()=>Ri,symbol:()=>ft,symbolBar:()=>Vm,taskLog:()=>vV,tasks:()=>xV,text:()=>SV,unicode:()=>au,unicodeOr:()=>ne,updateSettings:()=>yA});import{styleText as y,stripVTControlCharacters as Nm}from"node:util";import Ct from"node:process";import{existsSync as WW,lstatSync as xA,readdirSync as VW}from"node:fs";import{dirname as EA,join as KW}from"node:path";function qW(){return Ct.platform!=="win32"?Ct.env.TERM!=="linux":!!Ct.env.CI||!!Ct.env.WT_SESSION||!!Ct.env.TERMINUS_SUBLIME||Ct.env.ConEmuTask==="{cmd::Cmder}"||Ct.env.TERM_PROGRAM==="Terminus-Sublime"||Ct.env.TERM_PROGRAM==="vscode"||Ct.env.TERM==="xterm-256color"||Ct.env.TERM==="alacritty"||Ct.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function SA(e){return e.label??String(e.value??"")}function LA(e,t){if(!e)return!0;let r=(t.label??String(t.value??"")).toLowerCase(),n=(t.hint??"").toLowerCase(),i=String(t.value).toLowerCase(),o=e.toLowerCase();return r.includes(o)||n.includes(o)||i.includes(o)}function YW(e,t){let r=[];for(let n of t)e.includes(n.value)&&r.push(n);return r}function IA(e,t,r,n){let i=r,o=r;return n==="center"?i=Math.floor((t-e)/2):n==="right"&&(i=t-e-r),o=t-i-e,[i,o]}function rV(e,t){let r=e.segmentValues,n=e.segmentCursor;if(t==="submit"||t==="cancel")return e.formattedValue;let i=y("gray",e.separator);return e.segments.map((o,s)=>{let a=s===n.segmentIndex&&!["submit","cancel"].includes(t),c=iV[o.type];return nV(r[o.type],{isActive:a,label:c})}).join(i)}function nV(e,t){let r=!e||e.replace(/_/g,"")==="";return t.isActive?y("inverse",r?t.label:e.replace(/_/g," ")):r?y("dim",t.label):e.replace(/_/g,y("dim"," "))}function wV({style:e="heavy",max:t=100,size:r=40,...n}={}){let i=Km(n),o=0,s="",a=Math.max(1,t),c=Math.max(1,r),l=m=>{switch(m){case"initial":case"active":return h=>y("magenta",h);case"error":case"cancel":return h=>y("red",h);case"submit":return h=>y("green",h);default:return h=>y("magenta",h)}},u=(m,h)=>{let g=Math.floor(o/a*c);return`${l(m)(TA[e].repeat(g))}${y("dim",TA[e].repeat(c-g))} ${h}`},p=(m="")=>{s=m,i.start(u("initial",m))},d=(m=1,h)=>{o=Math.min(a,m+o),i.message(u("active",h??s)),s=h??s};return{start:p,stop:i.stop,cancel:i.cancel,error:i.error,clear:i.clear,advance:d,isCancelled:i.isCancelled,message:m=>d(0,m)}}var ss,au,Dm,$A,ne,CA,Lm,Pm,Di,Mm,C,ve,kA,RA,Ca,Ni,cu,Oi,as,OA,lu,Fm,NA,Bm,Um,DA,Hm,jm,Gm,Wm,ft,Vm,vA,In,PA,zW,JW,ZW,XW,QW,eV,tV,iV,oV,sV,pt,aV,cV,lV,uV,$a,dV,pV,fV,mV,hV,gV,yV,Km,TA,su,_V,bV,AA,Ri,xV,EV,vV,SV,Ra=f(()=>{Om();Om();Em();wm();ss=yu(Sm(),1);au=qW(),Dm=()=>process.env.CI==="true",$A=e=>e.isTTY===!0,ne=(e,t)=>au?e:t,CA=ne("\u25C6","*"),Lm=ne("\u25A0","x"),Pm=ne("\u25B2","x"),Di=ne("\u25C7","o"),Mm=ne("\u250C","T"),C=ne("\u2502","|"),ve=ne("\u2514","\u2014"),kA=ne("\u2510","T"),RA=ne("\u2518","\u2014"),Ca=ne("\u25CF",">"),Ni=ne("\u25CB"," "),cu=ne("\u25FB","[\u2022]"),Oi=ne("\u25FC","[+]"),as=ne("\u25FB","[ ]"),OA=ne("\u25AA","\u2022"),lu=ne("\u2500","-"),Fm=ne("\u256E","+"),NA=ne("\u251C","+"),Bm=ne("\u256F","+"),Um=ne("\u2570","+"),DA=ne("\u256D","+"),Hm=ne("\u25CF","\u2022"),jm=ne("\u25C6","*"),Gm=ne("\u25B2","!"),Wm=ne("\u25A0","x"),ft=e=>{switch(e){case"initial":case"active":return y("cyan",CA);case"cancel":return y("red",Lm);case"error":return y("yellow",Pm);case"submit":return y("green",Di)}},Vm=e=>{switch(e){case"initial":case"active":return y("cyan",C);case"cancel":return y("red",C);case"error":return y("yellow",C);case"submit":return y("green",C)}},vA=(e,t,r,n,i,o=!1)=>{let s=t,a=0;if(o)for(let c=n-1;c>=r&&(s-=e[c].length,a++,!(s<=i));c--);else for(let c=r;c<n&&(s-=e[c].length,a++,!(s<=i));c++);return{lineCount:s,removals:a}},In=({cursor:e,options:t,style:r,output:n=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let a=ki(n)-o,c=km(n),l=y("dim","..."),u=Math.max(c-s,0),p=Math.max(Math.min(i,u),5),d=0;e>=p-3&&(d=Math.max(Math.min(e-p+3,t.length-p),0));let m=p<t.length&&d>0,h=p<t.length&&d+p<t.length,g=Math.min(d+p,t.length),w=[],_=0;m&&_++,h&&_++;let E=d+(m?1:0),I=g-(h?1:0);for(let v=E;v<I;v++){let S=Vt(r(t[v],v===e),a,{hard:!0,trim:!1}).split(`
1048
+ `);w.push(S),_+=S.length}if(_>u){let v=0,S=0,L=_,F=e-E,D=u,J=()=>vA(w,L,0,F,D),G=()=>vA(w,L,F+1,w.length,D,!0);m?({lineCount:L,removals:v}=J(),L>D&&(h||(D-=1),{lineCount:L,removals:S}=G())):(h||(D-=1),{lineCount:L,removals:S}=G(),L>D&&(D-=1,{lineCount:L,removals:v}=J())),v>0&&(m=!0,w.splice(0,v)),S>0&&(h=!0,w.splice(w.length-S,S))}let $=[];m&&$.push(l);for(let v of w)for(let S of v)$.push(S);return h&&$.push(l),$};PA=e=>new Rm({options:e.options,initialValue:e.initialValue?[e.initialValue]:void 0,initialUserInput:e.initialUserInput,placeholder:e.placeholder,filter:e.filter??((t,r)=>LA(t,r)),signal:e.signal,input:e.input,output:e.output,validate:e.validate,render(){let t=e.withGuide??j.withGuide,r=t?[`${y("gray",C)}`,`${ft(this.state)} ${e.message}`]:[`${ft(this.state)} ${e.message}`],n=this.userInput,i=this.options,o=e.placeholder,s=n===""&&o!==void 0,a=(c,l)=>{let u=SA(c),p=c.hint&&c.value===this.focusedValue?y("dim",` (${c.hint})`):"";switch(l){case"active":return`${y("green",Ca)} ${u}${p}`;case"inactive":return`${y("dim",Ni)} ${y("dim",u)}`;case"disabled":return`${y("gray",Ni)} ${y(["strikethrough","gray"],u)}`}};switch(this.state){case"submit":{let c=YW(this.selectedValues,i),l=c.length>0?` ${y("dim",c.map(SA).join(", "))}`:"",u=t?y("gray",C):"";return`${r.join(`
1049
1049
  `)}
1050
1050
  ${u}${l}`}case"cancel":{let c=n?` ${y(["strikethrough","dim"],n)}`:"",l=t?y("gray",C):"";return`${r.join(`
1051
1051
  `)}
1052
1052
  ${l}${c}`}default:{let c=this.state==="error"?"yellow":"cyan",l=t?`${y(c,C)} `:"",u=t?y(c,ve):"",p="";if(this.isNavigating||s){let E=s?o:n;p=E!==""?` ${y("dim",E)}`:""}else p=` ${this.userInputWithCursor}`;let d=this.filteredOptions.length!==i.length?y("dim",` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",m=this.filteredOptions.length===0&&n?[`${l}${y("yellow","No matches found")}`]:[],h=this.state==="error"?[`${l}${y("yellow",this.error)}`]:[];t&&r.push(`${l.trimEnd()}`),r.push(`${l}${y("dim","Search:")}${p}${d}`,...m,...h);let g=[`${y("dim","\u2191/\u2193")} to select`,`${y("dim","Enter:")} confirm`,`${y("dim","Type:")} to search`],w=[`${l}${g.join(" \u2022 ")}`,u],_=this.filteredOptions.length===0?[]:In({cursor:this.cursor,options:this.filteredOptions,columnPadding:t?3:0,rowPadding:r.length+w.length,style:(E,I)=>a(E,E.disabled?"disabled":I?"active":"inactive"),maxItems:e.maxItems,output:e.output});return[...r,..._.map(E=>`${l}${E}`),...w].join(`
1053
- `)}}}}).prompt(),YW=e=>{let t=(n,i,o,s)=>{let a=o.includes(n.value),c=n.label??String(n.value??""),l=n.hint&&s!==void 0&&n.value===s?y("dim",` (${n.hint})`):"",u=a?y("green",Oi):y("dim",as);return n.disabled?`${y("gray",as)} ${y(["strikethrough","gray"],c)}`:i?`${u} ${c}${l}`:`${u} ${y("dim",c)}`},r=new Rm({options:e.options,multiple:!0,placeholder:e.placeholder,filter:e.filter??((n,i)=>LA(n,i)),validate:()=>{if(e.required&&r.selectedValues.length===0)return"Please select at least one item"},initialValue:e.initialValues,signal:e.signal,input:e.input,output:e.output,render(){let n=e.withGuide??j.withGuide,i=`${n?`${y("gray",C)}
1053
+ `)}}}}).prompt(),zW=e=>{let t=(n,i,o,s)=>{let a=o.includes(n.value),c=n.label??String(n.value??""),l=n.hint&&s!==void 0&&n.value===s?y("dim",` (${n.hint})`):"",u=a?y("green",Oi):y("dim",as);return n.disabled?`${y("gray",as)} ${y(["strikethrough","gray"],c)}`:i?`${u} ${c}${l}`:`${u} ${y("dim",c)}`},r=new Rm({options:e.options,multiple:!0,placeholder:e.placeholder,filter:e.filter??((n,i)=>LA(n,i)),validate:()=>{if(e.required&&r.selectedValues.length===0)return"Please select at least one item"},initialValue:e.initialValues,signal:e.signal,input:e.input,output:e.output,render(){let n=e.withGuide??j.withGuide,i=`${n?`${y("gray",C)}
1054
1054
  `:""}${ft(this.state)} ${e.message}
1055
1055
  `,o=this.userInput,s=e.placeholder,a=o===""&&s!==void 0,c=this.isNavigating||a?y("dim",a?s:o):this.userInputWithCursor,l=this.options,u=this.filteredOptions.length!==l.length?y("dim",` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${i}${n?`${y("gray",C)} `:""}${y("dim",`${this.selectedValues.length} items selected`)}`;case"cancel":return`${i}${n?`${y("gray",C)} `:""}${y(["strikethrough","dim"],o)}`;default:{let p=this.state==="error"?"yellow":"cyan",d=n?`${y(p,C)} `:"",m=n?y(p,ve):"",h=[`${y("dim","\u2191/\u2193")} to navigate`,`${y("dim",this.isNavigating?"Space/Tab:":"Tab:")} select`,`${y("dim","Enter:")} confirm`,`${y("dim","Type:")} to search`],g=this.filteredOptions.length===0&&o?[`${d}${y("yellow","No matches found")}`]:[],w=this.state==="error"?[`${d}${y("yellow",this.error)}`]:[],_=[...`${i}${n?y(p,C):""}`.split(`
1056
1056
  `),`${d}${y("dim","Search:")} ${c}${u}`,...g,...w],E=[`${d}${h.join(" \u2022 ")}`,m],I=In({cursor:this.cursor,options:this.filteredOptions,style:($,v)=>t($,v,this.selectedValues,this.focusedValue),maxItems:e.maxItems,output:e.output,rowPadding:_.length+E.length});return[..._,...I.map($=>`${d}${$}`),...E].join(`
1057
- `)}}}});return r.prompt()},zW=[DA,Fm,Um,Bm],JW=[Mm,kA,ve,RA];ZW=e=>e,XW=(e="",t="",r)=>{let n=r?.output??process.stdout,i=ki(n),o=2,s=r?.titlePadding??1,a=r?.contentPadding??2,c=r?.width===void 0||r.width==="auto"?1:Math.min(1,r.width),l=r?.withGuide??j.withGuide?`${C} `:"",u=r?.formatBorder??ZW,p=(r?.rounded?zW:JW).map(u),d=u(lu),m=u(C),h=Ae(l),g=Ae(t),w=i-h,_=Math.floor(i*c)-h;if(r?.width==="auto"){let D=e.split(`
1057
+ `)}}}});return r.prompt()},JW=[DA,Fm,Um,Bm],ZW=[Mm,kA,ve,RA];XW=e=>e,QW=(e="",t="",r)=>{let n=r?.output??process.stdout,i=ki(n),o=2,s=r?.titlePadding??1,a=r?.contentPadding??2,c=r?.width===void 0||r.width==="auto"?1:Math.min(1,r.width),l=r?.withGuide??j.withGuide?`${C} `:"",u=r?.formatBorder??XW,p=(r?.rounded?JW:ZW).map(u),d=u(lu),m=u(C),h=Ae(l),g=Ae(t),w=i-h,_=Math.floor(i*c)-h;if(r?.width==="auto"){let D=e.split(`
1058
1058
  `),J=g+s*2;for(let pe of D){let Ce=Ae(pe)+a*2;Ce>J&&(J=Ce)}let G=J+o;G<_&&(_=G)}_%2!==0&&(_<w?_++:_--);let E=_-o,I=E-s*2,$=g>I?`${t.slice(0,I-3)}...`:t,[v,S]=IA(Ae($),E,s,r?.titleAlign),L=Vt(e,E-a*2,{hard:!0,trim:!1});n.write(`${l}${p[0]}${d.repeat(v)}${$}${d.repeat(S)}${p[1]}
1059
1059
  `);let F=L.split(`
1060
1060
  `);for(let D of F){let[J,G]=IA(Ae(D),E,a,r?.contentAlign);n.write(`${l}${m}${" ".repeat(J)}${D}${" ".repeat(G)}${m}
1061
1061
  `)}n.write(`${l}${p[2]}${d.repeat(E)}${p[3]}
1062
- `)},QW=e=>{let t=e.active??"Yes",r=e.inactive??"No";return new Zl({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let n=e.withGuide??j.withGuide,i=`${ft(this.state)} `,o=n?`${y("gray",C)} `:"",s=Ie(e.output,e.message,o,i),a=`${n?`${y("gray",C)}
1062
+ `)},eV=e=>{let t=e.active??"Yes",r=e.inactive??"No";return new Zl({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let n=e.withGuide??j.withGuide,i=`${ft(this.state)} `,o=n?`${y("gray",C)} `:"",s=Ie(e.output,e.message,o,i),a=`${n?`${y("gray",C)}
1063
1063
  `:""}${s}
1064
1064
  `,c=this.value?t:r;switch(this.state){case"submit":{let l=n?`${y("gray",C)} `:"";return`${a}${l}${y("dim",c)}`}case"cancel":{let l=n?`${y("gray",C)} `:"";return`${a}${l}${y(["strikethrough","dim"],c)}${n?`
1065
1065
  ${y("gray",C)}`:""}`}default:{let l=n?`${y("cyan",C)} `:"",u=n?y("cyan",ve):"";return`${a}${l}${this.value?`${y("green",Ca)} ${t}`:`${y("dim",Ni)} ${y("dim",t)}`}${e.vertical?n?`
1066
1066
  ${y("cyan",C)} `:`
1067
1067
  `:` ${y("dim","/")} `}${this.value?`${y("dim",Ni)} ${y("dim",r)}`:`${y("green",Ca)} ${r}`}
1068
1068
  ${u}
1069
- `}}}}).prompt()},eV=e=>{let t=e.validate;return new Xl({...e,validate(r){if(r===void 0)return e.defaultValue!==void 0?void 0:t?t(r):j.date.messages.required;let n=i=>i.toISOString().slice(0,10);if(e.minDate&&n(r)<n(e.minDate))return j.date.messages.afterMin(e.minDate);if(e.maxDate&&n(r)>n(e.maxDate))return j.date.messages.beforeMax(e.maxDate);if(t)return t(r)},render(){let r=(e?.withGuide??j.withGuide)!==!1,n=`${`${r?`${y("gray",C)}
1069
+ `}}}}).prompt()},tV=e=>{let t=e.validate;return new Xl({...e,validate(r){if(r===void 0)return e.defaultValue!==void 0?void 0:t?t(r):j.date.messages.required;let n=i=>i.toISOString().slice(0,10);if(e.minDate&&n(r)<n(e.minDate))return j.date.messages.afterMin(e.minDate);if(e.maxDate&&n(r)>n(e.maxDate))return j.date.messages.beforeMax(e.maxDate);if(t)return t(r)},render(){let r=(e?.withGuide??j.withGuide)!==!1,n=`${`${r?`${y("gray",C)}
1070
1070
  `:""}${ft(this.state)} `}${e.message}
1071
- `,i=this.state!=="initial"?this.state:"active",o=tV(this,i),s=this.value instanceof Date?this.formattedValue:"";switch(this.state){case"error":{let a=this.error?` ${y("yellow",this.error)}`:"",c=r?`${y("yellow",C)} `:"",l=r?y("yellow",ve):"";return`${n.trim()}
1071
+ `,i=this.state!=="initial"?this.state:"active",o=rV(this,i),s=this.value instanceof Date?this.formattedValue:"";switch(this.state){case"error":{let a=this.error?` ${y("yellow",this.error)}`:"",c=r?`${y("yellow",C)} `:"",l=r?y("yellow",ve):"";return`${n.trim()}
1072
1072
  ${c}${o}
1073
1073
  ${l}${a}
1074
1074
  `}case"submit":{let a=s?` ${y("dim",s)}`:"",c=r?y("gray",C):"";return`${n}${c}${a}`}case"cancel":{let a=s?` ${y(["strikethrough","dim"],s)}`:"",c=r?y("gray",C):"";return`${n}${c}${a}${s.trim()?`
1075
1075
  ${c}`:""}`}default:{let a=r?`${y("cyan",C)} `:"",c=r?y("cyan",ve):"",l=r?`${y("cyan",C)} `:"",u=this.inlineError?`
1076
1076
  ${l}${y("yellow",this.inlineError)}`:"";return`${n}${a}${o}${u}
1077
1077
  ${c}
1078
- `}}}}).prompt()};nV={year:"yyyy",month:"mm",day:"dd"},iV=async(e,t)=>{let r={},n=Object.keys(e);for(let i of n){let o=e[i],s=await o({results:r})?.catch(a=>{throw a});if(typeof t?.onCancel=="function"&&ou(s)){r[i]="canceled",t.onCancel({results:r});continue}r[i]=s}return r},oV=e=>{let{selectableGroups:t=!0,groupSpacing:r=0}=e,n=(o,s,a=[])=>{let c=o.label??String(o.value),l=typeof o.group=="string",u=l&&(a[a.indexOf(o)+1]??{group:!0}),p=l&&u&&u.group===!0,d="",m="";l&&(t?(d=p?`${ve} `:`${C} `,m=p?" ":`${C} `):d=" ");let h="";if(r>0&&!l&&(h=`
1078
+ `}}}}).prompt()};iV={year:"yyyy",month:"mm",day:"dd"},oV=async(e,t)=>{let r={},n=Object.keys(e);for(let i of n){let o=e[i],s=await o({results:r})?.catch(a=>{throw a});if(typeof t?.onCancel=="function"&&ou(s)){r[i]="canceled",t.onCancel({results:r});continue}r[i]=s}return r},sV=e=>{let{selectableGroups:t=!0,groupSpacing:r=0}=e,n=(o,s,a=[])=>{let c=o.label??String(o.value),l=typeof o.group=="string",u=l&&(a[a.indexOf(o)+1]??{group:!0}),p=l&&u&&u.group===!0,d="",m="";l&&(t?(d=p?`${ve} `:`${C} `,m=p?" ":`${C} `):d=" ");let h="";if(r>0&&!l&&(h=`
1079
1079
  `.repeat(r)),s==="active")return Ie(e.output,`${c}${o.hint?` ${y("dim",`(${o.hint})`)}`:""}`,`${h}${y("dim",d)} `,`${h}${y("dim",d)}${y("cyan",cu)} `,`${h}${y("dim",m)} `);if(s==="group-active")return Ie(e.output,c,`${h}${d} `,`${h}${d}${y("cyan",cu)} `,`${h}${m} `,w=>y("dim",w));if(s==="group-active-selected")return Ie(e.output,c,`${h}${d} `,`${h}${d}${y("green",Oi)} `,`${h}${m} `,w=>y("dim",w));if(s==="selected"){let w=l||t?y("green",Oi):"";return Ie(e.output,`${c}${o.hint?` (${o.hint})`:""}`,`${h}${y("dim",d)} `,`${h}${y("dim",d)}${w} `,`${h}${y("dim",m)} `,_=>y("dim",_))}if(s==="cancelled")return`${y(["strikethrough","dim"],c)}`;if(s==="active-selected")return Ie(e.output,`${c}${o.hint?` ${y("dim",`(${o.hint})`)}`:""}`,`${h}${y("dim",d)} `,`${h}${y("dim",d)}${y("green",Oi)} `,`${h}${y("dim",m)} `);if(s==="submitted")return`${y("dim",c)}`;let g=l||t?y("dim",as):"";return Ie(e.output,c,`${h}${y("dim",d)} `,`${h}${y("dim",d)}${g} `,`${h}${y("dim",m)} `,w=>y("dim",w))},i=e.required??!0;return new Ql({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:i,cursorAt:e.cursorAt,selectableGroups:t,validate(o){if(i&&(o===void 0||o.length===0))return`Please select at least one option.
1080
1080
  ${y("reset",y("dim",`Press ${y(["gray","bgWhite","inverse"]," space ")} to select, ${y("gray",y(["bgWhite","inverse"]," enter "))} to submit`))}`},render(){let o=e.withGuide??j.withGuide,s=`${o?`${y("gray",C)}
1081
1081
  `:""}${ft(this.state)} ${e.message}
@@ -1094,13 +1094,13 @@ ${o?y("cyan",ve):""}
1094
1094
  `}}}}).prompt()},pt={message:(e=[],{symbol:t=y("gray",C),secondarySymbol:r=y("gray",C),output:n=process.stdout,spacing:i=1,withGuide:o}={})=>{let s=[],a=o??j.withGuide,c=a?r:"",l=a?`${t} `:"",u=a?`${r} `:"";for(let d=0;d<i;d++)s.push(c);let p=Array.isArray(e)?e:e.split(`
1095
1095
  `);if(p.length>0){let[d,...m]=p;d.length>0?s.push(`${l}${d}`):s.push(a?t:"");for(let h of m)h.length>0?s.push(`${u}${h}`):s.push(a?r:"")}n.write(`${s.join(`
1096
1096
  `)}
1097
- `)},info:(e,t)=>{pt.message(e,{...t,symbol:y("blue",Hm)})},success:(e,t)=>{pt.message(e,{...t,symbol:y("green",jm)})},step:(e,t)=>{pt.message(e,{...t,symbol:y("green",Di)})},warn:(e,t)=>{pt.message(e,{...t,symbol:y("yellow",Gm)})},warning:(e,t)=>{pt.warn(e,t)},error:(e,t)=>{pt.message(e,{...t,symbol:y("red",Wm)})}},sV=(e="",t)=>{let r=t?.output??process.stdout,n=t?.withGuide??j.withGuide?`${y("gray",ve)} `:"";r.write(`${n}${y("red",e)}
1097
+ `)},info:(e,t)=>{pt.message(e,{...t,symbol:y("blue",Hm)})},success:(e,t)=>{pt.message(e,{...t,symbol:y("green",jm)})},step:(e,t)=>{pt.message(e,{...t,symbol:y("green",Di)})},warn:(e,t)=>{pt.message(e,{...t,symbol:y("yellow",Gm)})},warning:(e,t)=>{pt.warn(e,t)},error:(e,t)=>{pt.message(e,{...t,symbol:y("red",Wm)})}},aV=(e="",t)=>{let r=t?.output??process.stdout,n=t?.withGuide??j.withGuide?`${y("gray",ve)} `:"";r.write(`${n}${y("red",e)}
1098
1098
 
1099
- `)},aV=(e="",t)=>{let r=t?.output??process.stdout,n=t?.withGuide??j.withGuide?`${y("gray",Mm)} `:"";r.write(`${n}${e}
1100
- `)},cV=(e="",t)=>{let r=t?.output??process.stdout,n=t?.withGuide??j.withGuide?`${y("gray",C)}
1099
+ `)},cV=(e="",t)=>{let r=t?.output??process.stdout,n=t?.withGuide??j.withGuide?`${y("gray",Mm)} `:"";r.write(`${n}${e}
1100
+ `)},lV=(e="",t)=>{let r=t?.output??process.stdout,n=t?.withGuide??j.withGuide?`${y("gray",C)}
1101
1101
  ${y("gray",ve)} `:"";r.write(`${n}${e}
1102
1102
 
1103
- `)},lV=e=>new eu({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,showSubmit:e.showSubmit,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??j.withGuide,r=`${`${t?`${y("gray",C)}
1103
+ `)},uV=e=>new eu({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,showSubmit:e.showSubmit,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??j.withGuide,r=`${`${t?`${y("gray",C)}
1104
1104
  `:""}${ft(this.state)} `}${e.message}
1105
1105
  `,n=e.placeholder?y("inverse",e.placeholder[0])+y("dim",e.placeholder.slice(1)):y(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:n,o=this.value??"",s=e.showSubmit?`
1106
1106
  ${y(this.focused==="submit"?"cyan":"dim","[ submit ]")}`:"";switch(this.state){case"error":{let a=`${y("yellow",C)} `,c=t?Ie(e.output,i,a,void 0):i,l=y("yellow",ve);return`${r}${c}
@@ -1109,7 +1109,7 @@ ${l} ${y("yellow",this.error)}${s}
1109
1109
  ${c}${s}
1110
1110
  `}}}}).prompt(),$a=(e,t)=>e.split(`
1111
1111
  `).map(r=>t(r)).join(`
1112
- `),uV=e=>{let t=(n,i)=>{let o=n.label??String(n.value);return i==="disabled"?`${y("gray",as)} ${$a(o,s=>y(["strikethrough","gray"],s))}${n.hint?` ${y("dim",`(${n.hint??"disabled"})`)}`:""}`:i==="active"?`${y("cyan",cu)} ${o}${n.hint?` ${y("dim",`(${n.hint})`)}`:""}`:i==="selected"?`${y("green",Oi)} ${$a(o,s=>y("dim",s))}${n.hint?` ${y("dim",`(${n.hint})`)}`:""}`:i==="cancelled"?`${$a(o,s=>y(["strikethrough","dim"],s))}`:i==="active-selected"?`${y("green",Oi)} ${o}${n.hint?` ${y("dim",`(${n.hint})`)}`:""}`:i==="submitted"?`${$a(o,s=>y("dim",s))}`:`${y("dim",as)} ${$a(o,s=>y("dim",s))}`},r=e.required??!0;return new bA({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:r,cursorAt:e.cursorAt,validate(n){if(r&&(n===void 0||n.length===0))return`Please select at least one option.
1112
+ `),dV=e=>{let t=(n,i)=>{let o=n.label??String(n.value);return i==="disabled"?`${y("gray",as)} ${$a(o,s=>y(["strikethrough","gray"],s))}${n.hint?` ${y("dim",`(${n.hint??"disabled"})`)}`:""}`:i==="active"?`${y("cyan",cu)} ${o}${n.hint?` ${y("dim",`(${n.hint})`)}`:""}`:i==="selected"?`${y("green",Oi)} ${$a(o,s=>y("dim",s))}${n.hint?` ${y("dim",`(${n.hint})`)}`:""}`:i==="cancelled"?`${$a(o,s=>y(["strikethrough","dim"],s))}`:i==="active-selected"?`${y("green",Oi)} ${o}${n.hint?` ${y("dim",`(${n.hint})`)}`:""}`:i==="submitted"?`${$a(o,s=>y("dim",s))}`:`${y("dim",as)} ${$a(o,s=>y("dim",s))}`},r=e.required??!0;return new bA({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:r,cursorAt:e.cursorAt,validate(n){if(r&&(n===void 0||n.length===0))return`Please select at least one option.
1113
1113
  ${y("reset",y("dim",`Press ${y(["gray","bgWhite","inverse"]," space ")} to select, ${y("gray",y("bgWhite",y("inverse"," enter ")))} to submit`))}`},render(){let n=e.withGuide??j.withGuide,i=Ie(e.output,e.message,n?`${Vm(this.state)} `:"",`${ft(this.state)} `),o=`${n?`${y("gray",C)}
1114
1114
  `:""}${i}
1115
1115
  `,s=this.value??[],a=(c,l)=>{if(c.disabled)return t(c,"disabled");let u=s.includes(c.value);return l&&u?t(c,"active-selected"):u?t(c,"selected"):t(c,l?"active":"inactive")};switch(this.state){case"submit":{let c=this.options.filter(({value:u})=>s.includes(u)).map(u=>t(u,"submitted")).join(y("dim",", "))||y("dim","none"),l=Ie(e.output,c,n?`${y("gray",C)} `:"");return`${o}${l}`}case"cancel":{let c=this.options.filter(({value:u})=>s.includes(u)).map(u=>t(u,"cancelled")).join(y("dim",", "));if(c.trim()==="")return`${o}${y("gray",C)}`;let l=Ie(e.output,c,n?`${y("gray",C)} `:"");return`${o}${l}${n?`
@@ -1124,14 +1124,14 @@ ${l}
1124
1124
  `).length,u=n?2:1;return`${o}${c}${In({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+u,style:a}).join(`
1125
1125
  ${c}`)}
1126
1126
  ${n?y("cyan",ve):""}
1127
- `}}}}).prompt()},dV=e=>y("dim",e),pV=(e,t,r)=>{let n={hard:!0,trim:!1},i=Vt(e,t,n).split(`
1128
- `),o=i.reduce((c,l)=>Math.max(Ae(l),c),0),s=i.map(r).reduce((c,l)=>Math.max(Ae(l),c),0),a=t-(s-o);return Vt(e,a,n)},fV=(e="",t="",r)=>{let n=r?.output??Ct.stdout,i=r?.withGuide??j.withGuide,o=r?.format??dV,s=["",...pV(e,ki(n)-6,o).split(`
1127
+ `}}}}).prompt()},pV=e=>y("dim",e),fV=(e,t,r)=>{let n={hard:!0,trim:!1},i=Vt(e,t,n).split(`
1128
+ `),o=i.reduce((c,l)=>Math.max(Ae(l),c),0),s=i.map(r).reduce((c,l)=>Math.max(Ae(l),c),0),a=t-(s-o);return Vt(e,a,n)},mV=(e="",t="",r)=>{let n=r?.output??Ct.stdout,i=r?.withGuide??j.withGuide,o=r?.format??pV,s=["",...fV(e,ki(n)-6,o).split(`
1129
1129
  `).map(o),""],a=Ae(t),c=Math.max(s.reduce((d,m)=>{let h=Ae(m);return h>d?h:d},0),a)+2,l=s.map(d=>`${y("gray",C)} ${d}${" ".repeat(c-Ae(d))}${y("gray",C)}`).join(`
1130
1130
  `),u=i?`${y("gray",C)}
1131
1131
  `:"",p=i?NA:Um;n.write(`${u}${y("green",Di)} ${y("reset",t)} ${y("gray",lu.repeat(Math.max(c-a-1,1))+Fm)}
1132
1132
  ${l}
1133
1133
  ${y("gray",p+lu.repeat(c+2)+Bm)}
1134
- `)},mV=e=>new tu({validate:e.validate,mask:e.mask??OA,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??j.withGuide,r=`${t?`${y("gray",C)}
1134
+ `)},hV=e=>new tu({validate:e.validate,mask:e.mask??OA,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??j.withGuide,r=`${t?`${y("gray",C)}
1135
1135
  `:""}${ft(this.state)} ${e.message}
1136
1136
  `,n=this.userInputWithCursor,i=this.masked;switch(this.state){case"error":{let o=t?`${y("yellow",C)} `:"",s=t?`${y("yellow",ve)} `:"",a=i??"";return e.clearOnError&&this.clear(),`${r.trim()}
1137
1137
  ${o}${a}
@@ -1139,7 +1139,7 @@ ${s}${y("yellow",this.error)}
1139
1139
  `}case"submit":{let o=t?`${y("gray",C)} `:"",s=i?y("dim",i):"";return`${r}${o}${s}`}case"cancel":{let o=t?`${y("gray",C)} `:"",s=i?y(["strikethrough","dim"],i):"";return`${r}${o}${s}${i&&t?`
1140
1140
  ${y("gray",C)}`:""}`}default:{let o=t?`${y("cyan",C)} `:"",s=t?y("cyan",ve):"";return`${r}${o}${n}
1141
1141
  ${s}
1142
- `}}}}).prompt(),hV=e=>{let t=e.validate;return PA({...e,initialUserInput:e.initialValue??e.root??process.cwd(),maxItems:5,validate(r){if(!Array.isArray(r)){if(!r)return"Please select a path";if(t)return t(r)}},options(){let r=this.userInput;if(r==="")return[];try{let n;GW(r)?xA(r).isDirectory()&&(!e.directory||r.endsWith("/"))?n=r:n=EA(r):n=EA(r);let i=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return WW(n).map(o=>{let s=VW(n,o),a=xA(s);return{name:o,path:s,isDirectory:a.isDirectory()}}).filter(({path:o,isDirectory:s})=>o.startsWith(i)&&(s||!e.directory)).map(o=>({value:o.path}))}catch{return[]}}})},gV=e=>y("magenta",e),Km=({indicator:e="dots",onCancel:t,output:r=process.stdout,cancelMessage:n,errorMessage:i,frames:o=au?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:s=au?80:120,signal:a,...c}={})=>{let l=Dm(),u,p,d=!1,m=!1,h="",g,w=performance.now(),_=ki(r),E=c?.styleFrame??gV,I=X=>{let re=X>1?i??j.messages.error:n??j.messages.cancel;m=X===1,d&&(Ce(re,X),m&&typeof t=="function"&&t())},$=()=>I(2),v=()=>I(1),S=()=>{process.on("uncaughtExceptionMonitor",$),process.on("unhandledRejection",$),process.on("SIGINT",v),process.on("SIGTERM",v),process.on("exit",I),a&&a.addEventListener("abort",v)},L=()=>{process.removeListener("uncaughtExceptionMonitor",$),process.removeListener("unhandledRejection",$),process.removeListener("SIGINT",v),process.removeListener("SIGTERM",v),process.removeListener("exit",I),a&&a.removeEventListener("abort",v)},F=()=>{if(g===void 0)return;l&&r.write(`
1142
+ `}}}}).prompt(),gV=e=>{let t=e.validate;return PA({...e,initialUserInput:e.initialValue??e.root??process.cwd(),maxItems:5,validate(r){if(!Array.isArray(r)){if(!r)return"Please select a path";if(t)return t(r)}},options(){let r=this.userInput;if(r==="")return[];try{let n;WW(r)?xA(r).isDirectory()&&(!e.directory||r.endsWith("/"))?n=r:n=EA(r):n=EA(r);let i=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return VW(n).map(o=>{let s=KW(n,o),a=xA(s);return{name:o,path:s,isDirectory:a.isDirectory()}}).filter(({path:o,isDirectory:s})=>o.startsWith(i)&&(s||!e.directory)).map(o=>({value:o.path}))}catch{return[]}}})},yV=e=>y("magenta",e),Km=({indicator:e="dots",onCancel:t,output:r=process.stdout,cancelMessage:n,errorMessage:i,frames:o=au?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:s=au?80:120,signal:a,...c}={})=>{let l=Dm(),u,p,d=!1,m=!1,h="",g,w=performance.now(),_=ki(r),E=c?.styleFrame??yV,I=X=>{let re=X>1?i??j.messages.error:n??j.messages.cancel;m=X===1,d&&(Ce(re,X),m&&typeof t=="function"&&t())},$=()=>I(2),v=()=>I(1),S=()=>{process.on("uncaughtExceptionMonitor",$),process.on("unhandledRejection",$),process.on("SIGINT",v),process.on("SIGTERM",v),process.on("exit",I),a&&a.addEventListener("abort",v)},L=()=>{process.removeListener("uncaughtExceptionMonitor",$),process.removeListener("unhandledRejection",$),process.removeListener("SIGINT",v),process.removeListener("SIGTERM",v),process.removeListener("exit",I),a&&a.removeEventListener("abort",v)},F=()=>{if(g===void 0)return;l&&r.write(`
1143
1143
  `);let X=Vt(g,_,{hard:!0,trim:!1}).split(`
1144
1144
  `);X.length>1&&r.write(ss.cursor.up(X.length-1)),r.write(ss.cursor.to(0)),r.write(ss.erase.down())},D=X=>X.replace(/\.+$/,""),J=X=>{let re=(performance.now()-X)/1e3,Q=Math.floor(re/60),ee=Math.floor(re%60);return Q>0?`[${Q}m ${ee}s]`:`[${ee}s]`},G=c.withGuide??j.withGuide,pe=(X="")=>{d=!0,u=wA({output:r}),h=D(X),w=performance.now(),G&&r.write(`${y("gray",C)}
1145
1145
  `);let re=0,Q=0;S(),p=setInterval(()=>{if(l&&h===g)return;F(),g=h;let ee=E(o[re]),Pe;if(l)Pe=`${ee} ${h}...`;else if(e==="timer")Pe=`${ee} ${h} ${J(w)}`;else{let ce=".".repeat(Math.floor(Q)).slice(0,3);Pe=`${ee} ${h}${ce}`}let ke=Vt(Pe,_,{hard:!0,trim:!1});r.write(ke),re=re+1<o.length?re+1:0,Q=Q<4?Q+.125:0},s)},Ce=(X="",re=0,Q=!1)=>{if(!d)return;d=!1,clearInterval(p),F();let ee=re===0?y("green",Di):re===1?y("red",Lm):y("red",Pm);h=X??h,Q||(e==="timer"?r.write(`${ee} ${h} ${J(w)}
@@ -1147,14 +1147,14 @@ ${s}
1147
1147
  `)),L(),u()};return{start:pe,stop:(X="")=>Ce(X,0),message:(X="")=>{h=D(X??h)},cancel:(X="")=>Ce(X,1),error:(X="")=>Ce(X,2),clear:()=>Ce("",0,!0),get isCancelled(){return m}}},TA={light:ne("\u2500","-"),heavy:ne("\u2501","="),block:ne("\u2588","#")};su=(e,t)=>e.includes(`
1148
1148
  `)?e.split(`
1149
1149
  `).map(r=>t(r)).join(`
1150
- `):t(e),wV=e=>{let t=(r,n)=>{let i=r.label??String(r.value);switch(n){case"disabled":return`${y("gray",Ni)} ${su(i,o=>y("gray",o))}${r.hint?` ${y("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${su(i,o=>y("dim",o))}`;case"active":return`${y("green",Ca)} ${i}${r.hint?` ${y("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${su(i,o=>y(["strikethrough","dim"],o))}`;default:return`${y("dim",Ni)} ${su(i,o=>y("dim",o))}`}};return new ru({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??j.withGuide,n=`${ft(this.state)} `,i=`${Vm(this.state)} `,o=Ie(e.output,e.message,i,n),s=`${r?`${y("gray",C)}
1150
+ `):t(e),_V=e=>{let t=(r,n)=>{let i=r.label??String(r.value);switch(n){case"disabled":return`${y("gray",Ni)} ${su(i,o=>y("gray",o))}${r.hint?` ${y("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${su(i,o=>y("dim",o))}`;case"active":return`${y("green",Ca)} ${i}${r.hint?` ${y("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${su(i,o=>y(["strikethrough","dim"],o))}`;default:return`${y("dim",Ni)} ${su(i,o=>y("dim",o))}`}};return new ru({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??j.withGuide,n=`${ft(this.state)} `,i=`${Vm(this.state)} `,o=Ie(e.output,e.message,i,n),s=`${r?`${y("gray",C)}
1151
1151
  `:""}${o}
1152
1152
  `;switch(this.state){case"submit":{let a=r?`${y("gray",C)} `:"",c=Ie(e.output,t(this.options[this.cursor],"selected"),a);return`${s}${c}`}case"cancel":{let a=r?`${y("gray",C)} `:"",c=Ie(e.output,t(this.options[this.cursor],"cancelled"),a);return`${s}${c}${r?`
1153
1153
  ${y("gray",C)}`:""}`}default:{let a=r?`${y("cyan",C)} `:"",c=r?y("cyan",ve):"",l=s.split(`
1154
1154
  `).length,u=r?2:1;return`${s}${a}${In({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:l+u,style:(p,d)=>t(p,p.disabled?"disabled":d?"active":"inactive")}).join(`
1155
1155
  ${a}`)}
1156
1156
  ${c}
1157
- `}}}}).prompt()},_V=e=>{let t=(r,n="inactive")=>{let i=r.label??String(r.value);return n==="selected"?`${y("dim",i)}`:n==="cancelled"?`${y(["strikethrough","dim"],i)}`:n==="active"?`${y(["bgCyan","gray"],` ${r.value} `)} ${i}${r.hint?` ${y("dim",`(${r.hint})`)}`:""}`:`${y(["gray","bgWhite","inverse"],` ${r.value} `)} ${i}${r.hint?` ${y("dim",`(${r.hint})`)}`:""}`};return new nu({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,caseSensitive:e.caseSensitive,render(){let r=e.withGuide??j.withGuide,n=`${r?`${y("gray",C)}
1157
+ `}}}}).prompt()},bV=e=>{let t=(r,n="inactive")=>{let i=r.label??String(r.value);return n==="selected"?`${y("dim",i)}`:n==="cancelled"?`${y(["strikethrough","dim"],i)}`:n==="active"?`${y(["bgCyan","gray"],` ${r.value} `)} ${i}${r.hint?` ${y("dim",`(${r.hint})`)}`:""}`:`${y(["gray","bgWhite","inverse"],` ${r.value} `)} ${i}${r.hint?` ${y("dim",`(${r.hint})`)}`:""}`};return new nu({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,caseSensitive:e.caseSensitive,render(){let r=e.withGuide??j.withGuide,n=`${r?`${y("gray",C)}
1158
1158
  `:""}${ft(this.state)} ${e.message}
1159
1159
  `;switch(this.state){case"submit":{let i=r?`${y("gray",C)} `:"",o=this.options.find(a=>a.value===this.value)??e.options[0],s=Ie(e.output,t(o,"selected"),i);return`${n}${s}`}case"cancel":{let i=r?`${y("gray",C)} `:"",o=Ie(e.output,t(this.options[0],"cancelled"),i);return`${n}${o}${r?`
1160
1160
  ${y("gray",C)}`:""}`}default:{let i=r?`${y("cyan",C)} `:"",o=r?y("cyan",ve):"",s=this.options.map((a,c)=>Ie(e.output,t(a,c===this.cursor?"active":"inactive"),i)).join(`
@@ -1166,7 +1166,7 @@ ${AA}`),n.includes(`
1166
1166
  `)&&(r=3+Nm(n.slice(n.lastIndexOf(`
1167
1167
  `))).length);let i=Nm(n).length;r+i<process.stdout.columns?(r+=i,process.stdout.write(n)):(process.stdout.write(`
1168
1168
  ${AA}${n.trimStart()}`),r=3+Nm(n.trimStart()).length)}process.stdout.write(`
1169
- `)},info:e=>Ri.message(e,{symbol:y("blue",Hm)}),success:e=>Ri.message(e,{symbol:y("green",jm)}),step:e=>Ri.message(e,{symbol:y("green",Di)}),warn:e=>Ri.message(e,{symbol:y("yellow",Gm)}),warning:e=>Ri.warn(e),error:e=>Ri.message(e,{symbol:y("red",Wm)})},bV=async(e,t)=>{for(let r of e){if(r.enabled===!1)continue;let n=Km(t);n.start(r.title);let i=await r.task(n.message);n.stop(i||r.title)}},xV=e=>e.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),EV=e=>{let t=e.output??process.stdout,r=ki(t),n=y("gray",C),i=e.spacing??1,o=3,s=e.retainLog===!0,a=!Dm()&&$A(t);t.write(`${n}
1169
+ `)},info:e=>Ri.message(e,{symbol:y("blue",Hm)}),success:e=>Ri.message(e,{symbol:y("green",jm)}),step:e=>Ri.message(e,{symbol:y("green",Di)}),warn:e=>Ri.message(e,{symbol:y("yellow",Gm)}),warning:e=>Ri.warn(e),error:e=>Ri.message(e,{symbol:y("red",Wm)})},xV=async(e,t)=>{for(let r of e){if(r.enabled===!1)continue;let n=Km(t);n.start(r.title);let i=await r.task(n.message);n.stop(i||r.title)}},EV=e=>e.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),vV=e=>{let t=e.output??process.stdout,r=ki(t),n=y("gray",C),i=e.spacing??1,o=3,s=e.retainLog===!0,a=!Dm()&&$A(t);t.write(`${n}
1170
1170
  `),t.write(`${y("green",Di)} ${e.title}
1171
1171
  `);for(let w=0;w<i;w++)t.write(`${n}
1172
1172
  `);let c=[{value:"",full:""}],l=!1,u=w=>{if(c.length===0)return;let _=0;w&&(_+=i+2);for(let E of c){let{value:I,result:$}=E,v=$?.message??I;if(v.length===0)continue;$===void 0&&E.header!==void 0&&E.header!==""&&(v+=`
@@ -1175,11 +1175,11 @@ ${E.header}`);let S=v.split(`
1175
1175
  ${w.value}`:w.value;w.header!==void 0&&w.header!==""&&pt.message(w.header.split(`
1176
1176
  `).map($=>y("bold",$)),{output:t,secondarySymbol:n,symbol:n,spacing:0}),pt.message(I.split(`
1177
1177
  `).map($=>y("dim",$)),{output:t,secondarySymbol:n,symbol:n,spacing:_??i})},d=()=>{for(let w of c){let{header:_,value:E,full:I}=w;(_===void 0||_.length===0)&&E.length===0||p(w,void 0,s===!0&&I.length>0)}},m=(w,_,E)=>{if(u(!1),(E?.raw!==!0||!l)&&w.value!==""&&(w.value+=`
1178
- `),w.value+=xV(_),l=E?.raw===!0,e.limit!==void 0){let I=w.value.split(`
1178
+ `),w.value+=EV(_),l=E?.raw===!0,e.limit!==void 0){let I=w.value.split(`
1179
1179
  `),$=I.length-e.limit;if($>0){let v=I.splice(0,$);s&&(w.full+=(w.full===""?"":`
1180
1180
  `)+v.join(`
1181
1181
  `))}w.value=I.join(`
1182
- `)}a&&h()},h=()=>{for(let w of c)w.result?w.result.status==="error"?pt.error(w.result.message,{output:t,secondarySymbol:n,spacing:0}):pt.success(w.result.message,{output:t,secondarySymbol:n,spacing:0}):w.value!==""&&p(w,0)},g=(w,_)=>{u(!1),w.result=_,a&&h()};return{message(w,_){m(c[0],w,_)},group(w){let _={header:w,value:"",full:""};return c.push(_),{message(E,I){m(_,E,I)},error(E){g(_,{status:"error",message:E})},success(E){g(_,{status:"success",message:E})}}},error(w,_){u(!0),pt.error(w,{output:t,secondarySymbol:n,spacing:1}),_?.showLog!==!1&&d(),c.splice(1,c.length-1),c[0].value="",c[0].full=""},success(w,_){u(!0),pt.success(w,{output:t,secondarySymbol:n,spacing:1}),_?.showLog===!0&&d(),c.splice(1,c.length-1),c[0].value="",c[0].full=""}}},vV=e=>new iu({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??j.withGuide,r=`${`${t?`${y("gray",C)}
1182
+ `)}a&&h()},h=()=>{for(let w of c)w.result?w.result.status==="error"?pt.error(w.result.message,{output:t,secondarySymbol:n,spacing:0}):pt.success(w.result.message,{output:t,secondarySymbol:n,spacing:0}):w.value!==""&&p(w,0)},g=(w,_)=>{u(!1),w.result=_,a&&h()};return{message(w,_){m(c[0],w,_)},group(w){let _={header:w,value:"",full:""};return c.push(_),{message(E,I){m(_,E,I)},error(E){g(_,{status:"error",message:E})},success(E){g(_,{status:"success",message:E})}}},error(w,_){u(!0),pt.error(w,{output:t,secondarySymbol:n,spacing:1}),_?.showLog!==!1&&d(),c.splice(1,c.length-1),c[0].value="",c[0].full=""},success(w,_){u(!0),pt.success(w,{output:t,secondarySymbol:n,spacing:1}),_?.showLog===!0&&d(),c.splice(1,c.length-1),c[0].value="",c[0].full=""}}},SV=e=>new iu({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??j.withGuide,r=`${`${t?`${y("gray",C)}
1183
1183
  `:""}${ft(this.state)} `}${e.message}
1184
1184
  `,n=e.placeholder?y("inverse",e.placeholder[0])+y("dim",e.placeholder.slice(1)):y(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:n,o=this.value??"";switch(this.state){case"error":{let s=this.error?` ${y("yellow",this.error)}`:"",a=t?`${y("yellow",C)} `:"",c=t?y("yellow",ve):"";return`${r.trim()}
1185
1185
  ${a}${i}
@@ -1187,24 +1187,24 @@ ${c}${s}
1187
1187
  `}case"submit":{let s=o?` ${y("dim",o)}`:"",a=t?y("gray",C):"";return`${r}${a}${s}`}case"cancel":{let s=o?` ${y(["strikethrough","dim"],o)}`:"",a=t?y("gray",C):"";return`${r}${a}${s}${o.trim()?`
1188
1188
  ${a}`:""}`}default:{let s=t?`${y("cyan",C)} `:"",a=t?y("cyan",ve):"";return`${r}${s}${i}
1189
1189
  ${a}
1190
- `}}}}).prompt()});var FA={};A(FA,{EMBEDDING_DEFAULTS:()=>IV,EMBEDDING_PROVIDERS:()=>MA,LLM_PROVIDERS:()=>SV});var SV,MA,IV,BA=f(()=>{SV=[{id:"claude-cli",label:"Claude Code",hint:"Uses your existing Claude Code subscription \u2014 no extra API key.",recommended:!0,fields:[],env:{LLM_PROVIDER:"claude-cli"}},{id:"openrouter",label:"OpenRouter",hint:"One API key for many models (Anthropic, OpenAI, Gemini, \u2026). Cheapest default.",fields:[{name:"OPENROUTER_API_KEY",label:"OpenRouter API key",type:"password",placeholder:"sk-or-\u2026"},{name:"LLM_OPENROUTER_MODEL",label:"Model (optional)",type:"text",placeholder:"google/gemini-flash-latest",optional:!0}],env:{LLM_PROVIDER:"openrouter"}},{id:"openai",label:"OpenAI",hint:"Direct OpenAI access. Requires sk-\u2026 key with chat + embeddings.",fields:[{name:"OPENAI_API_KEY",label:"OpenAI API key",type:"password",placeholder:"sk-\u2026"},{name:"LLM_OPENAI_MODEL",label:"Model (optional)",type:"text",placeholder:"gpt-4o-mini",optional:!0}],env:{LLM_PROVIDER:"openai"}},{id:"anthropic",label:"Anthropic",hint:"Direct Anthropic API access.",fields:[{name:"ANTHROPIC_API_KEY",label:"Anthropic API key",type:"password",placeholder:"sk-ant-\u2026"}],env:{LLM_PROVIDER:"anthropic"}},{id:"ollama",label:"Ollama",hint:"Local Ollama install. Free + private but slower on small machines.",fields:[{name:"LLM_OLLAMA_HOST",label:"Ollama host",type:"text",placeholder:"http://localhost:11434"},{name:"LLM_OLLAMA_MODEL",label:"Model",type:"text",placeholder:"qwen2.5:7b"}],env:{LLM_PROVIDER:"ollama"}}],MA=[{id:"openai",label:"OpenAI",hint:"text-embedding-3-large @ 1024 dimensions. Best out-of-the-box quality.",recommended:!0,fields:[{name:"OPENAI_API_KEY",label:"OpenAI API key",type:"password",placeholder:"sk-\u2026",sharedWith:"llm"}],env:{EMBEDDING_PROVIDER:"openai",EMBEDDING_MODEL:"text-embedding-3-large",EMBEDDING_DIMENSIONS:"1024"}},{id:"ollama",label:"Ollama (mxbai-embed-large)",hint:"1024-dim local embeddings. Free, no key. Lower retrieval quality than OpenAI.",fields:[{name:"OLLAMA_HOST",label:"Ollama host",type:"text",placeholder:"http://localhost:11434"}],env:{EMBEDDING_PROVIDER:"ollama",EMBEDDING_MODEL:"mxbai-embed-large",EMBEDDING_DIMENSIONS:"1024"}},{id:"openrouter",label:"OpenRouter",hint:"Uses OpenRouter as an embedding gateway. Reuses your LLM key.",fields:[{name:"OPENROUTER_API_KEY",label:"OpenRouter API key",type:"password",placeholder:"sk-or-\u2026",sharedWith:"llm"}],env:{EMBEDDING_PROVIDER:"openrouter",EMBEDDING_MODEL:"openai/text-embedding-3-large",EMBEDDING_DIMENSIONS:"1024"}}],IV=Object.fromEntries(MA.map(e=>[e.id,{model:e.env.EMBEDDING_MODEL,dimensions:Number(e.env.EMBEDDING_DIMENSIONS)}]))});var UA={};A(UA,{buildRememberRespawnArgs:()=>TV});function TV(e,t){return["remember",...e.filter(n=>n!=="--bg"&&n!=="--background"),...t]}var HA=f(()=>{});var jA={};A(jA,{closeEditingWindows:()=>kV,getLifecycleStats:()=>RV,promoteFreshFacts:()=>CV});async function CV(){let{rows:e}=await b.raw(`
1190
+ `}}}}).prompt()});var FA={};A(FA,{EMBEDDING_DEFAULTS:()=>TV,EMBEDDING_PROVIDERS:()=>MA,LLM_PROVIDERS:()=>IV});var IV,MA,TV,BA=f(()=>{IV=[{id:"claude-cli",label:"Claude Code",hint:"Uses your existing Claude Code subscription \u2014 no extra API key.",recommended:!0,fields:[],env:{LLM_PROVIDER:"claude-cli"}},{id:"openrouter",label:"OpenRouter",hint:"One API key for many models (Anthropic, OpenAI, Gemini, \u2026). Cheapest default.",fields:[{name:"OPENROUTER_API_KEY",label:"OpenRouter API key",type:"password",placeholder:"sk-or-\u2026"},{name:"LLM_OPENROUTER_MODEL",label:"Model (optional)",type:"text",placeholder:"google/gemini-flash-latest",optional:!0}],env:{LLM_PROVIDER:"openrouter"}},{id:"openai",label:"OpenAI",hint:"Direct OpenAI access. Requires sk-\u2026 key with chat + embeddings.",fields:[{name:"OPENAI_API_KEY",label:"OpenAI API key",type:"password",placeholder:"sk-\u2026"},{name:"LLM_OPENAI_MODEL",label:"Model (optional)",type:"text",placeholder:"gpt-4o-mini",optional:!0}],env:{LLM_PROVIDER:"openai"}},{id:"anthropic",label:"Anthropic",hint:"Direct Anthropic API access.",fields:[{name:"ANTHROPIC_API_KEY",label:"Anthropic API key",type:"password",placeholder:"sk-ant-\u2026"}],env:{LLM_PROVIDER:"anthropic"}},{id:"ollama",label:"Ollama",hint:"Local Ollama install. Free + private but slower on small machines.",fields:[{name:"LLM_OLLAMA_HOST",label:"Ollama host",type:"text",placeholder:"http://localhost:11434"},{name:"LLM_OLLAMA_MODEL",label:"Model",type:"text",placeholder:"qwen2.5:7b"}],env:{LLM_PROVIDER:"ollama"}}],MA=[{id:"openai",label:"OpenAI",hint:"text-embedding-3-large @ 1024 dimensions. Best out-of-the-box quality.",recommended:!0,fields:[{name:"OPENAI_API_KEY",label:"OpenAI API key",type:"password",placeholder:"sk-\u2026",sharedWith:"llm"}],env:{EMBEDDING_PROVIDER:"openai",EMBEDDING_MODEL:"text-embedding-3-large",EMBEDDING_DIMENSIONS:"1024"}},{id:"ollama",label:"Ollama (mxbai-embed-large)",hint:"1024-dim local embeddings. Free, no key. Lower retrieval quality than OpenAI.",fields:[{name:"OLLAMA_HOST",label:"Ollama host",type:"text",placeholder:"http://localhost:11434"}],env:{EMBEDDING_PROVIDER:"ollama",EMBEDDING_MODEL:"mxbai-embed-large",EMBEDDING_DIMENSIONS:"1024"}},{id:"openrouter",label:"OpenRouter",hint:"Uses OpenRouter as an embedding gateway. Reuses your LLM key.",fields:[{name:"OPENROUTER_API_KEY",label:"OpenRouter API key",type:"password",placeholder:"sk-or-\u2026",sharedWith:"llm"}],env:{EMBEDDING_PROVIDER:"openrouter",EMBEDDING_MODEL:"openai/text-embedding-3-large",EMBEDDING_DIMENSIONS:"1024"}}],TV=Object.fromEntries(MA.map(e=>[e.id,{model:e.env.EMBEDDING_MODEL,dimensions:Number(e.env.EMBEDDING_DIMENSIONS)}]))});var UA={};A(UA,{buildRememberRespawnArgs:()=>AV});function AV(e,t){return["remember",...e.filter(n=>n!=="--bg"&&n!=="--background"),...t]}var HA=f(()=>{});var jA={};A(jA,{closeEditingWindows:()=>RV,getLifecycleStats:()=>OV,promoteFreshFacts:()=>kV});async function kV(){let{rows:e}=await b.raw(`
1191
1191
  UPDATE fact_lifecycle fl
1192
1192
  SET stage = 'stable',
1193
1193
  stage_entered_at = NOW()
1194
1194
  FROM fact f
1195
1195
  WHERE fl.fact_id = f.id
1196
1196
  AND fl.stage = 'fresh'
1197
- AND fl.stage_entered_at < NOW() - INTERVAL '${AV} hours'
1197
+ AND fl.stage_entered_at < NOW() - INTERVAL '${$V} hours'
1198
1198
  AND (f.importance = 'vital' OR fl.access_count > 0)
1199
1199
  RETURNING fl.fact_id
1200
- `);return e.length}async function kV(){let{rows:e}=await b.raw(`
1200
+ `);return e.length}async function RV(){let{rows:e}=await b.raw(`
1201
1201
  UPDATE fact_lifecycle
1202
1202
  SET stage = 'stable',
1203
1203
  stage_entered_at = NOW()
1204
1204
  WHERE stage = 'editing'
1205
- AND stage_entered_at < NOW() - INTERVAL '${$V} minutes'
1205
+ AND stage_entered_at < NOW() - INTERVAL '${CV} minutes'
1206
1206
  RETURNING fact_id
1207
- `);return e.length}async function RV(){let e=await b("fact_lifecycle").select("stage").count({count:"*"}).groupBy("stage"),t={fresh:0,stable:0,editing:0};for(let r of e)t[r.stage]=Number(r.count);return t}var AV,$V,GA=f(()=>{B();AV=1,$V=30});import{resolve as OV,dirname as WA,join as Ue}from"node:path";import{fileURLToPath as NV}from"node:url";import{homedir as An}from"node:os";import{existsSync as $n,readFileSync as DV}from"node:fs";import{execSync as Li,spawn as LV}from"node:child_process";import{randomBytes as PV}from"node:crypto";import{config as zm}from"dotenv";var MV=WA(WA(NV(import.meta.url))),uu="0.0.0";try{uu=JSON.parse(DV(Ue(MV,"package.json"),"utf8")).version}catch{}var Ym=OV(process.cwd(),".env"),qm=Ue(An(),".sigil",".env");$n(Ym)&&zm({path:Ym,quiet:!0});$n(qm)&&qm!==Ym&&zm({path:qm,quiet:!0});process.env.SIGIL_AGENT||(process.env.SIGIL_AGENT="cli");var[Tn,...FV]=process.argv.slice(2),KA=`sigil \u2014 Persistent memory for your Claude sessions
1207
+ `);return e.length}async function OV(){let e=await b("fact_lifecycle").select("stage").count({count:"*"}).groupBy("stage"),t={fresh:0,stable:0,editing:0};for(let r of e)t[r.stage]=Number(r.count);return t}var $V,CV,GA=f(()=>{B();$V=1,CV=30});import{resolve as NV,dirname as WA,join as Ue}from"node:path";import{fileURLToPath as DV}from"node:url";import{homedir as An}from"node:os";import{existsSync as $n,readFileSync as LV}from"node:fs";import{execSync as Li,spawn as PV}from"node:child_process";import{randomBytes as MV}from"node:crypto";import{config as zm}from"dotenv";var FV=WA(WA(DV(import.meta.url))),uu="0.0.0";try{uu=JSON.parse(LV(Ue(FV,"package.json"),"utf8")).version}catch{}var Ym=NV(process.cwd(),".env"),qm=Ue(An(),".sigil",".env");$n(Ym)&&zm({path:Ym,quiet:!0});$n(qm)&&qm!==Ym&&zm({path:qm,quiet:!0});process.env.SIGIL_AGENT||(process.env.SIGIL_AGENT="cli");var[Tn,...BV]=process.argv.slice(2),KA=`sigil \u2014 Persistent memory for your Claude sessions
1208
1208
 
1209
1209
  Usage:
1210
1210
  sigil <command> [options]
@@ -1238,12 +1238,12 @@ Commands:
1238
1238
  Options:
1239
1239
  --help Show this help message
1240
1240
 
1241
- Run sigil <command> --help for command-specific options.`;(Tn==="--help"||Tn==="-h")&&(console.log(KA),process.exit(0));async function BV(){let{connectOrStartDaemon:e}=await Promise.resolve().then(()=>(We(),Rt)),{getGuiToken:t}=await Promise.resolve().then(()=>(ys(),Va)),{canOpenBrowser:r,openBrowser:n}=await Promise.resolve().then(()=>(Th(),Ih));process.stderr.write(`[sigil] starting daemon\u2026
1241
+ Run sigil <command> --help for command-specific options.`;(Tn==="--help"||Tn==="-h")&&(console.log(KA),process.exit(0));async function UV(){let{connectOrStartDaemon:e}=await Promise.resolve().then(()=>(We(),Rt)),{getGuiToken:t}=await Promise.resolve().then(()=>(ys(),Va)),{canOpenBrowser:r,openBrowser:n}=await Promise.resolve().then(()=>(Th(),Ih));process.stderr.write(`[sigil] starting daemon\u2026
1242
1242
  `);let i=await e({quiet:!0}),{data:o}=await i.call("ping",{});if(o.version&&uu!=="0.0.0"&&o.version!==uu){process.stderr.write(`[sigil] updating daemon ${o.version} \u2192 ${uu}\u2026
1243
1243
  `);try{await i.call("restartDaemon",{})}catch{}try{await i.close()}catch{}let{setTimeout:l}=await import("node:timers/promises");await l(900),i=await e({quiet:!0}),{data:o}=await i.call("ping",{})}let{default:s}=await Promise.resolve().then(()=>(N(),de)),a=await t(),c=`http://${s.http.host}:${s.http.port}/?t=${a}`;if(!r()){let l=!1;try{l=(await i.call("setup.state",{})).data?.complete}catch{}return await i.close(),console.log(""),console.log(` Sigil is running on this machine (pid ${o.pid}).`),console.log(` GUI URL (open from a machine with a browser): ${c}`),l?void 0:(console.log(` No display detected \u2014 continuing setup in the terminal.
1244
- `),YA([]))}await i.close(),console.log(""),console.log(" Sigil is running on this machine."),console.log(""),console.log(` PID: ${o.pid}`),console.log(` GUI: ${c}`),console.log(""),console.log(" Opening the dashboard in your browser\u2026"),console.log(" (Press Ctrl+C at any time. The daemon stays running.)"),console.log(""),n(c)}var UV={init:YA,connect:KV,setup:VV,uninstall:qV,doctor:YV,remember:nK,ingest:aK,search:cK,context:lK,preamble:uK,status:dK,facts:tK,forget:rK,namespace:JV,session:ZV,pod:XV,export:zV,maintain:fK,repair:pK,migrate:mK,reset:hK,register:iK,why:wK,kind:_K,daemon:HV,service:jV,pair:GV,join:WV};async function HV(e){let{runDaemon:t}=await Promise.resolve().then(()=>(LT(),DT));return t(e)}async function jV(e){let{runService:t}=await Promise.resolve().then(()=>(FT(),MT));return t(e)}async function GV(e){let{runPair:t}=await Promise.resolve().then(()=>(HT(),UT));return t(e)}async function WV(e){let{runJoin:t}=await Promise.resolve().then(()=>(GT(),jT));return t(e)}async function VV(e){let{runSetup:t}=await Promise.resolve().then(()=>(zT(),YT));return t(e)}var qA=Tn?UV[Tn]:async()=>{await BV(),process.exit(0)};qA||(console.error(`Unknown command: ${Tn}
1244
+ `),YA([]))}await i.close(),console.log(""),console.log(" Sigil is running on this machine."),console.log(""),console.log(` PID: ${o.pid}`),console.log(` GUI: ${c}`),console.log(""),console.log(" Opening the dashboard in your browser\u2026"),console.log(" (Press Ctrl+C at any time. The daemon stays running.)"),console.log(""),n(c)}var HV={init:YA,connect:qV,setup:KV,uninstall:YV,doctor:zV,remember:iK,ingest:cK,search:lK,context:uK,preamble:dK,status:pK,facts:rK,forget:nK,namespace:ZV,session:XV,pod:QV,export:JV,maintain:mK,repair:fK,migrate:hK,reset:gK,register:oK,why:_K,kind:bK,daemon:jV,service:GV,pair:WV,join:VV};async function jV(e){let{runDaemon:t}=await Promise.resolve().then(()=>(LT(),DT));return t(e)}async function GV(e){let{runService:t}=await Promise.resolve().then(()=>(FT(),MT));return t(e)}async function WV(e){let{runPair:t}=await Promise.resolve().then(()=>(HT(),UT));return t(e)}async function VV(e){let{runJoin:t}=await Promise.resolve().then(()=>(GT(),jT));return t(e)}async function KV(e){let{runSetup:t}=await Promise.resolve().then(()=>(zT(),YT));return t(e)}var qA=Tn?HV[Tn]:async()=>{await UV(),process.exit(0)};qA||(console.error(`Unknown command: ${Tn}
1245
1245
  `),console.log(KA),process.exit(1));if(Tn!=="doctor"&&Tn!=="export"&&Tn!=="register")try{let{getUnackedErrorCount:e}=await Promise.resolve().then(()=>(gi(),hi)),t=await e();t>0&&process.stderr.write(`\u26A0 Sigil: ${t} unacked hook error${t>1?"s":""} \u2014 run \`sigil doctor\` for details
1246
- `)}catch{}try{await qA(FV)}catch(e){let t=e instanceof AggregateError?e.errors||[]:[],r=[e.message,...t.map(i=>i?.message)].filter(Boolean).join("; ")||String(e);((e.code||t.find(i=>i?.code)?.code||"")==="3D000"||/database .* does not exist/i.test(r))&&(console.error("Error: the Sigil database does not exist yet on this Postgres server."),console.error(""),console.error("Run `sigil init` \u2014 it will create the database, the sigil_app user, and"),console.error("install pgvector for you (one-shot, requires Postgres admin credentials)."),console.error(""),console.error("Underlying error: "+r.split(`
1246
+ `)}catch{}try{await qA(BV)}catch(e){let t=e instanceof AggregateError?e.errors||[]:[],r=[e.message,...t.map(i=>i?.message)].filter(Boolean).join("; ")||String(e);((e.code||t.find(i=>i?.code)?.code||"")==="3D000"||/database .* does not exist/i.test(r))&&(console.error("Error: the Sigil database does not exist yet on this Postgres server."),console.error(""),console.error("Run `sigil init` \u2014 it will create the database, the sigil_app user, and"),console.error("install pgvector for you (one-shot, requires Postgres admin credentials)."),console.error(""),console.error("Underlying error: "+r.split(`
1247
1247
  `)[0]),process.exit(1)),/ECONNREFUSED|connection refused/i.test(r)&&(console.error("Error: Postgres is not reachable."),console.error(""),console.error("Sigil 0.10.0+ requires Postgres. Start your Postgres server first:"),console.error(" \u2022 Docker: docker run -d --name sigil-pg -p 5432:5432 -e POSTGRES_PASSWORD=\u2026 pgvector/pgvector:pg15"),console.error(" \u2022 brew: brew services start postgresql@15"),console.error(" \u2022 RDS / cloud: check the host/port in `grep SIGIL_DB_ ~/.sigil/.env`"),console.error(""),console.error("Underlying error: "+r.split(`
1248
1248
  `)[0]),process.exit(1)),/password authentication failed/i.test(r)&&(console.error("Error: Postgres rejected the Sigil credentials."),console.error(""),console.error("Re-run `sigil init` to reset the password (it will use Postgres admin"),console.error("credentials once to update the sigil_app user), or edit ~/.sigil/.env manually."),console.error(""),console.error("Underlying error: "+r.split(`
1249
1249
  `)[0]),process.exit(1)),/daemon did not become ready/i.test(r)&&(console.error(`Error: ${r}`),console.error(""),console.error('If the log shows "already running", a stale pidfile from a prior crash is'),console.error("blocking startup. Clear it and retry:"),console.error(" rm -f ~/.sigil/sigild.pid ~/.sigil/sock ~/.sigil/heartbeat.json"),process.exit(1)),console.error(`Error: ${r}`),process.exit(1)}async function YA(e){(e.includes("--help")||e.includes("-h"))&&(console.log(`sigil init \u2014 Set up Sigil (DB, env, hooks, Claude integration)
@@ -1280,11 +1280,11 @@ unsearchable until re-ingested. To stay coherent without losing data, either:
1280
1280
  \u2022 keep ${Pe} as your embedding provider, or
1281
1281
  \u2022 run \`sigil reset\` to wipe + re-ingest from scratch.`,"Dimension change ahead");let V=await m({message:`Continue with ${Q} (${ar}d)? Existing facts will become unsearchable.`,initialValue:!1});(w(V)||!V)&&(g("Setup cancelled \u2014 re-run sigil init and keep the prior embedding provider, or run sigil reset to wipe first."),process.exit(0))}}else ce=S.EMBEDDING_MODEL||ee[Q].model,ar=Number(S.EMBEDDING_DIMENSIONS)||ee[Q].dimensions;if(Q==="openrouter"&&!Ce){let R=await p({message:"OpenRouter API key (for embeddings) \u2014 get one at openrouter.ai/keys",placeholder:S.OPENROUTER_API_KEY?"(unchanged)":"sk-or-...",validate:V=>{if(!V&&!S.OPENROUTER_API_KEY)return"API key is required";if(V&&!V.startsWith("sk-or-"))return'OpenRouter keys start with "sk-or-" \u2014 check paste'}});w(R)&&(g("Setup cancelled."),process.exit(0)),R&&(Ce=R)}if(Q==="ollama"){v||(h(`Ollama is not installed.
1282
1282
  Install from https://ollama.com then run: ollama pull ${ce}
1283
- Or re-run sigil init and choose OpenAI for embeddings.`,"Ollama not found"),g("Install Ollama then re-run sigil init."),process.exit(0));let R=S.OLLAMA_HOST||"http://localhost:11434";if(t)$("check",`ollama server @ ${R}`,"start in background if not running"),$("pull",`ollama:${ce}`,"embedding model (if not already present)");else{let V=await ZA(R),te=null;if(!V){let Se=d();Se.start("Starting ollama serve in the background..."),te=bK(),V=await xK(R,15e3),V?Se.stop(`Ollama server ready (pid ${te?.pid??"?"}, background)`):(Se.stop("Ollama server did not come up in time"),h("Sigil tried to start `ollama serve` in the background but it did not\nbecome reachable at "+R+" within 15s.\n\nOpen a new terminal, run `ollama serve`, then re-run `sigil init`.","Ollama server unreachable"),g("Start ollama serve manually then re-run sigil init."),process.exit(0))}let{listCompatibleModels:le}=await Promise.resolve().then(()=>(Zf(),J0)),Oe=await le(R),ur=await l({message:"Ollama embedding model",options:Oe.map(Se=>({value:Se.name,label:`${Se.name}${Se.recommended?" (recommended)":""}`,hint:Se.installed?"installed":`pull ${Se.size}`})),initialValue:Oe.find(Se=>Se.installed)?.name||Oe.find(Se=>Se.recommended)?.name||ce});if(w(ur)&&(g("Setup cancelled."),process.exit(0)),ce=ur,!Oe.find(Se=>Se.name===ce)?.installed){let Se=d();Se.start(`Pulling ${ce}...`);try{Li(`ollama pull ${ce}`,{stdio:"pipe"}),Se.stop(`${ce} ready`)}catch{Se.stop(`Pull failed \u2014 run: ollama pull ${ce} manually`)}}te&&te.unref()}}let du=await p({message:"Default namespace",placeholder:"default",initialValue:S.DEFAULT_NAMESPACE||"default",validate:R=>{if(!R.trim())return"Cannot be empty"}});w(du)&&(g("Setup cancelled."),process.exit(0));let Cn="local",cr=null,Re=null,Cr,kr,lr,kn,Oa;if(n)Cn="url",cr=n;else if(S.SIGIL_DATABASE_URL&&!S.SIGIL_DB_HOST){let R=await l({message:"Database mode",options:[{value:"url",label:"Connection URL",hint:"keep current SIGIL_DATABASE_URL"},{value:"local",label:"Local Postgres install",hint:"discrete host/port/user/password"}],initialValue:"url"});w(R)&&(g("Setup cancelled."),process.exit(0)),Cn=R}else{let R=await l({message:"Database mode",options:[{value:"local",label:"Local Postgres install",hint:"docker / brew / RDS host:port"},{value:"url",label:"Connection URL",hint:"Neon, Supabase, RDS, Render, \u2026"}],initialValue:(S.SIGIL_DB_HOST,"local")});w(R)&&(g("Setup cancelled."),process.exit(0)),Cn=R}if(Cn==="url"){if(cr||(cr=await p({message:"Postgres connection URL",placeholder:S.SIGIL_DATABASE_URL||"postgres://user:pass@host.neon.tech/db",initialValue:S.SIGIL_DATABASE_URL||"",validate:R=>{if(!/^postgres(ql)?:\/\//i.test(R||""))return"Must start with postgres:// or postgresql://"}}),w(cr)&&(g("Setup cancelled."),process.exit(0))),!t){let{probeUrlConnection:R}=await Promise.resolve().then(()=>(qe(),Pn)),V=d();if(V.start("Probing connection URL..."),Re=await R(cr),Re.ok||(V.stop(`Connection failed (${Re.stage}${Re.code?`: ${Re.code}`:""})`),g(`Could not connect: ${Re.error}
1283
+ Or re-run sigil init and choose OpenAI for embeddings.`,"Ollama not found"),g("Install Ollama then re-run sigil init."),process.exit(0));let R=S.OLLAMA_HOST||"http://localhost:11434";if(t)$("check",`ollama server @ ${R}`,"start in background if not running"),$("pull",`ollama:${ce}`,"embedding model (if not already present)");else{let V=await ZA(R),te=null;if(!V){let Se=d();Se.start("Starting ollama serve in the background..."),te=xK(),V=await EK(R,15e3),V?Se.stop(`Ollama server ready (pid ${te?.pid??"?"}, background)`):(Se.stop("Ollama server did not come up in time"),h("Sigil tried to start `ollama serve` in the background but it did not\nbecome reachable at "+R+" within 15s.\n\nOpen a new terminal, run `ollama serve`, then re-run `sigil init`.","Ollama server unreachable"),g("Start ollama serve manually then re-run sigil init."),process.exit(0))}let{listCompatibleModels:le}=await Promise.resolve().then(()=>(Zf(),J0)),Oe=await le(R),ur=await l({message:"Ollama embedding model",options:Oe.map(Se=>({value:Se.name,label:`${Se.name}${Se.recommended?" (recommended)":""}`,hint:Se.installed?"installed":`pull ${Se.size}`})),initialValue:Oe.find(Se=>Se.installed)?.name||Oe.find(Se=>Se.recommended)?.name||ce});if(w(ur)&&(g("Setup cancelled."),process.exit(0)),ce=ur,!Oe.find(Se=>Se.name===ce)?.installed){let Se=d();Se.start(`Pulling ${ce}...`);try{Li(`ollama pull ${ce}`,{stdio:"pipe"}),Se.stop(`${ce} ready`)}catch{Se.stop(`Pull failed \u2014 run: ollama pull ${ce} manually`)}}te&&te.unref()}}let du=await p({message:"Default namespace",placeholder:"default",initialValue:S.DEFAULT_NAMESPACE||"default",validate:R=>{if(!R.trim())return"Cannot be empty"}});w(du)&&(g("Setup cancelled."),process.exit(0));let Cn="local",cr=null,Re=null,Cr,kr,lr,kn,Oa;if(n)Cn="url",cr=n;else if(S.SIGIL_DATABASE_URL&&!S.SIGIL_DB_HOST){let R=await l({message:"Database mode",options:[{value:"url",label:"Connection URL",hint:"keep current SIGIL_DATABASE_URL"},{value:"local",label:"Local Postgres install",hint:"discrete host/port/user/password"}],initialValue:"url"});w(R)&&(g("Setup cancelled."),process.exit(0)),Cn=R}else{let R=await l({message:"Database mode",options:[{value:"local",label:"Local Postgres install",hint:"docker / brew / RDS host:port"},{value:"url",label:"Connection URL",hint:"Neon, Supabase, RDS, Render, \u2026"}],initialValue:(S.SIGIL_DB_HOST,"local")});w(R)&&(g("Setup cancelled."),process.exit(0)),Cn=R}if(Cn==="url"){if(cr||(cr=await p({message:"Postgres connection URL",placeholder:S.SIGIL_DATABASE_URL||"postgres://user:pass@host.neon.tech/db",initialValue:S.SIGIL_DATABASE_URL||"",validate:R=>{if(!/^postgres(ql)?:\/\//i.test(R||""))return"Must start with postgres:// or postgresql://"}}),w(cr)&&(g("Setup cancelled."),process.exit(0))),!t){let{probeUrlConnection:R}=await Promise.resolve().then(()=>(qe(),Pn)),V=d();if(V.start("Probing connection URL..."),Re=await R(cr),Re.ok||(V.stop(`Connection failed (${Re.stage}${Re.code?`: ${Re.code}`:""})`),g(`Could not connect: ${Re.error}
1284
1284
  `+(Re.stage==="parse"?" Check the URL format (postgres://user:pass@host:port/db?sslmode=...)":"")+(Re.stage==="connect"?` Provider hint: ${Re.provider}. For Neon use the pooler URL.`:"")+(Re.stage==="query"?" Connection succeeded but a basic SELECT failed \u2014 check user privileges.":"")),process.exit(1)),Re.pgvector)V.stop(`Connected (${Re.provider}, ${Re.connectMs}ms) \u2014 pgvector \u2713`);else{V.stop(`Connected (${Re.provider}, ${Re.connectMs}ms) \u2014 pgvector NOT installed`);let te=await m({message:"pgvector extension is not installed on this database. Sigil cannot run without it. Continue anyway?",initialValue:!1});(w(te)||!te)&&(g(`Cancelled. Install pgvector on your database first:
1285
1285
  `+(Re.provider==="neon"?" Neon: extensions are auto-enabled, but the role may need the right privileges":"")+(Re.provider.startsWith("supabase")?" Supabase: enable via Dashboard \u2192 Database \u2192 Extensions \u2192 vector":"")+(Re.provider==="aws-rds"?" RDS: add `vector` to the parameter group `shared_preload_libraries`":"")+`
1286
1286
  Then re-run sigil init.`),process.exit(1))}}}else{let R=await p({message:"Postgres host",placeholder:S.SIGIL_DB_HOST||"localhost",initialValue:S.SIGIL_DB_HOST||"localhost"});w(R)&&(g("Setup cancelled."),process.exit(0)),Cr=R;let V=await p({message:"Postgres port",placeholder:S.SIGIL_DB_PORT||"5432",initialValue:S.SIGIL_DB_PORT||"5432",validate:ur=>{if(ur&&!/^\d+$/.test(ur))return"Port must be a number"}});w(V)&&(g("Setup cancelled."),process.exit(0)),kr=Number(V);let te=await p({message:"Sigil database name",placeholder:S.SIGIL_DB_NAME||"sigil",initialValue:S.SIGIL_DB_NAME||"sigil"});w(te)&&(g("Setup cancelled."),process.exit(0)),lr=te;let le=await p({message:"Sigil database user",placeholder:S.SIGIL_DB_USER||"sigil_app",initialValue:S.SIGIL_DB_USER||"sigil_app"});w(le)&&(g("Setup cancelled."),process.exit(0)),kn=le;let Oe=await p({message:S.SIGIL_DB_PASSWORD?"Sigil database password (keep existing \u2014 press Enter)":"Sigil database password",placeholder:S.SIGIL_DB_PASSWORD?"(unchanged)":"sigil_dev or generate",validate:ur=>{if(!ur&&!S.SIGIL_DB_PASSWORD)return"Password required"}});if(w(Oe)&&(g("Setup cancelled."),process.exit(0)),Oa=Oe||S.SIGIL_DB_PASSWORD,!t){let{probeSigilConnection:ur,ensurePostgresDatabase:th,diagnoseConnectionError:Se}=await Promise.resolve().then(()=>(qe(),Pn)),fu=d();fu.start("Probing Postgres connection...");let mu=await ur({host:Cr,port:kr,database:lr,user:kn,password:Oa});if(mu.ok)fu.stop(`Connected to ${kn}@${Cr}:${kr}/${lr}`);else{let Rn=Se({code:mu.code,message:mu.message});if(fu.stop(`Connection failed (${Rn.kind})`),Rn.kind==="unreachable"&&(g(`Postgres unreachable at ${Cr}:${kr}.
1287
- ${Rn.hint}`),process.exit(1)),Rn.kind==="missing-db"||Rn.kind==="auth"){let rh=await m({message:Rn.kind==="missing-db"?`Database "${lr}" does not exist. Create it now (requires admin credentials)?`:`Authentication failed for ${kn}@${lr}. Create / reset the user now (requires admin credentials)?`,initialValue:!0});(w(rh)||!rh)&&(g("Setup cancelled \u2014 fix Postgres credentials and re-run sigil init."),process.exit(0));let nh=await p({message:"Postgres admin user",placeholder:"postgres",initialValue:"postgres"});w(nh)&&(g("Setup cancelled."),process.exit(0));let ih=await p({message:"Postgres admin password (used once, not stored)",placeholder:"admin password",validate:cs=>{if(!cs)return"Required to create the database"}});w(ih)&&(g("Setup cancelled."),process.exit(0));let hu=d();hu.start("Creating database, user, and pgvector extension...");try{let{actions:cs}=await th({admin:{host:Cr,port:kr,user:nh,password:ih},sigil:{database:lr,user:kn,password:Oa}});hu.stop(`Bootstrapped: ${cs.join(", ")}`)}catch(cs){hu.stop("Bootstrap failed"),g(cs.message),process.exit(1)}}else g(`Postgres setup failed: ${Rn.hint}`),process.exit(1)}}}t||await o.mkdir(_,{recursive:!0});let XA=S.SIGIL_ENCRYPTION_KEY||EK(64),we={...S};we.LLM_PROVIDER=D,we.OLLAMA_HOST=S.OLLAMA_HOST||"http://localhost:11434",Object.assign(we,pe),we.EMBEDDING_PROVIDER=Q,we.EMBEDDING_MODEL=ce,we.EMBEDDING_DIMENSIONS=String(ar),we.DEFAULT_NAMESPACE=du,we.SIGIL_ENCRYPTION_KEY=XA,we.SIGIL_DB_TYPE="postgres",we.SIGIL_SETUP_COMPLETE="true",Cn==="url"?(we.SIGIL_DATABASE_URL=cr,delete we.SIGIL_DB_HOST,delete we.SIGIL_DB_PORT,delete we.SIGIL_DB_NAME,delete we.SIGIL_DB_USER,delete we.SIGIL_DB_PASSWORD):(delete we.SIGIL_DATABASE_URL,we.SIGIL_DB_HOST=Cr,we.SIGIL_DB_PORT=String(kr),we.SIGIL_DB_NAME=lr,we.SIGIL_DB_USER=kn,we.SIGIL_DB_PASSWORD=Oa);let QA=[`# Sigil \u2014 generated ${new Date().toISOString().slice(0,10)}`,"# (re-running `sigil init` preserves unrecognised keys \u2014 edit manually as needed)","",...Object.entries(we).map(([R,V])=>`${R}=${V}`)].join(`
1287
+ ${Rn.hint}`),process.exit(1)),Rn.kind==="missing-db"||Rn.kind==="auth"){let rh=await m({message:Rn.kind==="missing-db"?`Database "${lr}" does not exist. Create it now (requires admin credentials)?`:`Authentication failed for ${kn}@${lr}. Create / reset the user now (requires admin credentials)?`,initialValue:!0});(w(rh)||!rh)&&(g("Setup cancelled \u2014 fix Postgres credentials and re-run sigil init."),process.exit(0));let nh=await p({message:"Postgres admin user",placeholder:"postgres",initialValue:"postgres"});w(nh)&&(g("Setup cancelled."),process.exit(0));let ih=await p({message:"Postgres admin password (used once, not stored)",placeholder:"admin password",validate:cs=>{if(!cs)return"Required to create the database"}});w(ih)&&(g("Setup cancelled."),process.exit(0));let hu=d();hu.start("Creating database, user, and pgvector extension...");try{let{actions:cs}=await th({admin:{host:Cr,port:kr,user:nh,password:ih},sigil:{database:lr,user:kn,password:Oa}});hu.stop(`Bootstrapped: ${cs.join(", ")}`)}catch(cs){hu.stop("Bootstrap failed"),g(cs.message),process.exit(1)}}else g(`Postgres setup failed: ${Rn.hint}`),process.exit(1)}}}t||await o.mkdir(_,{recursive:!0});let XA=S.SIGIL_ENCRYPTION_KEY||vK(64),we={...S};we.LLM_PROVIDER=D,we.OLLAMA_HOST=S.OLLAMA_HOST||"http://localhost:11434",Object.assign(we,pe),we.EMBEDDING_PROVIDER=Q,we.EMBEDDING_MODEL=ce,we.EMBEDDING_DIMENSIONS=String(ar),we.DEFAULT_NAMESPACE=du,we.SIGIL_ENCRYPTION_KEY=XA,we.SIGIL_DB_TYPE="postgres",we.SIGIL_SETUP_COMPLETE="true",Cn==="url"?(we.SIGIL_DATABASE_URL=cr,delete we.SIGIL_DB_HOST,delete we.SIGIL_DB_PORT,delete we.SIGIL_DB_NAME,delete we.SIGIL_DB_USER,delete we.SIGIL_DB_PASSWORD):(delete we.SIGIL_DATABASE_URL,we.SIGIL_DB_HOST=Cr,we.SIGIL_DB_PORT=String(kr),we.SIGIL_DB_NAME=lr,we.SIGIL_DB_USER=kn,we.SIGIL_DB_PASSWORD=Oa);let QA=[`# Sigil \u2014 generated ${new Date().toISOString().slice(0,10)}`,"# (re-running `sigil init` preserves unrecognised keys \u2014 edit manually as needed)","",...Object.entries(we).map(([R,V])=>`${R}=${V}`)].join(`
1288
1288
  `),Zm=await s(E,QA,{dryRun:t});if($(Zm.action,E,`${Zm.bytes} bytes`),t){let R=Cn==="url"?`connection URL (${cr?new URL(cr).hostname:"\u2014"})`:`${Cr}:${kr}/${lr}`;$("migrate","postgres",R),$("verify","embedder",`${Q}/${ce} \u2014 live ping (skipped in dry-run)`)}else{zm({path:E,override:!0,quiet:!0});let R=d();R.start("Initialising memory database...");try{let{MIGRATIONS_DIR:te}=await Promise.resolve().then(()=>(K(),Ma)),le=(await Promise.resolve().then(()=>(B(),se))).default,[,Oe]=await le.migrate.latest({directory:te});R.stop(Oe.length?`Memory database ready (${Oe.length} tables created)`:"Memory database up to date")}catch(te){R.stop("Database setup failed");let{diagnoseError:le}=await Promise.resolve().then(()=>(qe(),Pn)),Oe=le(te);g(`${Oe.humanMessage}
1289
1289
  `+(Oe.fixHint?`
1290
1290
  \u2192 ${Oe.fixHint}
@@ -1301,7 +1301,7 @@ This means ${Q}/${ce} doesn't produce ${ar}d embeddings \u2014 one of them is wr
1301
1301
  Your config was written to `+E+` \u2014 fix the root cause then re-run sigil init.
1302
1302
  Sigil init aborted before any AI clients were touched \u2014 your existing setup is unchanged.`),process.exit(1)}}let{listClients:e$}=await Promise.resolve().then(()=>(Si(),es)),Na=await e$(),Xm=await Promise.all(Na.map(R=>R.detect())),Qm=Na.filter((R,V)=>Xm[V]).map(R=>R.id),Pi=await u({message:"Install Sigil for which clients? (space to toggle, enter to confirm)",options:Na.map((R,V)=>({value:R.id,label:R.label,hint:Xm[V]?`${R.hint} \u2014 detected`:R.hint})),initialValues:Qm.length?Qm:["claude-code"],required:!1});w(Pi)&&(g("Setup cancelled."),process.exit(0));let eh=d();eh.start(t?"Computing client integration plan...":"Configuring client integrations...");for(let R of Pi){let V=Na.find(le=>le.id===R),{actions:te}=await V.install({dryRun:t});for(let le of te)$(le.action,le.path,le.detail)}if(!t){let{updateContextSnapshot:R}=await Promise.resolve().then(()=>(an(),sn));await R({namespace:du.toString()}).catch(()=>{})}if(eh.stop(t?"Plan computed.":Pi.length?`Configured ${Pi.length} client${Pi.length>1?"s":""}: ${Pi.join(", ")}`:"No clients selected \u2014 skipping integration step"),t){let R=I.map(V=>` ${Jm(V.action,8)} ${V.path}${V.detail?` (${V.detail})`:""}`);h(["Dry run \u2014 no files were written. The following would happen:","",...R,"","Each existing file would be backed up to <path>.sigil.bak before its first","modification. Re-run without --dry-run to apply."].join(`
1303
1303
  `),"Plan"),c("Dry run complete.");return}let pu;if(Cn==="url"){let R="(connection url)";try{R=new URL(cr).host}catch{}pu=`Postgres ${R} (via SIGIL_DATABASE_URL)`}else pu=`Postgres ${kn}@${Cr}:${kr}/${lr}`;h([pu,`Config ${E}`,"Claude ~/.claude/CLAUDE.md \u2014 Sigil is now your memory","Backups any pre-existing files saved to <path>.sigil.bak","","Claude will search Sigil before answering and save important","facts automatically. Start a new Claude session to begin.","","Quick start:",' sigil remember "your first fact"'," sigil ingest <file-or-url>",' sigil search "anything"'].join(`
1304
- `),"Setup complete"),c("Open a new Claude Code session to start using Sigil."),process.exit(0)}function Jm(e,t){return String(e).padEnd(t)}async function KV(e){(e.includes("--help")||e.includes("-h"))&&(console.log(`sigil connect \u2014 (Re)register Sigil with your AI clients
1304
+ `),"Setup complete"),c("Open a new Claude Code session to start using Sigil."),process.exit(0)}function Jm(e,t){return String(e).padEnd(t)}async function qV(e){(e.includes("--help")||e.includes("-h"))&&(console.log(`sigil connect \u2014 (Re)register Sigil with your AI clients
1305
1305
 
1306
1306
  Usage:
1307
1307
  sigil connect [--clients <a,b,...>] [--all] [--dry-run]
@@ -1320,7 +1320,7 @@ Options:
1320
1320
 
1321
1321
  Non-interactive: with --clients/--all, or when stdin is not a TTY, the picker is
1322
1322
  skipped (agent/CI-friendly).`),process.exit(0));let t=e.includes("--dry-run"),r=e.includes("--all"),n={claude:"claude-code","claude-code":"claude-code",cursor:"cursor",codex:"codex-cli","codex-cli":"codex-cli",kiro:"kiro",hermes:"hermes"},i=null,o=e.findIndex(D=>D==="--clients"||D.startsWith("--clients="));o!==-1&&(i=((e[o].includes("=")?e[o].split("=").slice(1).join("="):e[o+1])||"").split(",").map(J=>J.trim()).filter(Boolean).map(J=>n[J.toLowerCase()]||J.toLowerCase()));let s=await Promise.resolve().then(()=>(Ra(),ka)),{intro:a,outro:c,multiselect:l,spinner:u,note:p,cancel:d,isCancel:m}=s;a(t?"Sigil connect \u2014 DRY RUN (no files will be written)":"Sigil connect");let{writeLauncherShim:h}=await Promise.resolve().then(()=>(fn(),hf)),g=await h({dryRun:t}),{listClients:w}=await Promise.resolve().then(()=>(Si(),es)),_=await w(),E=new Set(_.map(D=>D.id)),I=await Promise.all(_.map(D=>D.detect())),$=_.filter((D,J)=>I[J]).map(D=>D.id),v;if(i){let D=i.filter(J=>!E.has(J));D.length&&(d(`Unknown client id(s): ${D.join(", ")}. Valid: ${[...E].join(", ")}.`),process.exit(1)),v=i}else r||!process.stdin.isTTY?(v=$,v.length||(p("No AI clients detected. Shims were re-pinned; install a client, then re-run `sigil connect` (or pass --clients).","Nothing to connect"),c("Done."),process.exit(0))):(v=await l({message:"(Re)connect Sigil for which clients? (space to toggle, enter to confirm)",options:_.map((D,J)=>({value:D.id,label:D.label,hint:I[J]?`${D.hint} \u2014 detected`:D.hint})),initialValues:$.length?$:["claude-code"],required:!1}),m(v)&&(d("Connect cancelled."),process.exit(0)));let S=g.actions.map(D=>({client:"shim",...D})),L=u();L.start(t?"Computing connect plan...":"Re-syncing client integrations...");for(let D of v){let J=_.find(pe=>pe.id===D),{actions:G}=await J.install({dryRun:t});for(let pe of G)S.push({client:J.label,...pe})}if(!t){let{updateContextSnapshot:D}=await Promise.resolve().then(()=>(an(),sn));await D({}).catch(()=>{})}L.stop(t?"Plan computed.":`Connected ${v.length} client${v.length===1?"":"s"}: ${v.join(", ")}`);let F=S.map(D=>` ${Jm(D.action,8)} [${D.client}] ${D.path}${D.detail?` (${D.detail})`:""}`);p(F.join(`
1323
- `)||"(no changes)",t?"Plan":"Re-synced"),c(t?"Dry run complete. Re-run without --dry-run to apply.":"Done. Open a new agent session to pick up the refreshed integration."),process.exit(0)}async function qV(e){(e.includes("--help")||e.includes("-h"))&&(console.log(`sigil uninstall \u2014 Remove Sigil's entries from AI clients
1323
+ `)||"(no changes)",t?"Plan":"Re-synced"),c(t?"Dry run complete. Re-run without --dry-run to apply.":"Done. Open a new agent session to pick up the refreshed integration."),process.exit(0)}async function YV(e){(e.includes("--help")||e.includes("-h"))&&(console.log(`sigil uninstall \u2014 Remove Sigil's entries from AI clients
1324
1324
 
1325
1325
  Usage:
1326
1326
  sigil uninstall [--dry-run]
@@ -1336,7 +1336,7 @@ Use 'sigil reset' for a full wipe.
1336
1336
 
1337
1337
  Options:
1338
1338
  --dry-run Show what would be removed without writing anything.`),process.exit(0));let t=e.includes("--dry-run"),r=await Promise.resolve().then(()=>(Ra(),ka)),{intro:n,outro:i,multiselect:o,spinner:s,note:a,cancel:c,isCancel:l}=r;n(t?"Sigil uninstall \u2014 DRY RUN (no files will be written)":"Sigil uninstall");let{listClients:u}=await Promise.resolve().then(()=>(Si(),es)),p=await u(),d=[];for(let _ of p){if(!await _.detect())continue;let{installed:E}=await _.verify();E&&d.push(_)}if(d.length===0){a("No clients have Sigil installed \u2014 nothing to remove.","Nothing to do"),i("Done.");return}let m=await o({message:"Remove Sigil from which clients? (space to toggle, enter to confirm)",options:d.map(_=>({value:_.id,label:_.label,hint:_.hint})),initialValues:d.map(_=>_.id),required:!1});if(l(m)&&(c("Uninstall cancelled."),process.exit(0)),m.length===0){i("Nothing selected \u2014 nothing removed.");return}let h=[],g=s();g.start(t?"Computing uninstall plan...":"Removing Sigil entries...");for(let _ of m){let E=d.find($=>$.id===_),{actions:I}=await E.uninstall({dryRun:t});for(let $ of I)h.push({client:E.label,...$})}g.stop(t?"Plan computed.":`Removed from ${m.length} client${m.length>1?"s":""}`);let w=h.map(_=>` ${Jm(_.action,8)} [${_.client}] ${_.path}${_.detail?` (${_.detail})`:""}`);a(w.join(`
1339
- `)||"(no changes)",t?"Plan":"Done"),i(t?"Dry run complete. Re-run without --dry-run to apply.":"Sigil entries removed. Your stored memory is unchanged \u2014 use `sigil reset` to wipe data too.")}async function YV(e){e.includes("--help")&&(console.log(`sigil doctor \u2014 Diagnose Sigil setup
1339
+ `)||"(no changes)",t?"Plan":"Done"),i(t?"Dry run complete. Re-run without --dry-run to apply.":"Sigil entries removed. Your stored memory is unchanged \u2014 use `sigil reset` to wipe data too.")}async function zV(e){e.includes("--help")&&(console.log(`sigil doctor \u2014 Diagnose Sigil setup
1340
1340
 
1341
1341
  Usage:
1342
1342
  sigil doctor [--deep]
@@ -1353,7 +1353,7 @@ Sigil diagnostic
1353
1353
  `)[0]}`:"not configured \u2014 run `sigil init`")}catch(c){n("warn","Providers",`live probe failed: ${c.message.split(`
1354
1354
  `)[0]}`)}try{let{spoolCount:c}=await Promise.resolve().then(()=>(Ta(),Ia)),l=c();l===0?n("ok","Stop-hook spool","empty"):n("warn","Stop-hook spool",`${l} unsaved turn${l>1?"s":""} pending \u2014 restart the daemon or run \`sigil repair embeddings\` to replay`)}catch(c){n("warn","Stop-hook spool",`unreadable: ${c.message}`)}try{let{listClients:c}=await Promise.resolve().then(()=>(Si(),es)),l=await c(),u=0;for(let p of l){if(!await p.detect())continue;u++;let d=await p.verify({deep:t});d.installed?n("ok",`${p.label} integration`,t?"configured + round-trip ok":"configured"):n("warn",`${p.label} integration`,`${d.reason} \u2014 run 'sigil init' to refresh`)}u===0&&n("warn","Client integrations","no AI clients detected (Claude Code / Cursor / Codex / Kiro)")}catch(c){n("warn","Client integrations",`check failed: ${c.message}`)}let o=Ue(An(),".sigil","CLAUDE.md");$n(o)?n("ok","Sigil CLAUDE.md",o):n("warn","Sigil CLAUDE.md","not found \u2014 run 'sigil init'");try{let{readRecentHookErrors:c,getUnackedErrorCount:l,HOOK_ERROR_LOG:u}=await Promise.resolve().then(()=>(gi(),hi)),p=await c(100),d=await l();if(p.length===0)n("ok","Hook errors",`none in ${u}`);else if(d>5){n("fail","Hook errors",`${d} unacked errors since last clean doctor (budget: \u22645) \u2014 see ${u}`);for(let m of p.slice(-5))console.log(` ${m.ts} [${m.hook}] ${(m.error||"").split(`
1355
1355
  `)[0].slice(0,160)}`)}else if(d>0){n("warn","Hook errors",`${d} unacked / ${p.length} total \u2014 see ${u}`);for(let m of p.slice(-3))console.log(` ${m.ts} [${m.hook}] ${(m.error||"").split(`
1356
- `)[0].slice(0,160)}`)}else n("ok","Hook errors",`${p.length} historical errors, all acked`)}catch(c){n("warn","Hook errors",`unreadable: ${c.message}`)}console.log();let s=r.filter(c=>c.status==="fail").length,a=r.filter(c=>c.status==="warn").length;if(s)console.log(`${s} error${s>1?"s":""}, ${a} warning${a!==1?"s":""}`),process.exit(1);else if(a){console.log(`All critical checks passed. ${a} warning${a>1?"s":""}.`);try{let{markDoctorClean:c}=await Promise.resolve().then(()=>(gi(),hi));await c()}catch{}}else{console.log("All checks passed.");try{let{markDoctorClean:c}=await Promise.resolve().then(()=>(gi(),hi));await c()}catch{}}}async function zV(e){e.includes("--help")&&(console.log(`sigil export \u2014 Export knowledge base to stdout or a file
1356
+ `)[0].slice(0,160)}`)}else n("ok","Hook errors",`${p.length} historical errors, all acked`)}catch(c){n("warn","Hook errors",`unreadable: ${c.message}`)}console.log();let s=r.filter(c=>c.status==="fail").length,a=r.filter(c=>c.status==="warn").length;if(s)console.log(`${s} error${s>1?"s":""}, ${a} warning${a!==1?"s":""}`),process.exit(1);else if(a){console.log(`All critical checks passed. ${a} warning${a>1?"s":""}.`);try{let{markDoctorClean:c}=await Promise.resolve().then(()=>(gi(),hi));await c()}catch{}}else{console.log("All checks passed.");try{let{markDoctorClean:c}=await Promise.resolve().then(()=>(gi(),hi));await c()}catch{}}}async function JV(e){e.includes("--help")&&(console.log(`sigil export \u2014 Export knowledge base to stdout or a file
1357
1357
 
1358
1358
  Usage:
1359
1359
  sigil export [options] [> file]
@@ -1363,18 +1363,18 @@ Options:
1363
1363
  --format=<fmt> Output format: json (default) or markdown
1364
1364
  --output=<path> Write to file instead of stdout`),process.exit(0));let t=await import("node:fs/promises"),{listFacts:r}=await Promise.resolve().then(()=>(ir(),en)),n=(await Promise.resolve().then(()=>(N(),de))).default,i=(await Promise.resolve().then(()=>(B(),se))).default,o=e.find(d=>d.startsWith("--namespace="))?.split("=")[1]||n.defaults.namespace,s=e.find(d=>d.startsWith("--format="))?.split("=")[1]||"json",a=e.find(d=>d.startsWith("--output="))?.split("=")[1],c=await r({namespace:o,limit:1e4}),l=await i("entity").where({namespace:o}),u=await i("document").where({namespace:o}),p;if(s==="markdown"){let d=[`# Sigil export \u2014 namespace: ${o}`,`Generated: ${new Date().toISOString()}`,""];d.push(`## Facts (${c.length})`,"");for(let m of c){let h=m.importance==="vital"?" **[VITAL]**":"";d.push(`- **[${m.category}]**${h} ${m.content} *(${m.confidence})*`)}d.push("",`## Entities (${l.length})`,"");for(let m of l)d.push(`- **${m.name}** (${m.entityType})${m.description?` \u2014 ${m.description}`:""}`);d.push("",`## Documents (${u.length})`,"");for(let m of u)d.push(`- ${m.title} (${m.sourcePath})`);p=d.join(`
1365
1365
  `)}else p=JSON.stringify({namespace:o,exportedAt:new Date().toISOString(),facts:c.map(d=>({uid:d.uid,content:d.content,category:d.category,confidence:d.confidence,importance:d.importance,createdAt:d.createdAt})),entities:l.map(d=>({uid:d.uid,name:d.name,type:d.entityType,description:d.description,mentionCount:d.mentionCount})),documents:u.map(d=>({sourcePath:d.sourcePath,title:d.title,sourceType:d.sourceType,chunkCount:d.chunkCount,factCount:d.factCount}))},null,2);a?(await t.writeFile(a,p,"utf8"),console.log(`Exported ${c.length} facts, ${l.length} entities, ${u.length} documents to ${a}`)):process.stdout.write(p+`
1366
- `),await i.destroy()}async function JV(e){let t=e[0];(!t||e.includes("--help"))&&(console.log(`sigil namespace \u2014 Manage namespaces
1366
+ `),await i.destroy()}async function ZV(e){let t=e[0];(!t||e.includes("--help"))&&(console.log(`sigil namespace \u2014 Manage namespaces
1367
1367
 
1368
1368
  Usage:
1369
1369
  sigil namespace list
1370
1370
  sigil namespace delete <ns> [--confirm]
1371
1371
 
1372
- Namespaces isolate facts. A project, team, or context each gets its own.`),process.exit(t?0:1));let{listNamespaces:r,deleteNamespace:n}=await Promise.resolve().then(()=>(ir(),en)),i=(await Promise.resolve().then(()=>(B(),se))).default;if(t==="list"){let o=await r();if(!o.length)console.log("No namespaces with facts.");else{console.log("Namespaces:");for(let{namespace:s,factCount:a}of o)console.log(` ${s.padEnd(30)} ${a} fact${a===1?"":"s"}`)}}else if(t==="delete"){let o=e[1];(!o||o.startsWith("--"))&&(console.error("Provide a namespace: sigil namespace delete <ns> --confirm"),await i.destroy(),process.exit(1)),e.includes("--confirm")||(console.error(`This will delete ALL data in namespace "${o}". Run with --confirm to proceed.`),await i.destroy(),process.exit(1));let s=await n(o);console.log(`Deleted namespace "${o}":`),console.log(` ${s.factsDeleted} facts, ${s.chunksDeleted} chunks, ${s.docsDeleted} documents, ${s.entitiesDeleted} entities`)}else console.error(`Unknown subcommand: ${t}`),await i.destroy(),process.exit(1);await i.destroy()}async function ZV(e){let t=e[0];(!t||e.includes("--help"))&&(console.log(`sigil session \u2014 Inspect the active Claude Code session pod
1372
+ Namespaces isolate facts. A project, team, or context each gets its own.`),process.exit(t?0:1));let{listNamespaces:r,deleteNamespace:n}=await Promise.resolve().then(()=>(ir(),en)),i=(await Promise.resolve().then(()=>(B(),se))).default;if(t==="list"){let o=await r();if(!o.length)console.log("No namespaces with facts.");else{console.log("Namespaces:");for(let{namespace:s,factCount:a}of o)console.log(` ${s.padEnd(30)} ${a} fact${a===1?"":"s"}`)}}else if(t==="delete"){let o=e[1];(!o||o.startsWith("--"))&&(console.error("Provide a namespace: sigil namespace delete <ns> --confirm"),await i.destroy(),process.exit(1)),e.includes("--confirm")||(console.error(`This will delete ALL data in namespace "${o}". Run with --confirm to proceed.`),await i.destroy(),process.exit(1));let s=await n(o);console.log(`Deleted namespace "${o}":`),console.log(` ${s.factsDeleted} facts, ${s.chunksDeleted} chunks, ${s.docsDeleted} documents, ${s.entitiesDeleted} entities`)}else console.error(`Unknown subcommand: ${t}`),await i.destroy(),process.exit(1);await i.destroy()}async function XV(e){let t=e[0];(!t||e.includes("--help"))&&(console.log(`sigil session \u2014 Inspect the active Claude Code session pod
1373
1373
 
1374
1374
  Usage:
1375
1375
  sigil session current Show active session uid + summary
1376
1376
  sigil session list [--limit=10] List recent session pods
1377
- sigil session show [<uid>] Detailed view (defaults to active)`),process.exit(t?0:1));let r=(await Promise.resolve().then(()=>(B(),se))).default;try{if(t==="current"){let{getActiveCursor:n}=await Promise.resolve().then(()=>(mi(),Ho)),i=await n();if(!i){console.log("No active session.");return}let o=await(await Promise.resolve().then(()=>(Qe(),at))).findByUid(i.pod_uid);if(!o){console.log(`Cursor points to ${i.pod_uid} but pod row not found.`);return}let a=(await Promise.resolve().then(()=>(ol(),Np))).formatForDisplay(o);console.log(`Active session: ${o.uid}`),console.log(` session_id: ${a.sessionId}`),console.log(` started_at: ${o.startedAt}`),console.log(` turn_count: ${a.turnCount}`),console.log(` cwd: ${a.cwd||"\u2014"}`),console.log(` transcript: ${a.transcriptPath||"\u2014"}`),console.log(` facts in pod: ${o.memberFactCount}`),console.log(` docs in pod: ${o.memberDocCount}`)}else if(t==="list"){let n=Number(mt(e,"--limit")||10),i=await(await Promise.resolve().then(()=>(Qe(),at))).listPods({podType:"claude_session",limit:n});if(!i.length){console.log("No session pods.");return}for(let o of i){let s=o.endedAt?o.endedAt.toISOString().slice(0,16).replace("T"," "):"active";console.log(` ${o.uid} ${o.name.padEnd(40)} facts=${o.memberFactCount} ${s}`)}}else if(t==="show"){let n=e[1];if(!n){let{getActiveCursor:i}=await Promise.resolve().then(()=>(mi(),Ho));n=(await i())?.pod_uid,n||(console.log("No active session. Pass a uid: sigil session show <uid>"),process.exit(1))}await zA(n)}else console.error(`Unknown subcommand: ${t}`),process.exit(1)}finally{await r.destroy()}}async function XV(e){let t=e[0];(!t||e.includes("--help"))&&(console.log(`sigil pod \u2014 Inspect and manage memory pods
1377
+ sigil session show [<uid>] Detailed view (defaults to active)`),process.exit(t?0:1));let r=(await Promise.resolve().then(()=>(B(),se))).default;try{if(t==="current"){let{getActiveCursor:n}=await Promise.resolve().then(()=>(mi(),Ho)),i=await n();if(!i){console.log("No active session.");return}let o=await(await Promise.resolve().then(()=>(Qe(),at))).findByUid(i.pod_uid);if(!o){console.log(`Cursor points to ${i.pod_uid} but pod row not found.`);return}let a=(await Promise.resolve().then(()=>(ol(),Np))).formatForDisplay(o);console.log(`Active session: ${o.uid}`),console.log(` session_id: ${a.sessionId}`),console.log(` started_at: ${o.startedAt}`),console.log(` turn_count: ${a.turnCount}`),console.log(` cwd: ${a.cwd||"\u2014"}`),console.log(` transcript: ${a.transcriptPath||"\u2014"}`),console.log(` facts in pod: ${o.memberFactCount}`),console.log(` docs in pod: ${o.memberDocCount}`)}else if(t==="list"){let n=Number(mt(e,"--limit")||10),i=await(await Promise.resolve().then(()=>(Qe(),at))).listPods({podType:"claude_session",limit:n});if(!i.length){console.log("No session pods.");return}for(let o of i){let s=o.endedAt?o.endedAt.toISOString().slice(0,16).replace("T"," "):"active";console.log(` ${o.uid} ${o.name.padEnd(40)} facts=${o.memberFactCount} ${s}`)}}else if(t==="show"){let n=e[1];if(!n){let{getActiveCursor:i}=await Promise.resolve().then(()=>(mi(),Ho));n=(await i())?.pod_uid,n||(console.log("No active session. Pass a uid: sigil session show <uid>"),process.exit(1))}await zA(n)}else console.error(`Unknown subcommand: ${t}`),process.exit(1)}finally{await r.destroy()}}async function QV(e){let t=e[0];(!t||e.includes("--help"))&&(console.log(`sigil pod \u2014 Inspect and manage memory pods
1378
1378
 
1379
1379
  Usage:
1380
1380
  sigil pod list [--type=session|person] [--namespace=<ns>] [--limit=20]
@@ -1387,8 +1387,8 @@ Usage:
1387
1387
  sigil pod delete <uid> --confirm
1388
1388
 
1389
1389
  Pods are typed memory containers (session, person, ...). Person pods
1390
- back a canonical entity so dedup churn doesn't lose their metadata.`),process.exit(t?0:1));let r=(await Promise.resolve().then(()=>(B(),se))).default;try{if(t==="list"){let n=mt(e,"--type"),i=mt(e,"--namespace"),o=Number(mt(e,"--limit")||20),s=await(await Promise.resolve().then(()=>(Qe(),at))).listPods({podType:n,namespace:i,limit:o});if(!s.length){console.log("No pods.");return}for(let a of s)console.log(` ${a.uid} type=${a.podType.padEnd(20)} ${a.name.padEnd(40)} facts=${a.memberFactCount}`)}else if(t==="show"){let n=e[1];(!n||n.startsWith("--"))&&(console.error("Provide a uid: sigil pod show <uid>"),process.exit(1)),await zA(n)}else if(t==="create")await QV(e);else if(t==="archive"){let n=e[1];(!n||n.startsWith("--"))&&(console.error("Provide a uid: sigil pod archive <uid>"),process.exit(1));let i=await Promise.resolve().then(()=>(Qe(),at)),o=await i.findByUid(n);o||(console.error(`Not found: ${n}`),process.exit(1)),await i.archivePod(o.id),console.log(`Archived: ${n}`)}else if(t==="delete"){let n=e[1];(!n||n.startsWith("--"))&&(console.error("Provide a uid: sigil pod delete <uid> --confirm"),process.exit(1)),e.includes("--confirm")||(console.error("Pass --confirm to delete (cascades pod_membership)."),process.exit(1));let i=await Promise.resolve().then(()=>(Qe(),at)),o=await i.findByUid(n);o||(console.error(`Not found: ${n}`),process.exit(1)),await i.deletePod(o.id),console.log(`Deleted: ${n}`)}else console.error(`Unknown subcommand: ${t}`),process.exit(1)}finally{await r.destroy()}}async function zA(e){let t=await Promise.resolve().then(()=>(Qe(),at)),r=await Promise.resolve().then(()=>(pi(),rn)),n=await t.findByUid(e);n||(console.error(`Not found: ${e}`),process.exit(1));let i=typeof n.attrs=="object"?n.attrs:eK(n.attrs);console.log(`${n.uid} type=${n.podType}`),console.log(` name: ${n.name}`),console.log(` namespace: ${n.namespace}`),console.log(` status: ${n.status}`),console.log(` started_at: ${n.startedAt||"\u2014"}`),console.log(` ended_at: ${n.endedAt||"\u2014"}`),n.entityId&&console.log(` entity_id: ${n.entityId}`),n.connectionId&&console.log(` connection_id: ${n.connectionId}`),n.externalId&&console.log(` external_id: ${n.externalId}`),console.log(` facts: ${n.memberFactCount}`),console.log(` documents: ${n.memberDocCount}`),console.log(" attrs:");for(let[s,a]of Object.entries(i)){let c=typeof a=="object"?JSON.stringify(a):a;console.log(` ${s}: ${c??"\u2014"}`)}let o=await r.listMembers(n.id,{memberType:"fact",limit:10});if(o.length){console.log(`
1391
- Latest member facts (${o.length}):`);for(let s of o){let a=(s.content||"").slice(0,100);console.log(` - ${a}${s.content&&s.content.length>100?"\u2026":""}`)}}}async function QV(e){mt(e,"--type")!=="person"&&(console.error("Only --type=person is supported in PR1. Session pods are auto-created by hooks."),process.exit(1));let r=mt(e,"--name");r||(console.error("--name is required"),process.exit(1));let n=mt(e,"--namespace"),i=mt(e,"--slack"),o=mt(e,"--github"),s=mt(e,"--email"),a=mt(e,"--role"),c=mt(e,"--relationship"),l=mt(e,"--notes"),u={};i&&(u.slack={user_id:i}),o&&(u.github={username:o}),s&&(u.email=s);let p=(await Promise.resolve().then(()=>(N(),de))).default,d=n||p.defaults.namespace,m=await Promise.resolve().then(()=>(Ht(),li)),h=await m.findByName(r,d);if(h&&h.entityType&&h.entityType!=="person"&&(console.error(`An entity named "${r}" already exists with entity_type="${h.entityType}". Use a different name or merge manually.`),process.exit(1)),h)console.log(`Linked to existing entity: ${h.uid} (${h.name})`);else{let{embed:E}=await Promise.resolve().then(()=>(rr(),Gs)),I=await E(r).catch(()=>null);h=await m.insertEntity({name:r,entityType:"person",description:a?`${a}`:null,namespace:d,externalId:i||null,embedding:I}),console.log(`Created entity: ${h.uid} (${h.name})`)}let{upsertPersonPod:g}=await Promise.resolve().then(()=>(Hp(),UE)),{pod:w,isNew:_}=await g({entityId:h.id,name:r,namespace:d,attrs:{platforms:u,role:a,relationship:c,notes:l}});console.log(`${_?"Created":"Updated"} person pod: ${w.uid}`),console.log(` entity_id: ${h.id}`),console.log(` platforms: ${JSON.stringify(u)}`),a&&console.log(` role: ${a}`),c&&console.log(` relationship: ${c}`)}function mt(e,t){let r=e.find(i=>i.startsWith(`${t}=`));if(r)return r.slice(t.length+1);let n=e.indexOf(t);return n!==-1&&n+1<e.length&&!e[n+1].startsWith("--")?e[n+1]:null}function eK(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}async function tK(e){e.includes("--help")&&(console.log(`sigil facts \u2014 List stored facts
1390
+ back a canonical entity so dedup churn doesn't lose their metadata.`),process.exit(t?0:1));let r=(await Promise.resolve().then(()=>(B(),se))).default;try{if(t==="list"){let n=mt(e,"--type"),i=mt(e,"--namespace"),o=Number(mt(e,"--limit")||20),s=await(await Promise.resolve().then(()=>(Qe(),at))).listPods({podType:n,namespace:i,limit:o});if(!s.length){console.log("No pods.");return}for(let a of s)console.log(` ${a.uid} type=${a.podType.padEnd(20)} ${a.name.padEnd(40)} facts=${a.memberFactCount}`)}else if(t==="show"){let n=e[1];(!n||n.startsWith("--"))&&(console.error("Provide a uid: sigil pod show <uid>"),process.exit(1)),await zA(n)}else if(t==="create")await eK(e);else if(t==="archive"){let n=e[1];(!n||n.startsWith("--"))&&(console.error("Provide a uid: sigil pod archive <uid>"),process.exit(1));let i=await Promise.resolve().then(()=>(Qe(),at)),o=await i.findByUid(n);o||(console.error(`Not found: ${n}`),process.exit(1)),await i.archivePod(o.id),console.log(`Archived: ${n}`)}else if(t==="delete"){let n=e[1];(!n||n.startsWith("--"))&&(console.error("Provide a uid: sigil pod delete <uid> --confirm"),process.exit(1)),e.includes("--confirm")||(console.error("Pass --confirm to delete (cascades pod_membership)."),process.exit(1));let i=await Promise.resolve().then(()=>(Qe(),at)),o=await i.findByUid(n);o||(console.error(`Not found: ${n}`),process.exit(1)),await i.deletePod(o.id),console.log(`Deleted: ${n}`)}else console.error(`Unknown subcommand: ${t}`),process.exit(1)}finally{await r.destroy()}}async function zA(e){let t=await Promise.resolve().then(()=>(Qe(),at)),r=await Promise.resolve().then(()=>(pi(),rn)),n=await t.findByUid(e);n||(console.error(`Not found: ${e}`),process.exit(1));let i=typeof n.attrs=="object"?n.attrs:tK(n.attrs);console.log(`${n.uid} type=${n.podType}`),console.log(` name: ${n.name}`),console.log(` namespace: ${n.namespace}`),console.log(` status: ${n.status}`),console.log(` started_at: ${n.startedAt||"\u2014"}`),console.log(` ended_at: ${n.endedAt||"\u2014"}`),n.entityId&&console.log(` entity_id: ${n.entityId}`),n.connectionId&&console.log(` connection_id: ${n.connectionId}`),n.externalId&&console.log(` external_id: ${n.externalId}`),console.log(` facts: ${n.memberFactCount}`),console.log(` documents: ${n.memberDocCount}`),console.log(" attrs:");for(let[s,a]of Object.entries(i)){let c=typeof a=="object"?JSON.stringify(a):a;console.log(` ${s}: ${c??"\u2014"}`)}let o=await r.listMembers(n.id,{memberType:"fact",limit:10});if(o.length){console.log(`
1391
+ Latest member facts (${o.length}):`);for(let s of o){let a=(s.content||"").slice(0,100);console.log(` - ${a}${s.content&&s.content.length>100?"\u2026":""}`)}}}async function eK(e){mt(e,"--type")!=="person"&&(console.error("Only --type=person is supported in PR1. Session pods are auto-created by hooks."),process.exit(1));let r=mt(e,"--name");r||(console.error("--name is required"),process.exit(1));let n=mt(e,"--namespace"),i=mt(e,"--slack"),o=mt(e,"--github"),s=mt(e,"--email"),a=mt(e,"--role"),c=mt(e,"--relationship"),l=mt(e,"--notes"),u={};i&&(u.slack={user_id:i}),o&&(u.github={username:o}),s&&(u.email=s);let p=(await Promise.resolve().then(()=>(N(),de))).default,d=n||p.defaults.namespace,m=await Promise.resolve().then(()=>(Ht(),li)),h=await m.findByName(r,d);if(h&&h.entityType&&h.entityType!=="person"&&(console.error(`An entity named "${r}" already exists with entity_type="${h.entityType}". Use a different name or merge manually.`),process.exit(1)),h)console.log(`Linked to existing entity: ${h.uid} (${h.name})`);else{let{embed:E}=await Promise.resolve().then(()=>(rr(),Gs)),I=await E(r).catch(()=>null);h=await m.insertEntity({name:r,entityType:"person",description:a?`${a}`:null,namespace:d,externalId:i||null,embedding:I}),console.log(`Created entity: ${h.uid} (${h.name})`)}let{upsertPersonPod:g}=await Promise.resolve().then(()=>(Hp(),UE)),{pod:w,isNew:_}=await g({entityId:h.id,name:r,namespace:d,attrs:{platforms:u,role:a,relationship:c,notes:l}});console.log(`${_?"Created":"Updated"} person pod: ${w.uid}`),console.log(` entity_id: ${h.id}`),console.log(` platforms: ${JSON.stringify(u)}`),a&&console.log(` role: ${a}`),c&&console.log(` relationship: ${c}`)}function mt(e,t){let r=e.find(i=>i.startsWith(`${t}=`));if(r)return r.slice(t.length+1);let n=e.indexOf(t);return n!==-1&&n+1<e.length&&!e[n+1].startsWith("--")?e[n+1]:null}function tK(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}async function rK(e){e.includes("--help")&&(console.log(`sigil facts \u2014 List stored facts
1392
1392
 
1393
1393
  Usage:
1394
1394
  sigil facts [options]
@@ -1397,7 +1397,7 @@ Options:
1397
1397
  --namespace=<ns> Filter by namespace
1398
1398
  --category=<c> Filter by category
1399
1399
  --limit=<n> Max facts to show (default: 20)`),process.exit(0));let t=e.find(s=>s.startsWith("--namespace="))?.split("=")[1],r=e.find(s=>s.startsWith("--category="))?.split("=")[1],n=Number(e.find(s=>s.startsWith("--limit="))?.split("=")[1]||20),{connectOrStartDaemon:i}=await Promise.resolve().then(()=>(We(),Rt)),o=await i();try{let{data:s}=await o.call("listFacts",{namespace:t,category:r,limit:n});if(!s.facts.length)console.log("No facts found.");else{for(let a of s.facts){let c=a.importance==="vital"?" [VITAL]":"";console.log(`${a.uid.slice(0,8)} [${a.category}]${c} ${a.content}`)}console.log(`
1400
- ${s.facts.length} fact${s.facts.length>1?"s":""} shown. Use 'sigil forget <id>' to delete.`)}}finally{await o.close()}}async function rK(e){(e.includes("--help")||!e[0]||e[0].startsWith("--"))&&(console.log(`sigil forget \u2014 Delete a fact by ID
1400
+ ${s.facts.length} fact${s.facts.length>1?"s":""} shown. Use 'sigil forget <id>' to delete.`)}}finally{await o.close()}}async function nK(e){(e.includes("--help")||!e[0]||e[0].startsWith("--"))&&(console.log(`sigil forget \u2014 Delete a fact by ID
1401
1401
 
1402
1402
  Usage:
1403
1403
  sigil forget <id>
@@ -1405,7 +1405,7 @@ Usage:
1405
1405
  The <id> can be any of:
1406
1406
  - A numeric row id (e.g. 165) \u2014 shown by 'sigil facts' and 'sigil search'
1407
1407
  - A full UID (e.g. fact-eehjLrKb80s-TQHy)
1408
- - A short UID prefix (e.g. fact-eeh)`),process.exit(e[0]?0:1));let t=e[0],{connectOrStartDaemon:r}=await Promise.resolve().then(()=>(We(),Rt)),n=await r();try{let{data:i}=await n.call("forgetFact",{id:t});i.notFound&&(console.error(`No fact matches: ${t}`),process.exit(1)),console.log(`Forgotten: ${i.deleted.content}`)}finally{await n.close()}}async function nK(e){let t=e.filter(c=>c.startsWith("--")),r=e.filter(c=>!c.startsWith("--"));t.includes("--help")&&(console.log(`sigil remember \u2014 Save facts to memory
1408
+ - A short UID prefix (e.g. fact-eeh)`),process.exit(e[0]?0:1));let t=e[0],{connectOrStartDaemon:r}=await Promise.resolve().then(()=>(We(),Rt)),n=await r();try{let{data:i}=await n.call("forgetFact",{id:t});i.notFound&&(console.error(`No fact matches: ${t}`),process.exit(1)),console.log(`Forgotten: ${i.deleted.content}`)}finally{await n.close()}}async function iK(e){let t=e.filter(c=>c.startsWith("--")),r=e.filter(c=>!c.startsWith("--"));t.includes("--help")&&(console.log(`sigil remember \u2014 Save facts to memory
1409
1409
 
1410
1410
  Usage:
1411
1411
  sigil remember "fact1" ["fact2" ...] Save one or more facts
@@ -1422,7 +1422,7 @@ Examples:
1422
1422
  sigil remember --bg "user likes dark mode" "project uses Postgres"
1423
1423
  sigil remember --namespace=hermes-cli "agent decided to use Postgres LISTEN/NOTIFY"`),process.exit(0));let n=t.includes("--bg")||t.includes("--background"),i=t.find(c=>c.startsWith("--namespace="))?.split("=")[1]||void 0,o=r.filter(Boolean);if(o.length===0&&!process.stdin.isTTY){let c=[];for await(let u of process.stdin)c.push(u);let l=Buffer.concat(c).toString("utf8").trim();l&&(o=l.split(`
1424
1424
  `).map(u=>u.trim()).filter(Boolean))}if(o.length===0&&(console.error('Provide text to remember: sigil remember "your fact"'),process.exit(1)),n){let{spawn:c}=await import("node:child_process"),{buildRememberRespawnArgs:l}=await Promise.resolve().then(()=>(HA(),UA));c(process.execPath,[process.argv[1],...l(t,o)],{detached:!0,stdio:"ignore",env:{...process.env}}).unref(),console.log(`Saving ${o.length} fact${o.length>1?"s":""} in background...`);return}let{connectOrStartDaemon:s}=await Promise.resolve().then(()=>(We(),Rt)),a=await s();try{let{data:c}=await a.call("remember",{facts:o,namespace:i}),l=[];c.added&&l.push(`${c.added} new`),c.updated&&l.push(`${c.updated} updated`),c.alreadyKnown&&l.push(`${c.alreadyKnown} already known`),console.log(l.length?`Remembered. (${l.join(", ")})`:"Already known.")}catch(c){try{let{recordHookError:l}=await Promise.resolve().then(()=>(gi(),hi));await l("remember",c,o.join(`
1425
- `))}catch{}throw c}finally{await a.close()}}async function iK(e){e.includes("--help")&&(console.log(`sigil register \u2014 Register Sigil as an MCP server (advanced)
1425
+ `))}catch{}throw c}finally{await a.close()}}async function oK(e){e.includes("--help")&&(console.log(`sigil register \u2014 Register Sigil as an MCP server (advanced)
1426
1426
 
1427
1427
  Usage:
1428
1428
  sigil register [--http] [--print]
@@ -1438,10 +1438,10 @@ HTTP MCP.
1438
1438
 
1439
1439
  Options:
1440
1440
  --http Register the URL-based HTTP transport instead of stdio
1441
- --print Print the config without modifying any files`),process.exit(0)),await oK({http:e.includes("--http"),printOnly:e.includes("--print")})}async function oK({http:e=!1,printOnly:t=!1}={}){let r=await import("node:fs/promises"),{MCP_SHIM_PATH:n,writeLauncherShim:i}=await Promise.resolve().then(()=>(fn(),hf)),o,s,a;if(e){let d=(await Promise.resolve().then(()=>(N(),de))).default,{getGuiToken:m}=await Promise.resolve().then(()=>(ys(),Va)),h=await m(),g=`http://${d.http.host}:${d.http.port}/mcp`;o={type:"http",url:g,headers:{Authorization:`Bearer ${h}`}},s=`sigil -s user --transport http ${g} --header ${JSON.stringify(`Authorization: Bearer ${h}`)}`,a=`URL transport: ${g} (daemon must be running)`}else await i({}),o={command:n,args:[]},s=`sigil -s user -- ${n}`,a=`stdio launcher: ${n}`;let c=JSON.stringify({mcpServers:{sigil:o}},null,2);if(t){console.log(`
1441
+ --print Print the config without modifying any files`),process.exit(0)),await sK({http:e.includes("--http"),printOnly:e.includes("--print")})}async function sK({http:e=!1,printOnly:t=!1}={}){let r=await import("node:fs/promises"),{MCP_SHIM_PATH:n,writeLauncherShim:i}=await Promise.resolve().then(()=>(fn(),hf)),o,s,a;if(e){let d=(await Promise.resolve().then(()=>(N(),de))).default,{getGuiToken:m}=await Promise.resolve().then(()=>(ys(),Va)),h=await m(),g=`http://${d.http.host}:${d.http.port}/mcp`;o={type:"http",url:g,headers:{Authorization:`Bearer ${h}`}},s=`sigil -s user --transport http ${g} --header ${JSON.stringify(`Authorization: Bearer ${h}`)}`,a=`URL transport: ${g} (daemon must be running)`}else await i({}),o={command:n,args:[]},s=`sigil -s user -- ${n}`,a=`stdio launcher: ${n}`;let c=JSON.stringify({mcpServers:{sigil:o}},null,2);if(t){console.log(`
1442
1442
  Add this to your MCP client config:
1443
- `),console.log(c);return}if(JA("claude --version"))try{try{Li("claude mcp remove sigil",{stdio:"pipe"})}catch{}try{Li("claude mcp remove cortex",{stdio:"pipe"})}catch{}Li(`claude mcp add ${s}`,{stdio:"pipe"}),console.log("Registered sigil MCP server via `claude mcp add`."),console.log(` ${a}`);return}catch{}let u=sK(),p=!1;for(let d of u)if($n(d))try{let m=await r.readFile(d,"utf8"),h=JSON.parse(m);h.mcpServers=h.mcpServers||{},h.mcpServers.sigil=o,await r.writeFile(d,JSON.stringify(h,null,2),"utf8"),console.log(`Registered sigil MCP server in ${d}`),p=!0;break}catch{}p||(console.log(`Could not auto-register. Add this to your MCP client config:
1444
- `),console.log(c))}function sK(){let e=An(),t=process.platform,r=[Ue(e,".config","claude","claude_code_config.json"),Ue(e,".claude","settings.json")];return t==="darwin"?r.push(Ue(e,"Library","Application Support","Claude","claude_desktop_config.json")):t==="linux"?r.push(Ue(e,".config","Claude","claude_desktop_config.json")):t==="win32"&&r.push(Ue(process.env.APPDATA||"","Claude","claude_desktop_config.json")),r}async function aK(e){let t=e.filter(h=>h.startsWith("--")),r=e.filter(h=>!h.startsWith("--"));(!r.length||t.includes("--help"))&&(console.log(`sigil ingest \u2014 Ingest documents into the knowledge base
1443
+ `),console.log(c);return}if(JA("claude --version"))try{try{Li("claude mcp remove sigil",{stdio:"pipe"})}catch{}try{Li("claude mcp remove cortex",{stdio:"pipe"})}catch{}Li(`claude mcp add ${s}`,{stdio:"pipe"}),console.log("Registered sigil MCP server via `claude mcp add`."),console.log(` ${a}`);return}catch{}let u=aK(),p=!1;for(let d of u)if($n(d))try{let m=await r.readFile(d,"utf8"),h=JSON.parse(m);h.mcpServers=h.mcpServers||{},h.mcpServers.sigil=o,await r.writeFile(d,JSON.stringify(h,null,2),"utf8"),console.log(`Registered sigil MCP server in ${d}`),p=!0;break}catch{}p||(console.log(`Could not auto-register. Add this to your MCP client config:
1444
+ `),console.log(c))}function aK(){let e=An(),t=process.platform,r=[Ue(e,".config","claude","claude_code_config.json"),Ue(e,".claude","settings.json")];return t==="darwin"?r.push(Ue(e,"Library","Application Support","Claude","claude_desktop_config.json")):t==="linux"?r.push(Ue(e,".config","Claude","claude_desktop_config.json")):t==="win32"&&r.push(Ue(process.env.APPDATA||"","Claude","claude_desktop_config.json")),r}async function cK(e){let t=e.filter(h=>h.startsWith("--")),r=e.filter(h=>!h.startsWith("--"));(!r.length||t.includes("--help"))&&(console.log(`sigil ingest \u2014 Ingest documents into the knowledge base
1445
1445
 
1446
1446
  Usage:
1447
1447
  sigil ingest <file|url|glob> [options]
@@ -1459,7 +1459,7 @@ Examples:
1459
1459
  sigil ingest https://example.com/page --wait
1460
1460
  sigil ingest file1.md file2.md --namespace=engineering`),process.exit(0));let{readSource:n,readSources:i}=await Promise.resolve().then(()=>(ef(),Kv)),{fetchSource:o}=await Promise.resolve().then(()=>(rf(),qv)),s=t.find(h=>h.startsWith("--namespace="))?.split("=")[1],a=t.includes("--skip-facts"),c=t.includes("--skip-entities"),l=t.includes("--wait"),u={success:[],failed:[],skipped:[],queued:[]},p=Date.now(),{connectOrStartDaemon:d}=await Promise.resolve().then(()=>(We(),Rt)),m=await d(l?{timeoutMs:3e5}:void 0);try{for(let g of r)try{let w;if(g.startsWith("http://")||g.startsWith("https://"))w=[await o(g)];else if(g.includes("*")){if(w=await i(g),!w.length){console.error(`Error: No files matched pattern: ${g}`),u.failed.push({input:g,error:"no files matched"});continue}}else w=[await n(g)];for(let _ of w){console.log(`Ingesting: ${_.title}`);let{data:E}=await m.call("ingestDoc",{content:_.content,title:_.title,filePath:_.sourcePath,sourceType:_.sourceType,namespace:s,metadata:_.metadata,skipFacts:a,skipEntities:c,background:!l});if(E.queued)u.queued.push(_.title),console.log(" Queued");else if(E.skipped)u.skipped.push(_.title),console.log(" Skipped (unchanged)");else{u.success.push(_.title);let I=E.facts;console.log(` Done \u2014 ${E.chunkCount} chunks${I?`, ${I.total} facts (${I.added} new, ${I.updated??0} updated)`:""}`)}}}catch(w){console.error(` Failed: ${g} \u2014 ${w.message}`),u.failed.push({input:g,error:w.message})}let h=((Date.now()-p)/1e3).toFixed(1);u.queued.length?console.log(`
1461
1461
  Queued ${u.queued.length} document${u.queued.length===1?"":"s"} for background ingestion (${u.failed.length} failed). Run \`sigil status\` to watch the graph grow.`):console.log(`
1462
- Done in ${h}s \u2014 ${u.success.length} ingested, ${u.skipped.length} skipped, ${u.failed.length} failed`),u.success.length>0&&await m.call("refreshContext",{}).catch(()=>{})}finally{await m.close()}u.failed.length&&!u.success.length&&!u.queued.length&&process.exit(1)}async function cK(e){let t=e.filter(d=>d.startsWith("--")),r=e.filter(d=>!d.startsWith("--")).join(" ");(!r||t.includes("--help"))&&(console.log(`sigil search \u2014 Search the knowledge base
1462
+ Done in ${h}s \u2014 ${u.success.length} ingested, ${u.skipped.length} skipped, ${u.failed.length} failed`),u.success.length>0&&await m.call("refreshContext",{}).catch(()=>{})}finally{await m.close()}u.failed.length&&!u.success.length&&!u.queued.length&&process.exit(1)}async function lK(e){let t=e.filter(d=>d.startsWith("--")),r=e.filter(d=>!d.startsWith("--")).join(" ");(!r||t.includes("--help"))&&(console.log(`sigil search \u2014 Search the knowledge base
1463
1463
 
1464
1464
  Usage:
1465
1465
  sigil search "query" [options]
@@ -1480,7 +1480,7 @@ Examples:
1480
1480
  sigil search "API design" --limit=5
1481
1481
  sigil search "that decision" --scope # only this project's memory`),process.exit(0));let n=t.find(d=>d.startsWith("--namespace="))?.split("=")[1],i=n?n.split(","):void 0,o=Number(t.find(d=>d.startsWith("--limit="))?.split("=")[1]||10),s=t.includes("--graph")&&!t.includes("--no-graph"),a=t.includes("--route"),c=t.includes("--synthesize"),l=t.includes("--chunks")||c,{connectOrStartDaemon:u}=await Promise.resolve().then(()=>(We(),Rt)),p=await u();try{let d=t.includes("--scope")?"auto":"global",{data:m}=await p.call("search",{query:r,namespaces:i,limit:o,useGraph:s,route:a,synthesize:c,includeChunks:l,podScope:d,cwd:process.cwd()});if(m.synthesized&&console.log(m.synthesized),m.facts.length){console.log(`
1482
1482
  Facts (${m.facts.length}):`);for(let h of m.facts)console.log(` ${h.content}${VA(h)}`)}if(m.chunks.length){console.log(`
1483
- Chunks (${m.chunks.length}):`);for(let h of m.chunks){let g=h.content?.slice(0,120).replace(/\n/g," ");console.log(` ${g}...${VA(h)}`)}}!m.facts.length&&!m.chunks.length&&console.log("No results found.")}finally{await p.close()}}function VA(e){let t=Number(e?.similarity);return Number.isFinite(t)&&t>0?` [sim ${t.toFixed(2)}]`:Number.isFinite(t)&&t===0?" [kw]":e?.rrfScore!=null?` [${e.rrfScore}]`:""}async function lK(e){e.includes("--help")&&(console.log(`sigil context \u2014 Refresh the hot-context snapshot in ~/.claude/CLAUDE.md
1483
+ Chunks (${m.chunks.length}):`);for(let h of m.chunks){let g=h.content?.slice(0,120).replace(/\n/g," ");console.log(` ${g}...${VA(h)}`)}}!m.facts.length&&!m.chunks.length&&console.log("No results found.")}finally{await p.close()}}function VA(e){let t=Number(e?.similarity);return Number.isFinite(t)&&t>0?` [sim ${t.toFixed(2)}]`:Number.isFinite(t)&&t===0?" [kw]":e?.rrfScore!=null?` [${e.rrfScore}]`:""}async function uK(e){e.includes("--help")&&(console.log(`sigil context \u2014 Refresh the hot-context snapshot in ~/.claude/CLAUDE.md
1484
1484
 
1485
1485
  Usage:
1486
1486
  sigil context [--namespace=<ns>] [--limit=<n>] [--explain]
@@ -1493,7 +1493,7 @@ Options:
1493
1493
  --limit=<n> Max facts to include (default: 20)
1494
1494
  --explain Don't write the snapshot \u2014 print which kind each
1495
1495
  fact came from instead`),process.exit(0));let t=e.find(a=>a.startsWith("--namespace="))?.split("=")[1],r=e.find(a=>a.startsWith("--limit="))?.split("=")[1],n=r?Number(r):20,i=e.includes("--explain"),{connectOrStartDaemon:o}=await Promise.resolve().then(()=>(We(),Rt)),s=await o();try{let{data:a}=await s.call("refreshContext",{namespace:t,limit:n,explain:i,cwd:process.cwd()});if(a.mode==="explain"){console.log(`Hot-context blend for namespace=${a.namespace}:
1496
- `);for(let c of a.sections){if(console.log(` ${c.name} (budget=${c.budget}, ${c.visibility})`),c.error&&console.log(` (failed: ${c.error})`),!c.facts.length)console.log(" (no facts)");else for(let l of c.facts)console.log(` - ${(l.content||"").slice(0,120)}`);console.log("")}return}a.count?console.log(`Context refreshed \u2014 ${a.count} facts written to ~/.sigil/CLAUDE.md`):console.log("No facts found. Ingest some content first.")}finally{await s.close()}}async function uK(e){e.includes("--help")&&(console.log(`sigil preamble \u2014 Session-start sanity + fresh-facts pass
1496
+ `);for(let c of a.sections){if(console.log(` ${c.name} (budget=${c.budget}, ${c.visibility})`),c.error&&console.log(` (failed: ${c.error})`),!c.facts.length)console.log(" (no facts)");else for(let l of c.facts)console.log(` - ${(l.content||"").slice(0,120)}`);console.log("")}return}a.count?console.log(`Context refreshed \u2014 ${a.count} facts written to ~/.sigil/CLAUDE.md`):console.log("No facts found. Ingest some content first.")}finally{await s.close()}}async function dK(e){e.includes("--help")&&(console.log(`sigil preamble \u2014 Session-start sanity + fresh-facts pass
1497
1497
 
1498
1498
  Usage:
1499
1499
  sigil preamble [options]
@@ -1510,10 +1510,10 @@ Options:
1510
1510
  --transport=hooks How-to footer for Claude Code (default for CLI: cli)
1511
1511
  --limit=<n> Max fresh facts to load (default 12)
1512
1512
 
1513
- Exit code is always 0 \u2014 a degraded result is reported in-band, never thrown.`),process.exit(0));let t=e.find(c=>c.startsWith("--format="))?.split("=")[1]||"md",r=e.find(c=>c.startsWith("--transport="))?.split("=")[1]||"cli",n=e.find(c=>c.startsWith("--limit="))?.split("=")[1],i=n?Number(n):12,{buildPreamble:o}=await Promise.resolve().then(()=>(Nd(),Od)),{renderPreamble:s}=await Promise.resolve().then(()=>(Pd(),Ld)),a=await o({cwd:process.cwd(),limit:i});console.log(s(a,{format:t,transport:r}))}async function dK(e){e.includes("--help")&&(console.log(`sigil status \u2014 Show knowledge base statistics
1513
+ Exit code is always 0 \u2014 a degraded result is reported in-band, never thrown.`),process.exit(0));let t=e.find(c=>c.startsWith("--format="))?.split("=")[1]||"md",r=e.find(c=>c.startsWith("--transport="))?.split("=")[1]||"cli",n=e.find(c=>c.startsWith("--limit="))?.split("=")[1],i=n?Number(n):12,{buildPreamble:o}=await Promise.resolve().then(()=>(Nd(),Od)),{renderPreamble:s}=await Promise.resolve().then(()=>(Pd(),Ld)),a=await o({cwd:process.cwd(),limit:i});console.log(s(a,{format:t,transport:r}))}async function pK(e){e.includes("--help")&&(console.log(`sigil status \u2014 Show knowledge base statistics
1514
1514
 
1515
1515
  Usage:
1516
- sigil status [--namespace=<ns>]`),process.exit(0));let t=e.find(i=>i.startsWith("--namespace="))?.split("=")[1],{connectOrStartDaemon:r}=await Promise.resolve().then(()=>(We(),Rt)),n=await r();try{let{data:i}=await n.call("status",{namespace:t||null}),o=Object.entries(i.podsByType||{}).map(([s,a])=>`${a} ${s}`).join(", ")||"\u2014";if(console.log(`Sigil Knowledge Base${i.namespace?` (${i.namespace})`:""}`),console.log(` Documents: ${i.documents}`),console.log(` Chunks: ${i.chunks}`),console.log(` Facts: ${i.facts} active`),console.log(` Entities: ${i.entities.documents} documents, ${i.entities.people} people, ${i.entities.topics} topics`),console.log(` Relations: ${i.relations}`),console.log(` Pods: ${o}`),i.hebbian){let s=i.hebbian.avgStrength?i.hebbian.avgStrength.toFixed(2):"0",a=i.hebbian.maxStrength?i.hebbian.maxStrength.toFixed(2):"0";if(console.log(` Co-retrieval edges: ${i.hebbian.edgeCount} (avg ${s}, max ${a})`),i.hebbian.topPairs.length){console.log(" Top pairs by decayed strength:");for(let c of i.hebbian.topPairs)console.log(` ${c.a} \u2194 ${c.b} (decayed ${Number(c.decayed).toFixed(2)})`)}}}finally{await n.close()}}async function pK(e){let t=e.find(a=>!a.startsWith("--"));(e.includes("--help")||t&&t!=="embeddings")&&(console.log(`sigil repair \u2014 Heal a corpus with missing or stale embeddings
1516
+ sigil status [--namespace=<ns>]`),process.exit(0));let t=e.find(i=>i.startsWith("--namespace="))?.split("=")[1],{connectOrStartDaemon:r}=await Promise.resolve().then(()=>(We(),Rt)),n=await r();try{let{data:i}=await n.call("status",{namespace:t||null}),o=Object.entries(i.podsByType||{}).map(([s,a])=>`${a} ${s}`).join(", ")||"\u2014";if(console.log(`Sigil Knowledge Base${i.namespace?` (${i.namespace})`:""}`),console.log(` Documents: ${i.documents}`),console.log(` Chunks: ${i.chunks}`),console.log(` Facts: ${i.facts} active`),console.log(` Entities: ${i.entities.documents} documents, ${i.entities.people} people, ${i.entities.topics} topics`),console.log(` Relations: ${i.relations}`),console.log(` Pods: ${o}`),i.hebbian){let s=i.hebbian.avgStrength?i.hebbian.avgStrength.toFixed(2):"0",a=i.hebbian.maxStrength?i.hebbian.maxStrength.toFixed(2):"0";if(console.log(` Co-retrieval edges: ${i.hebbian.edgeCount} (avg ${s}, max ${a})`),i.hebbian.topPairs.length){console.log(" Top pairs by decayed strength:");for(let c of i.hebbian.topPairs)console.log(` ${c.a} \u2194 ${c.b} (decayed ${Number(c.decayed).toFixed(2)})`)}}}finally{await n.close()}}async function fK(e){let t=e.find(a=>!a.startsWith("--"));(e.includes("--help")||t&&t!=="embeddings")&&(console.log(`sigil repair \u2014 Heal a corpus with missing or stale embeddings
1517
1517
 
1518
1518
  Usage:
1519
1519
  sigil repair embeddings [options]
@@ -1527,17 +1527,17 @@ Options:
1527
1527
  --namespace=<ns> Limit to one namespace
1528
1528
  --all-chunks Re-embed every chunk (use after switching providers; chunks
1529
1529
  carry no model stamp, so NULL-only is the default)`),process.exit(0));let r=e.includes("--dry-run"),n=e.find(a=>a.startsWith("--namespace="))?.split("=")[1]||null,i=e.includes("--all-chunks"),{connectOrStartDaemon:o}=await Promise.resolve().then(()=>(We(),Rt)),s=await o();try{let{data:a}=await s.call("repair.embeddings",{dryRun:r,namespace:n,allChunks:i});a.dryRun?(console.log(`Repair (dry run)${n?` [ns=${n}]`:""} \u2014 target model: ${a.model}`),console.log(` Facts needing repair: ${a.facts.scanned}`),console.log(` Chunks needing repair: ${a.chunks.scanned}`),a.spool?.pending&&console.log(` Stop-hook spool: ${a.spool.pending} turns pending replay`),console.log(`
1530
- Run without --dry-run to re-embed them.`)):(console.log(`Repair complete${n?` [ns=${n}]`:""} \u2014 model: ${a.model}`),console.log(` Facts re-embedded: ${a.facts.repaired} / ${a.facts.scanned}`),console.log(` Chunks re-embedded: ${a.chunks.repaired} / ${a.chunks.scanned}`),a.spool&&console.log(` Stop-spool replayed: ${a.spool.drained} turns (${a.spool.replayed} facts, ${a.spool.remaining} still pending)`))}finally{await s.close()}}async function fK(e){e.includes("--help")&&(console.log(`sigil maintain \u2014 Run periodic memory maintenance
1530
+ Run without --dry-run to re-embed them.`)):(console.log(`Repair complete${n?` [ns=${n}]`:""} \u2014 model: ${a.model}`),console.log(` Facts re-embedded: ${a.facts.repaired} / ${a.facts.scanned}`),console.log(` Chunks re-embedded: ${a.chunks.repaired} / ${a.chunks.scanned}`),a.spool&&console.log(` Stop-spool replayed: ${a.spool.drained} turns (${a.spool.replayed} facts, ${a.spool.remaining} still pending)`))}finally{await s.close()}}async function mK(e){e.includes("--help")&&(console.log(`sigil maintain \u2014 Run periodic memory maintenance
1531
1531
 
1532
1532
  Usage:
1533
1533
  sigil maintain
1534
1534
 
1535
1535
  Promotes 'fresh' facts (older than 1h with importance=vital or any access) to 'stable',
1536
1536
  closes 'editing' windows older than 30 minutes back to 'stable', and consolidates
1537
- co-retrieval edges. Safe to run as a cron \u2014 fully idempotent.`),process.exit(0));let t=(await Promise.resolve().then(()=>(B(),se))).default,{promoteFreshFacts:r,closeEditingWindows:n,getLifecycleStats:i}=await Promise.resolve().then(()=>(GA(),jA)),{consolidateCoRetrievalEdges:o}=await Promise.resolve().then(()=>(Kp(),iv)).catch(()=>({})),{consolidateEntityCoRetrievalEdges:s}=await Promise.resolve().then(()=>(ta(),ll)).catch(()=>({})),{pruneLogs:a}=await Promise.resolve().then(()=>(ii(),Sx)),c=await i(),l=await r(),u=await n(),p=o?await o():0,d=s?await s():0,m=await a(),h=await i();console.log("Memory maintenance:"),console.log(` Stages \u2014 fresh: ${c.fresh}\u2192${h.fresh}, stable: ${c.stable}\u2192${h.stable}, editing: ${c.editing}\u2192${h.editing}`),console.log(` Promoted (fresh\u2192stable): ${l}`),console.log(` Closed editing windows (editing\u2192stable): ${u}`),p&&console.log(` Fact co-retrieval edges consolidated: ${p}`),d&&console.log(` Entity co-retrieval edges consolidated: ${d}`),console.log(` Pruned logs \u2014 llm_log: ${m.llmDeleted}, trace_event: ${m.traceDeleted}`),await t.destroy()}async function mK(e){e.includes("--help")&&(console.log(`sigil migrate \u2014 Run database migrations
1537
+ co-retrieval edges. Safe to run as a cron \u2014 fully idempotent.`),process.exit(0));let t=(await Promise.resolve().then(()=>(B(),se))).default,{promoteFreshFacts:r,closeEditingWindows:n,getLifecycleStats:i}=await Promise.resolve().then(()=>(GA(),jA)),{consolidateCoRetrievalEdges:o}=await Promise.resolve().then(()=>(Kp(),iv)).catch(()=>({})),{consolidateEntityCoRetrievalEdges:s}=await Promise.resolve().then(()=>(ta(),ll)).catch(()=>({})),{pruneLogs:a}=await Promise.resolve().then(()=>(ii(),Sx)),c=await i(),l=await r(),u=await n(),p=o?await o():0,d=s?await s():0,m=await a(),h=await i();console.log("Memory maintenance:"),console.log(` Stages \u2014 fresh: ${c.fresh}\u2192${h.fresh}, stable: ${c.stable}\u2192${h.stable}, editing: ${c.editing}\u2192${h.editing}`),console.log(` Promoted (fresh\u2192stable): ${l}`),console.log(` Closed editing windows (editing\u2192stable): ${u}`),p&&console.log(` Fact co-retrieval edges consolidated: ${p}`),d&&console.log(` Entity co-retrieval edges consolidated: ${d}`),console.log(` Pruned logs \u2014 llm_log: ${m.llmDeleted}, trace_event: ${m.traceDeleted}`),await t.destroy()}async function hK(e){e.includes("--help")&&(console.log(`sigil migrate \u2014 Run database migrations
1538
1538
 
1539
1539
  Usage:
1540
- sigil migrate [--rollback]`),process.exit(0));let t=(await Promise.resolve().then(()=>(B(),se))).default,{MIGRATIONS_DIR:r}=await Promise.resolve().then(()=>(K(),Ma));if(e.includes("--rollback")){let[n,i]=await t.migrate.rollback({directory:r});console.log(`Rolled back batch ${n}: ${i.length} migrations`);for(let o of i)console.log(` ${o}`)}else{let[n,i]=await t.migrate.latest({directory:r});if(i.length){console.log(`Ran batch ${n}: ${i.length} migrations`);for(let o of i)console.log(` ${o}`)}else console.log("Already up to date.")}await t.destroy()}async function hK(e){e.includes("--help")&&(console.log(`sigil reset \u2014 Clean rebuild: tear down Sigil's setup, config, and data
1540
+ sigil migrate [--rollback]`),process.exit(0));let t=(await Promise.resolve().then(()=>(B(),se))).default,{MIGRATIONS_DIR:r}=await Promise.resolve().then(()=>(K(),Ma));if(e.includes("--rollback")){let[n,i]=await t.migrate.rollback({directory:r});console.log(`Rolled back batch ${n}: ${i.length} migrations`);for(let o of i)console.log(` ${o}`)}else{let[n,i]=await t.migrate.latest({directory:r});if(i.length){console.log(`Ran batch ${n}: ${i.length} migrations`);for(let o of i)console.log(` ${o}`)}else console.log("Already up to date.")}await t.destroy()}async function gK(e){e.includes("--help")&&(console.log(`sigil reset \u2014 Clean rebuild: tear down Sigil's setup, config, and data
1541
1541
 
1542
1542
  Usage:
1543
1543
  sigil reset Confirm, then drop the database + wipe everything
@@ -1552,7 +1552,7 @@ Tears down:
1552
1552
  - ~/.claude/CLAUDE.md the @~/.sigil/CLAUDE.md import line
1553
1553
 
1554
1554
  Re-run 'npx @anmol-srv/sigil' (or 'sigil') afterwards to set up fresh.`),process.exit(0));let t=e.includes("--confirm")||e.includes("--yes")||e.includes("-y"),r=e.includes("--keep-db"),n=An(),i=Ue(n,".sigil");if(!t){let s=await Promise.resolve().then(()=>(Ra(),ka));s.intro("Sigil \u2014 reset (clean rebuild)"),s.note(["This will:",r?" - KEEP the database (--keep-db)":" - drop the database (Docker container+volume / local DROP DATABASE; external left intact)"," - disconnect every coding agent (remove Sigil hooks/config)",` - delete ${i} (config + all local state)`," - remove the @~/.sigil/CLAUDE.md import line"].join(`
1555
- `),"About to reset");let a=await s.confirm({message:r?"Wipe config + disconnect agents?":"Drop the database and wipe everything?",initialValue:!1});(s.isCancel(a)||a!==!0)&&(s.cancel("Reset cancelled. Nothing changed."),process.exit(0))}if(r)console.log(" database: kept (--keep-db)");else try{let{dropConfiguredDatabase:s}=await Promise.resolve().then(()=>(Vl(),Wl)),a=await s();console.log(` database: ${a.detail}`)}catch(s){console.log(` database: drop failed (${s.message}) \u2014 continuing`)}try{let{disconnectAllClients:s}=await Promise.resolve().then(()=>(Vl(),Wl)),a=await s();console.log(` agents: ${a.length?`disconnected ${a.join(", ")}`:"none connected"}`)}catch(s){console.log(` agents: ${s.message}`)}try{Li('pkill -f "dist/daemon.js"',{stdio:"pipe"})}catch{}try{Li('pkill -f "sigil/dist/server.js --mcp"',{stdio:"pipe"})}catch{}let o=await import("node:fs/promises");$n(i)&&await o.rm(i,{recursive:!0,force:!0}),await gK(),console.log(""),console.log(" Reset complete. Run `npx @anmol-srv/sigil` (or `sigil`) to set up again."),console.log(""),process.exit(0)}async function gK(){let e=await import("node:fs/promises"),t=Ue(An(),".claude","CLAUDE.md");if(!$n(t))return!1;let r=await e.readFile(t,"utf8"),n=An(),i=[Ue(n,".sigil","CLAUDE.md"),Ue(n,".smara","CLAUDE.md"),Ue(n,".cortex","CLAUDE.md")],o=r;for(let s of i){let a=new RegExp(`^@${yK(s)}\\s*\\n?`,"gm");o=o.replace(a,"")}return o===r?!1:(await e.writeFile(t,o,"utf8"),!0)}function yK(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function wK(e){(e.length===0||e.includes("--help"))&&(console.log(`sigil why \u2014 Explain a search result
1555
+ `),"About to reset");let a=await s.confirm({message:r?"Wipe config + disconnect agents?":"Drop the database and wipe everything?",initialValue:!1});(s.isCancel(a)||a!==!0)&&(s.cancel("Reset cancelled. Nothing changed."),process.exit(0))}if(r)console.log(" database: kept (--keep-db)");else try{let{dropConfiguredDatabase:s}=await Promise.resolve().then(()=>(Vl(),Wl)),a=await s();console.log(` database: ${a.detail}`)}catch(s){console.log(` database: drop failed (${s.message}) \u2014 continuing`)}try{let{disconnectAllClients:s}=await Promise.resolve().then(()=>(Vl(),Wl)),a=await s();console.log(` agents: ${a.length?`disconnected ${a.join(", ")}`:"none connected"}`)}catch(s){console.log(` agents: ${s.message}`)}try{Li('pkill -f "dist/daemon.js"',{stdio:"pipe"})}catch{}try{Li('pkill -f "sigil/dist/server.js --mcp"',{stdio:"pipe"})}catch{}let o=await import("node:fs/promises");$n(i)&&await o.rm(i,{recursive:!0,force:!0}),await yK(),console.log(""),console.log(" Reset complete. Run `npx @anmol-srv/sigil` (or `sigil`) to set up again."),console.log(""),process.exit(0)}async function yK(){let e=await import("node:fs/promises"),t=Ue(An(),".claude","CLAUDE.md");if(!$n(t))return!1;let r=await e.readFile(t,"utf8"),n=An(),i=[Ue(n,".sigil","CLAUDE.md"),Ue(n,".smara","CLAUDE.md"),Ue(n,".cortex","CLAUDE.md")],o=r;for(let s of i){let a=new RegExp(`^@${wK(s)}\\s*\\n?`,"gm");o=o.replace(a,"")}return o===r?!1:(await e.writeFile(t,o,"utf8"),!0)}function wK(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function _K(e){(e.length===0||e.includes("--help"))&&(console.log(`sigil why \u2014 Explain a search result
1556
1556
 
1557
1557
  Usage:
1558
1558
  sigil why "<query>" [--namespace=<ns>] [--limit=5] [--pod-scope=auto|global|<name>,<name>]
@@ -1560,7 +1560,7 @@ Usage:
1560
1560
  Runs the same hybrid search the UserPromptSubmit hook uses and prints
1561
1561
  the per-fact breakdown \u2014 vector score, keyword score, importance,
1562
1562
  recency, kind / pod source \u2014 so you can see WHY each fact made the
1563
- top-K for a given query.`),process.exit(0));let t=(await Promise.resolve().then(()=>(N(),de))).default,r=(await Promise.resolve().then(()=>(B(),se))).default,n=e.findIndex(h=>h.startsWith("--")),o=(n===-1?e:e.slice(0,n)).join(" ").replace(/^["']|["']$/g,"");o||(console.error('Provide a query: sigil why "<query>"'),process.exit(1));let s=e.find(h=>h.startsWith("--namespace="))?.split("=")[1]||t.defaults.namespace,a=e.find(h=>h.startsWith("--limit="))?.split("=")[1],c=a?Number(a):5,l=e.find(h=>h.startsWith("--pod-scope="))?.split("=")[1],u=null;l&&(l==="auto"||l==="global"?u=l:u=l.split(",").map(h=>h.trim()).filter(Boolean));let{search:p}=await Promise.resolve().then(()=>(Qp(),Xp)),d=await p(o,{namespaces:[s],limit:c,route:!0,expand:!0,synthesize:!1,podScope:u??"auto"});if(console.log(`Query: ${o}`),console.log(`Namespace: ${s}`),console.log(`Pod scope: ${JSON.stringify(u??"auto")}`),console.log(""),d.matchedEntity&&(console.log(`Matched entity: ${d.matchedEntity.name} (${d.matchedEntity.type}, id:${d.matchedEntity.id})`),console.log("")),!d.facts.length){console.log("No facts returned."),await r.destroy();return}let m=await Promise.resolve().then(()=>(pi(),rn));console.log(`Facts (${d.facts.length}):`);for(let[h,g]of d.facts.entries()){let w=await m.listPodsForMember("fact",g.id).catch(()=>[]),_=w.length?w.map($=>`${$.podType}:${$.name}`).join(", "):"\u2014",E=g.importance||`score=${g.importanceScore??"?"}`,I=g.coRetrievalBoost!=null?` hebbian=${g.coRetrievalBoost}`:"";console.log(` ${h+1}. [rrf=${g.rrfScore??"?"}${I}] [${g.category}] [${E}] [conf=${g.confidence}]`),console.log(` pods: ${_}`),console.log(` content: ${(g.content||"").slice(0,140)}`)}await r.destroy()}async function _K(e){let t=e[0];(!t||t==="--help")&&(console.log(`sigil kind \u2014 Inspect registered pod kinds
1563
+ top-K for a given query.`),process.exit(0));let t=(await Promise.resolve().then(()=>(N(),de))).default,r=(await Promise.resolve().then(()=>(B(),se))).default,n=e.findIndex(h=>h.startsWith("--")),o=(n===-1?e:e.slice(0,n)).join(" ").replace(/^["']|["']$/g,"");o||(console.error('Provide a query: sigil why "<query>"'),process.exit(1));let s=e.find(h=>h.startsWith("--namespace="))?.split("=")[1]||t.defaults.namespace,a=e.find(h=>h.startsWith("--limit="))?.split("=")[1],c=a?Number(a):5,l=e.find(h=>h.startsWith("--pod-scope="))?.split("=")[1],u=null;l&&(l==="auto"||l==="global"?u=l:u=l.split(",").map(h=>h.trim()).filter(Boolean));let{search:p}=await Promise.resolve().then(()=>(Qp(),Xp)),d=await p(o,{namespaces:[s],limit:c,route:!0,expand:!0,synthesize:!1,podScope:u??"auto"});if(console.log(`Query: ${o}`),console.log(`Namespace: ${s}`),console.log(`Pod scope: ${JSON.stringify(u??"auto")}`),console.log(""),d.matchedEntity&&(console.log(`Matched entity: ${d.matchedEntity.name} (${d.matchedEntity.type}, id:${d.matchedEntity.id})`),console.log("")),!d.facts.length){console.log("No facts returned."),await r.destroy();return}let m=await Promise.resolve().then(()=>(pi(),rn));console.log(`Facts (${d.facts.length}):`);for(let[h,g]of d.facts.entries()){let w=await m.listPodsForMember("fact",g.id).catch(()=>[]),_=w.length?w.map($=>`${$.podType}:${$.name}`).join(", "):"\u2014",E=g.importance||`score=${g.importanceScore??"?"}`,I=g.coRetrievalBoost!=null?` hebbian=${g.coRetrievalBoost}`:"";console.log(` ${h+1}. [rrf=${g.rrfScore??"?"}${I}] [${g.category}] [${E}] [conf=${g.confidence}]`),console.log(` pods: ${_}`),console.log(` content: ${(g.content||"").slice(0,140)}`)}await r.destroy()}async function bK(e){let t=e[0];(!t||t==="--help")&&(console.log(`sigil kind \u2014 Inspect registered pod kinds
1564
1564
 
1565
1565
  Usage:
1566
1566
  sigil kind list
@@ -1568,4 +1568,4 @@ Usage:
1568
1568
 
1569
1569
  list Show every registered pod kind with budget / visibility / TTL.
1570
1570
  show Show one kind's full contract, schema doc path, and active scope
1571
- for the current shell context.`),process.exit(0)),await Promise.resolve().then(()=>(ea(),Wp));let{list:r,get:n,activeKinds:i,getSchemaDoc:o}=await Promise.resolve().then(()=>(jo(),Gp));if(t==="list"){let s=r();console.log(`Registered kinds (${s.length}):`);for(let l of s){let u=l.ttlDays?`${l.ttlDays}d TTL`:"no decay";console.log(` ${l.name.padEnd(18)} budget=${l.hotContextBudget} ${l.visibility.padEnd(8)} ${u}`),console.log(` ${l.description}`)}let a=(await Promise.resolve().then(()=>(N(),de))).default.defaults.namespace,c=await i({namespace:a,cwd:process.cwd()});console.log(""),console.log(`Active for cwd=${process.cwd()}: ${c.length?c.map(l=>l.kind.name).join(", "):"(none)"}`);return}if(t==="show"){let s=e[1];s||(console.error("Provide a kind name: sigil kind show <name>"),process.exit(1));let a=n(s);a||(console.error(`Unknown kind: ${s}`),process.exit(1)),console.log(`Kind: ${a.name}`),console.log(` description: ${a.description}`),console.log(` identityField: ${a.identityField??"\u2014"}`),console.log(` visibility: ${a.visibility}`),console.log(` activeMode: ${a.activeMode}`),console.log(` hotContextBudget: ${a.hotContextBudget}`),console.log(` retrievalWeights: ${JSON.stringify(a.retrievalWeights)}`),console.log(` importanceDefault: ${a.importanceDefault}`),console.log(` ttlDays: ${a.ttlDays??"no decay"}`),console.log(` writePolicy: ${a.writePolicy}`),console.log(` schemaDocPath: ${a.schemaDocPath??"\u2014"}`);let c=await o(a);console.log(` schemaDoc chars: ${c?c.length:0}`);return}console.error(`Unknown subcommand: ${t}`),process.exit(1)}function JA(e){try{return Li(e,{stdio:"pipe"}),!0}catch{return!1}}async function ZA(e){try{return(await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}function bK(){return LV("ollama",["serve"],{detached:!0,stdio:"ignore"})}async function xK(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(await ZA(e))return!0;await new Promise(n=>setTimeout(n,250))}return!1}function EK(e){return PV(e).toString("hex")}
1571
+ for the current shell context.`),process.exit(0)),await Promise.resolve().then(()=>(ea(),Wp));let{list:r,get:n,activeKinds:i,getSchemaDoc:o}=await Promise.resolve().then(()=>(jo(),Gp));if(t==="list"){let s=r();console.log(`Registered kinds (${s.length}):`);for(let l of s){let u=l.ttlDays?`${l.ttlDays}d TTL`:"no decay";console.log(` ${l.name.padEnd(18)} budget=${l.hotContextBudget} ${l.visibility.padEnd(8)} ${u}`),console.log(` ${l.description}`)}let a=(await Promise.resolve().then(()=>(N(),de))).default.defaults.namespace,c=await i({namespace:a,cwd:process.cwd()});console.log(""),console.log(`Active for cwd=${process.cwd()}: ${c.length?c.map(l=>l.kind.name).join(", "):"(none)"}`);return}if(t==="show"){let s=e[1];s||(console.error("Provide a kind name: sigil kind show <name>"),process.exit(1));let a=n(s);a||(console.error(`Unknown kind: ${s}`),process.exit(1)),console.log(`Kind: ${a.name}`),console.log(` description: ${a.description}`),console.log(` identityField: ${a.identityField??"\u2014"}`),console.log(` visibility: ${a.visibility}`),console.log(` activeMode: ${a.activeMode}`),console.log(` hotContextBudget: ${a.hotContextBudget}`),console.log(` retrievalWeights: ${JSON.stringify(a.retrievalWeights)}`),console.log(` importanceDefault: ${a.importanceDefault}`),console.log(` ttlDays: ${a.ttlDays??"no decay"}`),console.log(` writePolicy: ${a.writePolicy}`),console.log(` schemaDocPath: ${a.schemaDocPath??"\u2014"}`);let c=await o(a);console.log(` schemaDoc chars: ${c?c.length:0}`);return}console.error(`Unknown subcommand: ${t}`),process.exit(1)}function JA(e){try{return Li(e,{stdio:"pipe"}),!0}catch{return!1}}async function ZA(e){try{return(await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}function xK(){return PV("ollama",["serve"],{detached:!0,stdio:"ignore"})}async function EK(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(await ZA(e))return!0;await new Promise(n=>setTimeout(n,250))}return!1}function vK(e){return MV(e).toString("hex")}