agentix-cli 0.87.0 → 0.88.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{d as e}from"./chunk-O5U5NVLR.js";function i(t={}){let r=`<div class="ax-proc__kpis" id="proc-kpis" hidden></div>
1
+ import{d as e}from"./chunk-OAA7TNB6.js";function i(t={}){let r=`<div class="ax-proc__kpis" id="proc-kpis" hidden></div>
2
2
  <div class="ax-proc__root">
3
3
  <aside class="ax-proc__list">
4
4
  <header>
@@ -253,4 +253,4 @@ import{d as e}from"./chunk-O5U5NVLR.js";function i(t={}){let r=`<div class="ax-p
253
253
  setInterval(refresh, 5000);
254
254
  })();
255
255
  `;export{i as a};
256
- //# sourceMappingURL=chunk-CPXZWVKN.js.map
256
+ //# sourceMappingURL=chunk-BFY4D4RH.js.map
@@ -1,6 +1,6 @@
1
- import{c as se,d as de,e as J,f as E,g as K,h as D}from"./chunk-O5U5NVLR.js";import{a as ie}from"./chunk-CL53UVOF.js";import{e as ae,g as re,n as oe,p as j}from"./chunk-XIYWXCNU.js";import{a as te,b as ne}from"./chunk-I6HCIQCQ.js";import{a as ee}from"./chunk-N4HFUAPN.js";import{L as Q,S as Te,aa as F,ca as Z,da as U,ga as q,s as L,w as Ce}from"./chunk-54VYZE7A.js";import{existsSync as M,readFileSync as fe,writeFileSync as he,appendFileSync as De,mkdirSync as Me}from"fs";import{dirname as Ne,resolve as P}from"path";import{fileURLToPath as Ue}from"url";import{hostname as We}from"os";import{spawn as Oe}from"child_process";q();import{existsSync as ce,readFileSync as le,writeFileSync as Y,copyFileSync as Re}from"fs";import{resolve as pe}from"path";function W(e,t={}){let n=t.configPath||pe(process.cwd(),"agentx.json");if(!ce(n))throw new Error(`agentx.json not found at ${n}`);let a=JSON.parse(le(n,"utf-8")),r=e(a),o=typeof r=="string"?{summary:r}:r,s=JSON.stringify(a,null,2)+`
2
- `,l=n+".tmp";Y(l,s,"utf-8");try{JSON.parse(le(l,"utf-8"))}catch(p){throw new Error(`config did not round-trip cleanly: ${p.message}`)}let i;return t.skipBackup||(i=`${n}.bak.${Date.now()}`,Re(n,i)),Y(n,s,"utf-8"),t.skipReload||Pe().catch(()=>{}),{summary:o.summary,payload:o.payload,backupPath:i}}function ge(e,t={}){let n=t.configPath||pe(process.cwd(),"agentx.json");if(ce(n)&&!t.overwrite)throw new Error(`agentx.json already exists at ${n}. Pass overwrite=true to replace it.`);return Y(n,JSON.stringify(e,null,2)+`
3
- `,"utf-8"),{file:n}}async function Pe(){try{let t=U().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${t}/reload`,{method:"POST"}).catch(()=>null)}catch{}}function me(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",a=`<header class="ax-topbar">
1
+ import{c as de,d as le,e as K,f as E,g as Y,h as D}from"./chunk-OAA7TNB6.js";import{a as se}from"./chunk-DWZYVYZS.js";import{e as j,g as oe,n as ie,p as J}from"./chunk-XIYWXCNU.js";import{a as ae,b as re}from"./chunk-I6HCIQCQ.js";import{a as ne}from"./chunk-N4HFUAPN.js";import{L as ee,S as ze,aa as q,ca as te,da as U,ga as F,s as L,t as Z,w as Pe}from"./chunk-54VYZE7A.js";import{existsSync as M,readFileSync as he,writeFileSync as ve,appendFileSync as Ue,mkdirSync as We}from"fs";import{dirname as Oe,resolve as P}from"path";import{fileURLToPath as Be}from"url";import{hostname as He}from"os";import{spawn as Le}from"child_process";F();import{existsSync as pe,readFileSync as ce,writeFileSync as G,copyFileSync as _e}from"fs";import{resolve as ge}from"path";function W(e,t={}){let n=t.configPath||ge(process.cwd(),"agentx.json");if(!pe(n))throw new Error(`agentx.json not found at ${n}`);let a=JSON.parse(ce(n,"utf-8")),r=e(a),o=typeof r=="string"?{summary:r}:r,s=JSON.stringify(a,null,2)+`
2
+ `,l=n+".tmp";G(l,s,"utf-8");try{JSON.parse(ce(l,"utf-8"))}catch(p){throw new Error(`config did not round-trip cleanly: ${p.message}`)}let i;return t.skipBackup||(i=`${n}.bak.${Date.now()}`,_e(n,i)),G(n,s,"utf-8"),t.skipReload||De().catch(()=>{}),{summary:o.summary,payload:o.payload,backupPath:i}}function me(e,t={}){let n=t.configPath||ge(process.cwd(),"agentx.json");if(pe(n)&&!t.overwrite)throw new Error(`agentx.json already exists at ${n}. Pass overwrite=true to replace it.`);return G(n,JSON.stringify(e,null,2)+`
3
+ `,"utf-8"),{file:n}}async function De(){try{let t=U().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${t}/reload`,{method:"POST"}).catch(()=>null)}catch{}}function ue(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",a=`<header class="ax-topbar">
4
4
  <div class="ax-topbar__left">
5
5
  <div class="ax-brand">
6
6
  <span class="ax-brand__mark">AX</span>
@@ -16,7 +16,7 @@ import{c as se,d as de,e as J,f as E,g as K,h as D}from"./chunk-O5U5NVLR.js";imp
16
16
  <button data-theme-opt="light">Light</button>
17
17
  </div>
18
18
  </div>
19
- </header>`,r=D(1,"Team basics",E({name:"nodeName",label:"Team name",hint:"(what you'd call this AgentX install)",value:t,placeholder:"My Team",required:!0})),o=D(2,"First agent",K([E({name:"agentName",label:"Agent name",value:"Assistant",placeholder:"Support Bot",required:!0}),E({name:"agentId",label:"Agent id",hint:"(lowercase, no spaces)",value:"assistant",pattern:"[a-z0-9][a-z0-9_-]*",required:!0})])+E({name:"triggerWords",label:"Trigger words",hint:"(comma or space separated \u2014 e.g. <code>@support, support</code>)",value:"@assistant, assistant",required:!0})+K([E({name:"tier",label:"AI engine",type:"select",options:[{value:"claude-code",label:"Claude Code (recommended)",selected:!0},{value:"codex-cli",label:"Codex CLI"},{value:"opencode",label:"OpenCode CLI"},{value:"sdk",label:"Anthropic API (BYO key)"},{value:"orchestrator",label:"Orchestrator (any provider)"}]}),E({name:"model",label:"Model",hint:"(optional)",value:"claude-sonnet-4-6",placeholder:"claude-sonnet-4-6"})])+E({name:"personality",label:"Personality / instructions",hint:"(optional \u2014 what this agent does, in plain English)",type:"textarea",placeholder:"You are a support agent for Acme Co. Answer customer questions about our product, be friendly, keep replies short."})),s=D(3,"First channel",`
19
+ </header>`,r=D(1,"Team basics",E({name:"nodeName",label:"Team name",hint:"(what you'd call this AgentX install)",value:t,placeholder:"My Team",required:!0})),o=D(2,"First agent",Y([E({name:"agentName",label:"Agent name",value:"Assistant",placeholder:"Support Bot",required:!0}),E({name:"agentId",label:"Agent id",hint:"(lowercase, no spaces)",value:"assistant",pattern:"[a-z0-9][a-z0-9_-]*",required:!0})])+E({name:"triggerWords",label:"Trigger words",hint:"(comma or space separated \u2014 e.g. <code>@support, support</code>)",value:"@assistant, assistant",required:!0})+Y([E({name:"tier",label:"AI engine",type:"select",options:[{value:"claude-code",label:"Claude Code (recommended)",selected:!0},{value:"codex-cli",label:"Codex CLI"},{value:"opencode",label:"OpenCode CLI"},{value:"sdk",label:"Anthropic API (BYO key)"},{value:"orchestrator",label:"Orchestrator (any provider)"}]}),E({name:"model",label:"Model",hint:"(optional)",value:"claude-sonnet-4-6",placeholder:"claude-sonnet-4-6"})])+E({name:"personality",label:"Personality / instructions",hint:"(optional \u2014 what this agent does, in plain English)",type:"textarea",placeholder:"You are a support agent for Acme Co. Answer customer questions about our product, be friendly, keep replies short."})),s=D(3,"First channel",`
20
20
  <label class="ax-toggle"><input type="checkbox" id="enableTelegram" /> Connect Telegram now</label>
21
21
  <div class="ax-optional" id="telegramFields">
22
22
  ${E({name:"telegramAccountId",label:"Account id",hint:"(a label you choose \u2014 e.g. <code>support</code>)",value:"default"})}
@@ -26,7 +26,7 @@ import{c as se,d as de,e as J,f as E,g as K,h as D}from"./chunk-O5U5NVLR.js";imp
26
26
  `),l=D(4,"Anthropic API key",E({name:"anthropicApiKey",label:"API key",hint:"(optional \u2014 skip if you're using Claude Code)",type:"password",placeholder:"sk-ant-\u2026",extraAttrs:'autocomplete="off"'})+`<div class="ax-hint-block">
27
27
  The key is stored in <code>.env</code> as <code>ANTHROPIC_API_KEY</code> and used to authenticate requests to Anthropic. Keep it private.
28
28
  </div>`),i=e.configExists?`<div class="ax-banner">Existing install: <b>${e.agentCount}</b> agent(s), <b>${e.channelCount}</b> channel(s) already configured. This wizard will add to it.</div>`:"",p=`<div class="ax-wizard">
29
- <h1 class="ax-wizard__h1">${ie(n)}</h1>
29
+ <h1 class="ax-wizard__h1">${se(n)}</h1>
30
30
  <p class="ax-wizard__lead">Fill in the basics below. We'll write <code>agentx.json</code>, set up a folder for your first agent, and point you at the next step.</p>
31
31
 
32
32
  ${i}
@@ -39,11 +39,11 @@ import{c as se,d as de,e as J,f as E,g as K,h as D}from"./chunk-O5U5NVLR.js";imp
39
39
  ${s}
40
40
  ${l}
41
41
  <footer class="ax-actions">
42
- ${J("Save and continue",{type:"submit",primary:!0,id:"submitBtn"})}
43
- ${J("Skip, I'll do it later",{onclick:"window.location.href='/live'"})}
42
+ ${K("Save and continue",{type:"submit",primary:!0,id:"submitBtn"})}
43
+ ${K("Skip, I'll do it later",{onclick:"window.location.href='/live'"})}
44
44
  </footer>
45
45
  </form>
46
- </div>`;return de({title:"AgentX \u2014 Setup",activeTab:"custom",subtitle:"Setup",customHeader:a,noMain:!0,body:p,css:ze,scripts:_e})}var ze=`
46
+ </div>`;return le({title:"AgentX \u2014 Setup",activeTab:"custom",subtitle:"Setup",customHeader:a,noMain:!0,body:p,css:Me,scripts:Ne})}var Me=`
47
47
  /* Pre-dashboard topbar variant \u2014 no tab nav, the pills are the only chrome. */
48
48
  .ax-topbar__right a.ax-skip {
49
49
  padding: 4px 10px; border: 1px solid var(--ax-border-2); border-radius: 4px;
@@ -100,7 +100,7 @@ import{c as se,d as de,e as J,f as E,g as K,h as D}from"./chunk-O5U5NVLR.js";imp
100
100
  .ax-next-steps code { background: var(--ax-surface-2); padding: 1px 6px; border-radius: 3px; color: var(--ax-text); font-family: var(--ax-mono); font-size: var(--ax-fs-sm); }
101
101
  .ax-startd { margin-top: 14px; display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
102
102
  .ax-startd__status { color: var(--ax-text-2); font-size: var(--ax-fs-sm); }
103
- .ax-startd__status a { color: var(--ax-accent); }`,_e=`<script>
103
+ .ax-startd__status a { color: var(--ax-accent); }`,Ne=`<script>
104
104
  document.getElementById('enableTelegram').addEventListener('change', (e) => {
105
105
  document.getElementById('telegramFields').classList.toggle('is-show', e.target.checked);
106
106
  });
@@ -174,17 +174,17 @@ document.getElementById('wizard').addEventListener('submit', async (e) => {
174
174
  btn.disabled = false; btn.textContent = 'Save and continue';
175
175
  }
176
176
  });
177
- </script>`;q();function ve(e=process.cwd()){let t=P(e,"agentx.json");if(!M(t))return{configExists:!1,agentCount:0,channelCount:0};try{let n=JSON.parse(fe(t,"utf-8")),a=n.agents?Object.keys(n.agents).length:0,r=n.channels?Object.values(n.channels).filter(o=>o&&o.enabled).length:0;return{configExists:!0,agentCount:a,channelCount:r,nodeName:n.node?.name}}catch{return{configExists:!1,agentCount:0,channelCount:0}}}function Be(e,t=process.cwd()){if(!e.nodeName?.trim())throw new Error("Team name is required.");if(!e.agent?.id?.trim())throw new Error("Agent id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(e.agent.id))throw new Error("Agent id must be lowercase (letters, digits, -, _) and start with a letter or digit.");if(!e.agent.name?.trim())throw new Error("Agent name is required.");let n=He(e.agent.triggerWords);if(n.length===0)throw new Error("At least one trigger word is required.");if(e.agent.tier!=="claude-code"&&e.agent.tier!=="codex-cli"&&e.agent.tier!=="opencode"&&e.agent.tier!=="sdk"&&e.agent.tier!=="orchestrator")throw new Error("AI engine must be claude-code, codex-cli, opencode, sdk, or orchestrator.");let a=P(t,"agentx.json"),r=P(t,".env"),o=P(t,"agents",e.agent.id),s=ve(t);Me(o,{recursive:!0});let l=P(o,"CLAUDE.md");if(!M(l)){let f=e.agent.personality?.trim()||`You are ${e.agent.name}, an assistant on the ${e.nodeName} team.`;he(l,`# ${e.agent.name}
177
+ </script>`;F();function be(e=process.cwd()){let t=P(e,"agentx.json");if(!M(t))return{configExists:!1,agentCount:0,channelCount:0};try{let n=JSON.parse(he(t,"utf-8")),a=n.agents?Object.keys(n.agents).length:0,r=n.channels?Object.values(n.channels).filter(o=>o&&o.enabled).length:0;return{configExists:!0,agentCount:a,channelCount:r,nodeName:n.node?.name}}catch{return{configExists:!1,agentCount:0,channelCount:0}}}function qe(e,t=process.cwd()){if(!e.nodeName?.trim())throw new Error("Team name is required.");if(!e.agent?.id?.trim())throw new Error("Agent id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(e.agent.id))throw new Error("Agent id must be lowercase (letters, digits, -, _) and start with a letter or digit.");if(!e.agent.name?.trim())throw new Error("Agent name is required.");let n=Fe(e.agent.triggerWords);if(n.length===0)throw new Error("At least one trigger word is required.");if(e.agent.tier!=="claude-code"&&e.agent.tier!=="codex-cli"&&e.agent.tier!=="opencode"&&e.agent.tier!=="sdk"&&e.agent.tier!=="orchestrator")throw new Error("AI engine must be claude-code, codex-cli, opencode, sdk, or orchestrator.");let a=P(t,"agentx.json"),r=P(t,".env"),o=P(t,"agents",e.agent.id),s=be(t);We(o,{recursive:!0});let l=P(o,"CLAUDE.md");if(!M(l)){let f=e.agent.personality?.trim()||`You are ${e.agent.name}, an assistant on the ${e.nodeName} team.`;ve(l,`# ${e.agent.name}
178
178
 
179
179
  ${f}
180
- `)}let i=e.telegram?`TG_${e.agent.id.toUpperCase()}_BOT_TOKEN`:void 0,p;if(s.configExists)p=W(d=>{if(d.node=d.node||{},d.node.name||(d.node.name=e.nodeName),d.node.id||(d.node.id=be(e.nodeName)||"team"),d.node.bind||(d.node.bind="127.0.0.1:18800"),d.node.defaultAgent=d.node.defaultAgent||e.agent.id,d.providers=d.providers||{},d.providers.claude||(d.providers.claude={apiKey:"${ANTHROPIC_API_KEY}"}),d.agents=d.agents||{},d.agents[e.agent.id])throw new Error(`Agent "${e.agent.id}" already exists.`);return d.agents[e.agent.id]=xe(e,o,n),e.telegram&&(d.channels=d.channels||{},d.channels.telegram=d.channels.telegram||{enabled:!0,accounts:{},policy:{dm:"pair",group:"mention-required"}},d.channels.telegram.enabled=!0,d.channels.telegram.accounts=d.channels.telegram.accounts||{},d.channels.telegram.accounts[e.telegram.accountId]=ye(e,i)),{summary:`added agent "${e.agent.id}"`+(e.telegram?" + telegram account":"")}},{configPath:a}).backupPath;else{let f=Le(e,o,n,i);ge(f,{configPath:a})}Fe(r,e,i);let g=[];return(e.anthropicApiKey||!M(P(t,".env")))&&g.push("Double-check the API keys in .env"),e.agent.tier==="claude-code"&&g.push("Run claude --version to confirm Claude Code is installed (needed for the claude-code engine)"),e.agent.tier==="codex-cli"&&g.push("Run codex --version to confirm Codex CLI is installed (needed for the codex-cli engine)"),e.agent.tier==="opencode"&&g.push("Run opencode --version to confirm OpenCode is installed and authenticated"),g.push("Start the daemon: agentx daemon start"),g.push("Open the dashboard: http://127.0.0.1:4202"),{summary:s.configExists?`Added agent "${e.agent.id}" to your team.`:`Initialized your team with first agent "${e.agent.id}".`,nextSteps:g,backupPath:p}}function He(e){return(e||"").split(/[,\s]+/).map(t=>t.trim()).filter(Boolean).filter((t,n,a)=>a.indexOf(t)===n)}function be(e){return(e||"").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")}function Le(e,t,n,a){let o={node:{id:be(e.nodeName)||"team",name:e.nodeName,bind:"127.0.0.1:18800",defaultAgent:e.agent.id},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{[e.agent.id]:xe(e,t,n)},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},dashboard:{enabled:!0,port:4202,bind:"127.0.0.1",daemonUrl:"http://localhost:18800"},boards:[]};return e.telegram&&a?o.channels.telegram={enabled:!0,accounts:{[e.telegram.accountId]:ye(e,a)},policy:{dm:"pair",group:"mention-required"}}:o.channels.telegram={enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},o}function xe(e,t,n){let a={name:e.agent.name,workspace:t,tier:e.agent.tier,mentions:n,maxConcurrent:2,permissionMode:"default"};return e.agent.model&&(a.model=e.agent.model),e.agent.personality?.trim()&&(a.systemPrompt=e.agent.personality.trim().slice(0,400)),a}function ye(e,t){return e.telegram?.botUsername,{token:"${"+t+"}",agentBinding:e.agent.id}}function Fe(e,t,n){let a=M(e)?fe(e,"utf-8"):"",r=[];if(t.anthropicApiKey&&!a.includes("ANTHROPIC_API_KEY=")&&r.push(`ANTHROPIC_API_KEY=${t.anthropicApiKey}`),t.telegram&&n&&!a.includes(`${n}=`)&&r.push(`${n}=${t.telegram.botToken}`),!M(e)){he(e,[...["# AgentX environment variables","# (Never commit this file \u2014 it contains secrets.)",""],...r,""].join(`
180
+ `)}let i=e.telegram?`TG_${e.agent.id.toUpperCase()}_BOT_TOKEN`:void 0,p;if(s.configExists)p=W(d=>{if(d.node=d.node||{},d.node.name||(d.node.name=e.nodeName),d.node.id||(d.node.id=xe(e.nodeName)||"team"),d.node.bind||(d.node.bind="127.0.0.1:18800"),d.node.defaultAgent=d.node.defaultAgent||e.agent.id,d.providers=d.providers||{},d.providers.claude||(d.providers.claude={apiKey:"${ANTHROPIC_API_KEY}"}),d.agents=d.agents||{},d.agents[e.agent.id])throw new Error(`Agent "${e.agent.id}" already exists.`);return d.agents[e.agent.id]=ye(e,o,n),e.telegram&&(d.channels=d.channels||{},d.channels.telegram=d.channels.telegram||{enabled:!0,accounts:{},policy:{dm:"pair",group:"mention-required"}},d.channels.telegram.enabled=!0,d.channels.telegram.accounts=d.channels.telegram.accounts||{},d.channels.telegram.accounts[e.telegram.accountId]=ke(e,i)),{summary:`added agent "${e.agent.id}"`+(e.telegram?" + telegram account":"")}},{configPath:a}).backupPath;else{let f=je(e,o,n,i);me(f,{configPath:a})}Je(r,e,i);let g=[];return(e.anthropicApiKey||!M(P(t,".env")))&&g.push("Double-check the API keys in .env"),e.agent.tier==="claude-code"&&g.push("Run claude --version to confirm Claude Code is installed (needed for the claude-code engine)"),e.agent.tier==="codex-cli"&&g.push("Run codex --version to confirm Codex CLI is installed (needed for the codex-cli engine)"),e.agent.tier==="opencode"&&g.push("Run opencode --version to confirm OpenCode is installed and authenticated"),g.push("Start the daemon: agentx daemon start"),g.push("Open the dashboard: http://127.0.0.1:4202"),{summary:s.configExists?`Added agent "${e.agent.id}" to your team.`:`Initialized your team with first agent "${e.agent.id}".`,nextSteps:g,backupPath:p}}function Fe(e){return(e||"").split(/[,\s]+/).map(t=>t.trim()).filter(Boolean).filter((t,n,a)=>a.indexOf(t)===n)}function xe(e){return(e||"").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")}function je(e,t,n,a){let o={node:{id:xe(e.nodeName)||"team",name:e.nodeName,bind:"127.0.0.1:18800",defaultAgent:e.agent.id},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{[e.agent.id]:ye(e,t,n)},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},dashboard:{enabled:!0,port:4202,bind:"127.0.0.1",daemonUrl:"http://localhost:18800"},boards:[]};return e.telegram&&a?o.channels.telegram={enabled:!0,accounts:{[e.telegram.accountId]:ke(e,a)},policy:{dm:"pair",group:"mention-required"}}:o.channels.telegram={enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},o}function ye(e,t,n){let a={name:e.agent.name,workspace:t,tier:e.agent.tier,mentions:n,maxConcurrent:2,permissionMode:"default"};return e.agent.model&&(a.model=e.agent.model),e.agent.personality?.trim()&&(a.systemPrompt=e.agent.personality.trim().slice(0,400)),a}function ke(e,t){return e.telegram?.botUsername,{token:"${"+t+"}",agentBinding:e.agent.id}}function Je(e,t,n){let a=M(e)?he(e,"utf-8"):"",r=[];if(t.anthropicApiKey&&!a.includes("ANTHROPIC_API_KEY=")&&r.push(`ANTHROPIC_API_KEY=${t.anthropicApiKey}`),t.telegram&&n&&!a.includes(`${n}=`)&&r.push(`${n}=${t.telegram.botToken}`),!M(e)){ve(e,[...["# AgentX environment variables","# (Never commit this file \u2014 it contains secrets.)",""],...r,""].join(`
181
181
  `));return}if(r.length>0){let o=a.endsWith(`
182
182
  `)?"":`
183
- `;De(e,o+r.join(`
183
+ `;Ue(e,o+r.join(`
184
184
  `)+`
185
- `)}}function Nt(e,t){let n=ve(),a=n.nodeName||We().replace(/\.local$/,""),r=me(n,a);t.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),t.end(r)}async function Ut(e,t){let n="";await new Promise(r=>{e.on("data",o=>{n+=o}),e.on("end",()=>r())});let a;try{a=JSON.parse(n)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON"}));return}try{let r=Be(a);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(r))}catch(r){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:r.message||"wizard failed"}))}}async function Wt(e,t){t.setHeader("Content-Type","application/json");let n;try{n=U().node?.bind||"127.0.0.1:18800"}catch(s){t.writeHead(400),t.end(JSON.stringify({ok:!1,error:`Config validation failed: ${s.message}`}));return}let a=`http://${n.replace(/^0\.0\.0\.0/,"127.0.0.1")}`;if(await ue(a)){t.writeHead(200),t.end(JSON.stringify({ok:!0,url:a,alreadyRunning:!0}));return}let r=process.argv[1]||P(Ne(Ue(import.meta.url)),"cli.js");try{Oe(process.execPath,[r,"daemon","start"],{detached:!0,stdio:"ignore",cwd:process.cwd()}).unref()}catch(s){t.writeHead(500),t.end(JSON.stringify({ok:!1,error:`Failed to spawn daemon: ${s.message}`,manualUrl:a}));return}let o=Date.now()+12e3;for(;Date.now()<o;)if(await new Promise(s=>setTimeout(s,400)),await ue(a)){t.writeHead(200),t.end(JSON.stringify({ok:!0,url:a,alreadyRunning:!1}));return}t.writeHead(504),t.end(JSON.stringify({ok:!1,error:"Daemon spawn succeeded but never bound the port within 12s \u2014 check `agentx daemon status` and the dotfile log for errors.",manualUrl:a}))}async function ue(e){try{let t=await fetch(e,{method:"GET",signal:AbortSignal.timeout(800)});return t.status>0&&t.status<600}catch{return!1}}import{existsSync as qe,readFileSync as je}from"fs";q();function Ft(e){let t=te(e),n={};if(qe(t))try{n=Z(JSON.parse(je(t,"utf-8")))}catch{n={}}let a=F.safeParse(n?.approvals);return a.success?a.data:F.parse(void 0)}function qt(e){let t=e.indexOf(":");return t<=0||t===e.length-1?null:{channel:e.slice(0,t).trim(),chatId:e.slice(t+1).trim()}}async function jt(e,t={}){return ne(n=>{let a=n.approvals??={};e.defaultExpiryDays!==void 0&&(a.defaultExpiryDays=e.defaultExpiryDays),e.maxExpiryDays!==void 0&&(a.maxExpiryDays=e.maxExpiryDays),e.laterHours!==void 0&&(a.laterHours=e.laterHours),e.notifyAgent!==void 0&&(a.notifyAgent=e.notifyAgent);let r=a.digest??={};e.digestEnabled!==void 0&&(r.enabled=e.digestEnabled),e.digestTime!==void 0&&(r.time=e.digestTime),e.digestTimezone===null?delete r.timezone:e.digestTimezone!==void 0&&(r.timezone=e.digestTimezone),e.destination===null?delete r.destination:e.destination!==void 0&&(r.destination=e.destination);let o=a.popup??={};e.popupEnabled!==void 0&&(o.enabled=e.popupEnabled),e.popupSpeak!==void 0&&(o.speak=e.popupSpeak),e.popupVoice===null?delete o.voice:e.popupVoice!==void 0&&(o.voice=e.popupVoice),e.popupSound!==void 0&&(o.sound=e.popupSound),e.popupTimeoutSeconds!==void 0&&(o.timeoutSeconds=e.popupTimeoutSeconds),e.popupStyle!==void 0&&(o.style=e.popupStyle),e.popupTheme!==void 0&&(o.theme=e.popupTheme);let s=a.checkin??={};e.checkinEnabled!==void 0&&(s.enabled=e.checkinEnabled),e.checkinTimes!==void 0&&(s.times=e.checkinTimes),e.checkinDailyAt!==void 0&&(s.dailyAt=e.checkinDailyAt),e.checkinLists!==void 0&&(s.lists=e.checkinLists),e.checkinAgent===null?delete s.agent:e.checkinAgent!==void 0&&(s.agent=e.checkinAgent);let l=a.defaultExpiryDays??3,i=a.maxExpiryDays??30;if(l>i)throw new Error(`defaultExpiryDays (${l}) can't be more than maxExpiryDays (${i})`)},{configPath:t.configPath,reload:t.reload})}import{createServer as Je}from"http";var O=class{peers;cache=new Map;ttl=3e4;constructor(t){this.peers=t.map(n=>({url:n.replace(/\/$/,"")}))}async getRemoteAgents(){let t=[];return await Promise.all(this.peers.map(async n=>{try{let a=await this.fetchJson(`${n.url}/wiki/agents`);n.nodeId=a.nodeId;for(let r of a.agents||[])(r.totalEntries>0||r.totalArticles>0)&&t.push({...r,nodeId:a.nodeId,peerUrl:n.url})}catch{}})),t}async getRemoteArticles(t,n){try{return(await this.fetchJson(`${t}/wiki/articles?agent=${encodeURIComponent(n)}`)).articles||[]}catch{return[]}}async getRemoteArticle(t,n,a){try{let r=await this.fetchJson(`${t}/wiki/article?agent=${encodeURIComponent(n)}&path=${encodeURIComponent(a)}`);return{meta:{title:r.title,tags:r.tags||[],owner:r.owner,access:"public",created:r.created,lastUpdated:r.lastUpdated,sources:r.sources||[]},content:r.content,path:r.path}}catch{return null}}async fetchJson(t){let n=this.cache.get(t);if(n&&Date.now()-n.ts<this.ttl)return n.data;let a=await fetch(t,{signal:AbortSignal.timeout(5e3)});if(!a.ok)throw new Error(`HTTP ${a.status}`);let r=await a.json();return this.cache.set(t,{data:r,ts:Date.now()}),r}};function c(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Ke(e){return e.replace(/<!--\s*tags?:[^>]*-->\s*\n?/gi,"")}function ke(e,t){return`<a href="${t?`/agent/${encodeURIComponent(t)}/tag/${encodeURIComponent(e)}`:`/tag/${encodeURIComponent(e)}`}" class="tag">${c(e)}</a>`}function z(e,t){return(e||[]).map(n=>ke(n,t)).join(" ")}function Ye(e,t){if(!e)return;let n=t.get(e);if(n)return n;let a=new Set(t.values());if(a.has(e))return e;let r=e.endsWith(".md")?e:`${e}.md`;if(a.has(r))return r;let o=e.toLowerCase();for(let[s,l]of t)if(s.toLowerCase()===o)return l}function B(e,t,n=""){return se(Ke(e),{wikilink:(a,r)=>{let o=Ye(a,t);return o?`<a href="${n}/article/${encodeURIComponent(o)}" class="wikilink">${r}</a>`:`<a href="${n}/search?q=${encodeURIComponent(a)}" class="wikilink broken" title="Not found \u2014 click to search">${r}</a>`}})}var Ge=`<link rel="preconnect" href="https://fonts.googleapis.com">
185
+ `)}}function Bt(e,t){let n=be(),a=n.nodeName||He().replace(/\.local$/,""),r=ue(n,a);t.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),t.end(r)}async function Ht(e,t){let n="";await new Promise(r=>{e.on("data",o=>{n+=o}),e.on("end",()=>r())});let a;try{a=JSON.parse(n)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON"}));return}try{let r=qe(a);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(r))}catch(r){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:r.message||"wizard failed"}))}}async function Lt(e,t){t.setHeader("Content-Type","application/json");let n;try{n=U().node?.bind||"127.0.0.1:18800"}catch(s){t.writeHead(400),t.end(JSON.stringify({ok:!1,error:`Config validation failed: ${s.message}`}));return}let a=`http://${n.replace(/^0\.0\.0\.0/,"127.0.0.1")}`;if(await fe(a)){t.writeHead(200),t.end(JSON.stringify({ok:!0,url:a,alreadyRunning:!0}));return}let r=process.argv[1]||P(Oe(Be(import.meta.url)),"cli.js");try{Le(process.execPath,[r,"daemon","start"],{detached:!0,stdio:"ignore",cwd:process.cwd()}).unref()}catch(s){t.writeHead(500),t.end(JSON.stringify({ok:!1,error:`Failed to spawn daemon: ${s.message}`,manualUrl:a}));return}let o=Date.now()+12e3;for(;Date.now()<o;)if(await new Promise(s=>setTimeout(s,400)),await fe(a)){t.writeHead(200),t.end(JSON.stringify({ok:!0,url:a,alreadyRunning:!1}));return}t.writeHead(504),t.end(JSON.stringify({ok:!1,error:"Daemon spawn succeeded but never bound the port within 12s \u2014 check `agentx daemon status` and the dotfile log for errors.",manualUrl:a}))}async function fe(e){try{let t=await fetch(e,{method:"GET",signal:AbortSignal.timeout(800)});return t.status>0&&t.status<600}catch{return!1}}import{existsSync as Ke,readFileSync as Ye}from"fs";F();function Kt(e){let t=ae(e),n={};if(Ke(t))try{n=te(JSON.parse(Ye(t,"utf-8")))}catch{n={}}let a=q.safeParse(n?.approvals);return a.success?a.data:q.parse(void 0)}function Yt(e){let t=e.indexOf(":");return t<=0||t===e.length-1?null:{channel:e.slice(0,t).trim(),chatId:e.slice(t+1).trim()}}async function Gt(e,t={}){return re(n=>{let a=n.approvals??={};e.defaultExpiryDays!==void 0&&(a.defaultExpiryDays=e.defaultExpiryDays),e.maxExpiryDays!==void 0&&(a.maxExpiryDays=e.maxExpiryDays),e.laterHours!==void 0&&(a.laterHours=e.laterHours),e.notifyAgent!==void 0&&(a.notifyAgent=e.notifyAgent);let r=a.digest??={};e.digestEnabled!==void 0&&(r.enabled=e.digestEnabled),e.digestTime!==void 0&&(r.time=e.digestTime),e.digestTimezone===null?delete r.timezone:e.digestTimezone!==void 0&&(r.timezone=e.digestTimezone),e.destination===null?delete r.destination:e.destination!==void 0&&(r.destination=e.destination);let o=a.popup??={};e.popupEnabled!==void 0&&(o.enabled=e.popupEnabled),e.popupSpeak!==void 0&&(o.speak=e.popupSpeak),e.popupVoice===null?delete o.voice:e.popupVoice!==void 0&&(o.voice=e.popupVoice),e.popupSound!==void 0&&(o.sound=e.popupSound),e.popupTimeoutSeconds!==void 0&&(o.timeoutSeconds=e.popupTimeoutSeconds),e.popupStyle!==void 0&&(o.style=e.popupStyle),e.popupTheme!==void 0&&(o.theme=e.popupTheme);let s=a.checkin??={};e.checkinEnabled!==void 0&&(s.enabled=e.checkinEnabled),e.checkinTimes!==void 0&&(s.times=e.checkinTimes),e.checkinDailyAt!==void 0&&(s.dailyAt=e.checkinDailyAt),e.checkinLists!==void 0&&(s.lists=e.checkinLists),e.checkinAgent===null?delete s.agent:e.checkinAgent!==void 0&&(s.agent=e.checkinAgent);let l=a.defaultExpiryDays??3,i=a.maxExpiryDays??30;if(l>i)throw new Error(`defaultExpiryDays (${l}) can't be more than maxExpiryDays (${i})`)},{configPath:t.configPath,reload:t.reload})}import{createServer as Ge}from"http";var O=class{peers;cache=new Map;ttl=3e4;constructor(t){this.peers=t.map(n=>({url:n.replace(/\/$/,"")}))}async getRemoteAgents(){let t=[];return await Promise.all(this.peers.map(async n=>{try{let a=await this.fetchJson(`${n.url}/wiki/agents`);n.nodeId=a.nodeId;for(let r of a.agents||[])(r.totalEntries>0||r.totalArticles>0)&&t.push({...r,nodeId:a.nodeId,peerUrl:n.url})}catch{}})),t}async getRemoteArticles(t,n){try{return(await this.fetchJson(`${t}/wiki/articles?agent=${encodeURIComponent(n)}`)).articles||[]}catch{return[]}}async getRemoteArticle(t,n,a){try{let r=await this.fetchJson(`${t}/wiki/article?agent=${encodeURIComponent(n)}&path=${encodeURIComponent(a)}`);return{meta:{title:r.title,tags:r.tags||[],owner:r.owner,access:"public",created:r.created,lastUpdated:r.lastUpdated,sources:r.sources||[]},content:r.content,path:r.path}}catch{return null}}async fetchJson(t){let n=this.cache.get(t);if(n&&Date.now()-n.ts<this.ttl)return n.data;let a=await fetch(t,{signal:AbortSignal.timeout(5e3)});if(!a.ok)throw new Error(`HTTP ${a.status}`);let r=await a.json();return this.cache.set(t,{data:r,ts:Date.now()}),r}};function c(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Xe(e){return e.replace(/<!--\s*tags?:[^>]*-->\s*\n?/gi,"")}function we(e,t){return`<a href="${t?`/agent/${encodeURIComponent(t)}/tag/${encodeURIComponent(e)}`:`/tag/${encodeURIComponent(e)}`}" class="tag">${c(e)}</a>`}function z(e,t){return(e||[]).map(n=>we(n,t)).join(" ")}function Ve(e,t){if(!e)return;let n=t.get(e);if(n)return n;let a=new Set(t.values());if(a.has(e))return e;let r=e.endsWith(".md")?e:`${e}.md`;if(a.has(r))return r;let o=e.toLowerCase();for(let[s,l]of t)if(s.toLowerCase()===o)return l}function B(e,t,n=""){return de(Xe(e),{wikilink:(a,r)=>{let o=Ve(a,t);return o?`<a href="${n}/article/${encodeURIComponent(o)}" class="wikilink">${r}</a>`:`<a href="${n}/search?q=${encodeURIComponent(a)}" class="wikilink broken" title="Not found \u2014 click to search">${r}</a>`}})}var Qe=`<link rel="preconnect" href="https://fonts.googleapis.com">
186
186
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
187
- <link href="https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,300..600;1,6..72,300..600&family=Inter+Tight:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">`,Xe=`
187
+ <link href="https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,300..600;1,6..72,300..600&family=Inter+Tight:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">`,Ze=`
188
188
  :root {
189
189
  --bg: #FAF8F3;
190
190
  --bg-raised: #FFFFFF;
@@ -657,8 +657,8 @@ tr:hover td { background: var(--bg-hover); }
657
657
  <meta charset="utf-8">
658
658
  <meta name="viewport" content="width=device-width, initial-scale=1">
659
659
  <title>${c(e)} \u2014 AgentX Wiki</title>
660
- ${Ge}
661
- <style>${Xe}</style>
660
+ ${Qe}
661
+ <style>${Ze}</style>
662
662
  <script>(function(){try{var t=localStorage.getItem('wiki-theme');if(t)document.documentElement.setAttribute('data-theme',t)}catch(e){}})();</script>
663
663
  </head>
664
664
  <body>
@@ -703,7 +703,7 @@ tr:hover td { background: var(--bg-hover); }
703
703
  })();
704
704
  </script>
705
705
  </body>
706
- </html>`}function G(e){let t=new Map;for(let n of e){let a=n.path.includes("/")?n.path.split("/").slice(0,-1).join("/"):"/",r=t.get(a)||[];r.push(n),t.set(a,r)}return new Map([...t].sort((n,a)=>n[0].localeCompare(a[0])))}function X(e){return e==="/"?"Root":e.split("/").pop().replace(/-/g," ")}function C(e,t){let n='<div class="nav-section">';n+=`<a class="nav-item${t?"":" active"}" href="/">Home</a>`,n+='<a class="nav-item" href="/entries">All entries</a>',n+="</div>";for(let a of e){let r=`/agent/${encodeURIComponent(a.agentId)}`;n+='<div class="nav-section">',n+=`<a class="nav-agent-header" href="${r}">`,n+=`<span class="name">${c(a.agentId)}</span>`,n+=`<span class="badge">${a.totalArticles}</span>`,n+="</a>",n+='<div class="nav-agent-children">';let o=G(a.articles);for(let[s,l]of o){n+=`<div class="nav-agent-type-label">${X(s)}</div>`;for(let i of l){let g=`${a.agentId}/${i.path}`===t;n+=`<a class="nav-item${g?" active":""}" href="${r}/article/${encodeURIComponent(i.path)}">${c(i.title)}</a>`}}n+="</div>",n+="</div>"}return n}function Ve(e,t,n){let a=t||e.summary(),o=e.getSharedStore().listEntries().length,s=a.reduce((g,f)=>g+f.totalArticles,0),l=a.reduce((g,f)=>g+f.unabsorbed,0),i=new Set((n||[]).map(g=>g.agentId)),p=`<div class="page-head">
706
+ </html>`}function X(e){let t=new Map;for(let n of e){let a=n.path.includes("/")?n.path.split("/").slice(0,-1).join("/"):"/",r=t.get(a)||[];r.push(n),t.set(a,r)}return new Map([...t].sort((n,a)=>n[0].localeCompare(a[0])))}function V(e){return e==="/"?"Root":e.split("/").pop().replace(/-/g," ")}function C(e,t){let n='<div class="nav-section">';n+=`<a class="nav-item${t?"":" active"}" href="/">Home</a>`,n+='<a class="nav-item" href="/entries">All entries</a>',n+="</div>";for(let a of e){let r=`/agent/${encodeURIComponent(a.agentId)}`;n+='<div class="nav-section">',n+=`<a class="nav-agent-header" href="${r}">`,n+=`<span class="name">${c(a.agentId)}</span>`,n+=`<span class="badge">${a.totalArticles}</span>`,n+="</a>",n+='<div class="nav-agent-children">';let o=X(a.articles);for(let[s,l]of o){n+=`<div class="nav-agent-type-label">${V(s)}</div>`;for(let i of l){let g=`${a.agentId}/${i.path}`===t;n+=`<a class="nav-item${g?" active":""}" href="${r}/article/${encodeURIComponent(i.path)}">${c(i.title)}</a>`}}n+="</div>",n+="</div>"}return n}function et(e,t,n){let a=t||e.summary(),o=e.getSharedStore().listEntries().length,s=a.reduce((g,f)=>g+f.totalArticles,0),l=a.reduce((g,f)=>g+f.unabsorbed,0),i=new Set((n||[]).map(g=>g.agentId)),p=`<div class="page-head">
707
707
  <div>
708
708
  <h1>AgentX Wiki</h1>
709
709
  <p class="page-sub">Agent-owned institutional knowledge, typed and cross-referenced. Everything here compiles from raw conversation entries through the nightly absorb pass.</p>
@@ -712,33 +712,33 @@ tr:hover td { background: var(--bg-hover); }
712
712
  <span><strong>${g.totalArticles}</strong> articles</span>
713
713
  <span><strong>${g.totalEntries}</strong> entries</span>
714
714
  ${f}
715
- </div>`,g.articles.length>0){p+='<div class="article-list">';for(let u of g.articles.slice(0,6)){let A=z((u.tags||[]).slice(0,2),g.agentId);p+=`<div class="article-row">${A} <a class="article-title" href="/agent/${encodeURIComponent(g.agentId)}/article/${encodeURIComponent(u.path)}">${c(u.title)}</a></div>`}g.articles.length>6&&(p+=`<div class="article-row"><a class="article-title" style="color:var(--muted)" href="/agent/${encodeURIComponent(g.agentId)}">+ ${g.articles.length-6} more \u2192</a></div>`),p+="</div>"}p+="</div>"}return p+="</div>",$("Hub",C(a),p)}function Qe(e,t,n){let a=n||e.summary(),r=a.find(d=>d.agentId===t);if(!r)return $("Not Found",C(a),"<h1>Agent not found</h1>");let o=r.peerUrl!==void 0,s=e.getAgentEntries(t),l=r.articles||[],i=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">${c(t)}</span></nav>`;if(i+=`<div class="page-head"><div><h1>${c(t)}</h1>`,o&&(i+=`<p class="page-sub"><span class="tag" style="color:var(--cool);background:var(--cool-soft)">remote @ ${c(r.nodeId)}</span></p>`),i+="</div></div>",i+='<div class="stat-strip">',i+=`<div class="stat-cell"><div class="label">Articles</div><div class="number">${r.totalArticles}</div></div>`,i+=`<div class="stat-cell"><div class="label">Entries</div><div class="number">${r.totalEntries}</div></div>`,i+=`<div class="stat-cell"><div class="label">Unabsorbed</div><div class="number">${r.unabsorbed}</div></div>`,i+="</div>",l.length>0){i+='<div class="section-head"><h2>Articles</h2><span class="mono" style="font-size:12px;color:var(--muted)">'+l.length+" total</span></div>";let d=G(l);for(let[h,u]of d){i+=`<h3 class="display" style="font-size:17px;color:var(--muted);font-weight:500;margin:20px 0 8px">${X(h)}</h3>`,i+='<div class="agent-card" style="padding:4px 14px"><div class="article-list">';for(let A of u)i+=`<div class="article-row">${z((A.tags||[]).slice(0,3),t)} <a class="article-title" href="/agent/${encodeURIComponent(t)}/article/${encodeURIComponent(A.path)}">${c(A.title)}</a></div>`;i+="</div></div>"}}let p=s.slice(-5).reverse();if(p.length>0){i+='<div class="section-head"><h2>Recent entries</h2><a class="btn ghost" href="/entries">See all \u2192</a></div>';for(let d of p)i+=`<div class="entry-card">
715
+ </div>`,g.articles.length>0){p+='<div class="article-list">';for(let u of g.articles.slice(0,6)){let A=z((u.tags||[]).slice(0,2),g.agentId);p+=`<div class="article-row">${A} <a class="article-title" href="/agent/${encodeURIComponent(g.agentId)}/article/${encodeURIComponent(u.path)}">${c(u.title)}</a></div>`}g.articles.length>6&&(p+=`<div class="article-row"><a class="article-title" style="color:var(--muted)" href="/agent/${encodeURIComponent(g.agentId)}">+ ${g.articles.length-6} more \u2192</a></div>`),p+="</div>"}p+="</div>"}return p+="</div>",$("Hub",C(a),p)}function tt(e,t,n){let a=n||e.summary(),r=a.find(d=>d.agentId===t);if(!r)return $("Not Found",C(a),"<h1>Agent not found</h1>");let o=r.peerUrl!==void 0,s=e.getAgentEntries(t),l=r.articles||[],i=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">${c(t)}</span></nav>`;if(i+=`<div class="page-head"><div><h1>${c(t)}</h1>`,o&&(i+=`<p class="page-sub"><span class="tag" style="color:var(--cool);background:var(--cool-soft)">remote @ ${c(r.nodeId)}</span></p>`),i+="</div></div>",i+='<div class="stat-strip">',i+=`<div class="stat-cell"><div class="label">Articles</div><div class="number">${r.totalArticles}</div></div>`,i+=`<div class="stat-cell"><div class="label">Entries</div><div class="number">${r.totalEntries}</div></div>`,i+=`<div class="stat-cell"><div class="label">Unabsorbed</div><div class="number">${r.unabsorbed}</div></div>`,i+="</div>",l.length>0){i+='<div class="section-head"><h2>Articles</h2><span class="mono" style="font-size:12px;color:var(--muted)">'+l.length+" total</span></div>";let d=X(l);for(let[h,u]of d){i+=`<h3 class="display" style="font-size:17px;color:var(--muted);font-weight:500;margin:20px 0 8px">${V(h)}</h3>`,i+='<div class="agent-card" style="padding:4px 14px"><div class="article-list">';for(let A of u)i+=`<div class="article-row">${z((A.tags||[]).slice(0,3),t)} <a class="article-title" href="/agent/${encodeURIComponent(t)}/article/${encodeURIComponent(A.path)}">${c(A.title)}</a></div>`;i+="</div></div>"}}let p=s.slice(-5).reverse();if(p.length>0){i+='<div class="section-head"><h2>Recent entries</h2><a class="btn ghost" href="/entries">See all \u2192</a></div>';for(let d of p)i+=`<div class="entry-card">
716
716
  <div class="meta-line">${d.date} \xB7 via ${c(d.source)} \xB7 <code>${c(d.id)}</code></div>
717
717
  <p>${c(d.content.slice(0,300))}${d.content.length>300?"\u2026":""}</p>
718
718
  </div>`}let f=e.getAgentWiki(t).lint();if(f.length>0){i+=`<div class="section-head"><h2>Health issues</h2><span class="mono" style="font-size:12px;color:var(--warn)">${f.length}</span></div>`,i+='<div class="health-list">';for(let d of f)i+=`<div class="health-row">
719
719
  <span class="kind">${c(d.type)}</span>
720
720
  <span class="article">${c(d.article)}</span>
721
721
  <span class="msg">${c(d.message)}</span>
722
- </div>`;i+="</div>"}return $(t,C(a,t),i)}function Ze(e,t,n,a){let r=e.getAgentWiki(t),o=r.readArticle(n);if(!o)return null;let s=a||e.summary(),l=r.rebuildIndex(),i=new Map;for(let h of l.articles)i.set(h.title,h.path);let p=`/agent/${encodeURIComponent(t)}`,f=r.buildBacklinks()[o.meta.title]||[],d=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${p}">${c(t)}</a> <span class="sep">/</span> <span class="current">${c(o.meta.title)}</span></nav>`;if(d+=`<article class="prose"><h1>${c(o.meta.title)}</h1>`,d+='<dl class="meta">',o.meta.type&&(d+=`<dt>Type</dt><dd>${ke(o.meta.type,t)}</dd>`),o.meta.tags?.length&&(d+=`<dt>Tags</dt><dd>${z(o.meta.tags,t)}</dd>`),o.meta.owner&&(d+=`<dt>Owner</dt><dd>${c(o.meta.owner)}</dd>`),d+=`<dt>Created</dt><dd>${c(o.meta.created||"\u2014")}</dd>`,d+=`<dt>Updated</dt><dd>${c(o.meta.lastUpdated||"\u2014")}</dd>`,o.meta.sources?.length&&(d+=`<dt>Sources</dt><dd>${o.meta.sources.length} entries</dd>`),d+="</dl>",d+=B(o.content,i,p),f.length>0){d+='<div class="backlinks"><h4>Pages that link here</h4><ul>';for(let h of f){let u=r.readArticle(h);d+=`<li><a href="${p}/article/${encodeURIComponent(h)}">${c(u?.meta.title||h)}</a></li>`}d+="</ul></div>"}return d+="</article>",$(o.meta.title,C(s,`${t}/${n}`),d)}function et(e,t){let n=t||e.summary(),r=e.getSharedStore().listEntries(),o='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Entries</span></nav>';o+='<div class="page-head"><div><h1>All raw entries</h1><p class="page-sub">Every conversation line that the ingest pipeline captured. Absorb compiles these into typed articles nightly.</p></div></div>';let s=new Map;for(let l of r){let i=s.get(l.date)||[];i.push(l),s.set(l.date,i)}for(let[l,i]of[...s].reverse()){o+=`<div class="section-head"><h2>${l}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${i.length} entries</span></div>`;for(let p of i)o+=`<div class="entry-card">
722
+ </div>`;i+="</div>"}return $(t,C(a,t),i)}function nt(e,t,n,a){let r=e.getAgentWiki(t),o=r.readArticle(n);if(!o)return null;let s=a||e.summary(),l=r.rebuildIndex(),i=new Map;for(let h of l.articles)i.set(h.title,h.path);let p=`/agent/${encodeURIComponent(t)}`,f=r.buildBacklinks()[o.meta.title]||[],d=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${p}">${c(t)}</a> <span class="sep">/</span> <span class="current">${c(o.meta.title)}</span></nav>`;if(d+=`<article class="prose"><h1>${c(o.meta.title)}</h1>`,d+='<dl class="meta">',o.meta.type&&(d+=`<dt>Type</dt><dd>${we(o.meta.type,t)}</dd>`),o.meta.tags?.length&&(d+=`<dt>Tags</dt><dd>${z(o.meta.tags,t)}</dd>`),o.meta.owner&&(d+=`<dt>Owner</dt><dd>${c(o.meta.owner)}</dd>`),d+=`<dt>Created</dt><dd>${c(o.meta.created||"\u2014")}</dd>`,d+=`<dt>Updated</dt><dd>${c(o.meta.lastUpdated||"\u2014")}</dd>`,o.meta.sources?.length&&(d+=`<dt>Sources</dt><dd>${o.meta.sources.length} entries</dd>`),d+="</dl>",d+=B(o.content,i,p),f.length>0){d+='<div class="backlinks"><h4>Pages that link here</h4><ul>';for(let h of f){let u=r.readArticle(h);d+=`<li><a href="${p}/article/${encodeURIComponent(h)}">${c(u?.meta.title||h)}</a></li>`}d+="</ul></div>"}return d+="</article>",$(o.meta.title,C(s,`${t}/${n}`),d)}function at(e,t){let n=t||e.summary(),r=e.getSharedStore().listEntries(),o='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Entries</span></nav>';o+='<div class="page-head"><div><h1>All raw entries</h1><p class="page-sub">Every conversation line that the ingest pipeline captured. Absorb compiles these into typed articles nightly.</p></div></div>';let s=new Map;for(let l of r){let i=s.get(l.date)||[];i.push(l),s.set(l.date,i)}for(let[l,i]of[...s].reverse()){o+=`<div class="section-head"><h2>${l}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${i.length} entries</span></div>`;for(let p of i)o+=`<div class="entry-card">
723
723
  <div class="meta-line">
724
724
  <a href="/agent/${encodeURIComponent(p.agentId)}">${c(p.agentId)}</a>
725
725
  \xB7 via ${c(p.source)} \xB7 <code>${c(p.id)}</code>
726
726
  </div>
727
727
  <p>${c(p.content.slice(0,400))}${p.content.length>400?"\u2026":""}</p>
728
- </div>`}return $("All Entries",C(n),o)}function tt(e,t,n){let a=n||e.summary(),r='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Search</span></nav>';r+=`<div class="page-head"><div><h1>\u201C${c(t)}\u201D</h1><p class="page-sub">Full-text search across every agent's wiki.</p></div></div>`;let o=0,s=[];for(let l of a){let p=e.getAgentWiki(l.agentId).findRelevant(t,void 0,10);if(p.length>0){s.push(`<div class="section-head"><h2>${c(l.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${p.length} match${p.length===1?"":"es"}</span></div>`);for(let g of p){let f=`/agent/${encodeURIComponent(l.agentId)}`;s.push(`<div class="entry-card">
728
+ </div>`}return $("All Entries",C(n),o)}function rt(e,t,n){let a=n||e.summary(),r='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Search</span></nav>';r+=`<div class="page-head"><div><h1>\u201C${c(t)}\u201D</h1><p class="page-sub">Full-text search across every agent's wiki.</p></div></div>`;let o=0,s=[];for(let l of a){let p=e.getAgentWiki(l.agentId).findRelevant(t,void 0,10);if(p.length>0){s.push(`<div class="section-head"><h2>${c(l.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${p.length} match${p.length===1?"":"es"}</span></div>`);for(let g of p){let f=`/agent/${encodeURIComponent(l.agentId)}`;s.push(`<div class="entry-card">
729
729
  <div class="meta-line">${z((g.meta.tags||[]).slice(0,3),l.agentId)}</div>
730
730
  <h3><a href="${f}/article/${encodeURIComponent(g.path)}">${c(g.meta.title)}</a></h3>
731
731
  <p>${c(g.content.slice(0,240))}\u2026</p>
732
- </div>`)}o+=p.length}}return r+=s.join(""),o===0&&(r+='<p style="color:var(--muted);margin-top:24px">No matching articles found.</p>'),$(`Search: ${t}`,C(a),r,t)}function nt(e,t,n){let a=n||e.summary(),r='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Tag</span></nav>';r+=`<div class="page-head"><div><h1>${c(t)}</h1><p class="page-sub">All articles tagged <span class="tag">${c(t)}</span>, across every agent.</p></div></div>`;let o=0;for(let s of a){let l;try{l=e.getAgentWiki(s.agentId)}catch{continue}let i=l.findByTags([t],void 0,100);if(i.length!==0){r+=`<div class="section-head"><h2>${c(s.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${i.length}</span></div>`;for(let p of i){let g=`/agent/${encodeURIComponent(s.agentId)}`;r+=`<div class="entry-card">
732
+ </div>`)}o+=p.length}}return r+=s.join(""),o===0&&(r+='<p style="color:var(--muted);margin-top:24px">No matching articles found.</p>'),$(`Search: ${t}`,C(a),r,t)}function ot(e,t,n){let a=n||e.summary(),r='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Tag</span></nav>';r+=`<div class="page-head"><div><h1>${c(t)}</h1><p class="page-sub">All articles tagged <span class="tag">${c(t)}</span>, across every agent.</p></div></div>`;let o=0;for(let s of a){let l;try{l=e.getAgentWiki(s.agentId)}catch{continue}let i=l.findByTags([t],void 0,100);if(i.length!==0){r+=`<div class="section-head"><h2>${c(s.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${i.length}</span></div>`;for(let p of i){let g=`/agent/${encodeURIComponent(s.agentId)}`;r+=`<div class="entry-card">
733
733
  <div class="meta-line">${z((p.meta.tags||[]).slice(0,6),s.agentId)}</div>
734
734
  <h3><a href="${g}/article/${encodeURIComponent(p.path)}">${c(p.meta.title)}</a></h3>
735
- </div>`}o+=i.length}}return o===0&&(r+=`<p style="color:var(--muted);margin-top:24px">No articles tagged <code>${c(t)}</code>.</p>`),$(`Tag: ${t}`,C(a),r)}function at(e,t,n,a){let r=a||e.summary(),o;try{o=e.getAgentWiki(t)}catch{return $(`Tag: ${n}`,C(r),`<h1>Agent not found: ${c(t)}</h1>`)}let s=o.findByTags([n],void 0,100),l=`/agent/${encodeURIComponent(t)}`,i=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${l}">${c(t)}</a> <span class="sep">/</span> <span class="current">${c(n)}</span></nav>`;i+=`<div class="page-head"><div><h1>${c(n)}</h1><p class="page-sub">${s.length} article${s.length===1?"":"s"} tagged <code>${c(n)}</code> in <b>${c(t)}</b>.</p></div></div>`;for(let p of s)i+=`<div class="entry-card">
735
+ </div>`}o+=i.length}}return o===0&&(r+=`<p style="color:var(--muted);margin-top:24px">No articles tagged <code>${c(t)}</code>.</p>`),$(`Tag: ${t}`,C(a),r)}function it(e,t,n,a){let r=a||e.summary(),o;try{o=e.getAgentWiki(t)}catch{return $(`Tag: ${n}`,C(r),`<h1>Agent not found: ${c(t)}</h1>`)}let s=o.findByTags([n],void 0,100),l=`/agent/${encodeURIComponent(t)}`,i=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${l}">${c(t)}</a> <span class="sep">/</span> <span class="current">${c(n)}</span></nav>`;i+=`<div class="page-head"><div><h1>${c(n)}</h1><p class="page-sub">${s.length} article${s.length===1?"":"s"} tagged <code>${c(n)}</code> in <b>${c(t)}</b>.</p></div></div>`;for(let p of s)i+=`<div class="entry-card">
736
736
  <div class="meta-line">${z((p.meta.tags||[]).slice(0,6),t)}</div>
737
737
  <h3><a href="${l}/article/${encodeURIComponent(p.path)}">${c(p.meta.title)}</a></h3>
738
- </div>`;return $(`${t} \xB7 ${n}`,C(r),i)}function _(e,t,n){let a=e.rebuildIndex(),r=G(a.articles.map(s=>({title:s.title,path:s.path,tags:s.tags}))),o='<div class="nav-section">';o+=`<div class="nav-section-title">${c(t)}</div>`,o+=`<a class="nav-item${n?"":" active"}" href="/">Home</a>`,o+='<a class="nav-item" href="/lint">Health check</a>',o+="</div>";for(let[s,l]of r){o+='<div class="nav-section">',o+=`<div class="nav-section-title">${X(s)}</div>`;for(let i of l){let p=i.path===n;o+=`<a class="nav-item${p?" active":""}" href="/article/${encodeURIComponent(i.path)}">${c(i.title)}</a>`}o+="</div>"}return o}function rt(e){let{wikiDir:t,agentFilter:n,peerUrls:a=[],mode:r="graph",pathPrefix:o=""}=e,s=o.replace(/\/+$/,""),l=new ee(t,void 0,r),i=a.length>0?new O(a):null;return async(p,g)=>{let f=new URL(p.url||"/","http://localhost"),d=decodeURIComponent(f.pathname),h=s&&d.startsWith(s)?d.slice(s.length)||"/":d,u=null,A=200;try{if(h.startsWith("/remote/")&&i){let x=h.slice(8).split("/article/");if(x.length===2){let[y,v]=x,m=y.indexOf("/"),k=decodeURIComponent(y.slice(0,m)),b=y.slice(m+1),w=await i.getRemoteArticle(k,b,v);if(w){let R=await i.getRemoteAgents(),N=[...l.summary(),...R.map(I=>({...I,agentId:`${I.agentId} @${I.nodeId}`}))],S=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${c(b)} @ ${c(k)}</div>`;S+=`<h1>${c(w.meta.title)}</h1>`,S+='<dl class="meta">',S+=`<dt>Tags</dt><dd>${(w.meta.tags||[]).map(I=>`<span class="tag">${I}</span>`).join(" ")}</dd>`,S+=`<dt>Owner</dt><dd>${c(w.meta.owner)}</dd>`,S+=`<dt>Source</dt><dd><span class="tag">remote</span> ${c(k)}</dd>`,S+=`<dt>Updated</dt><dd>${w.meta.lastUpdated}</dd>`,S+="</dl>";let T=new Map;S+=B(w.content,T),u=$(w.meta.title,C(N),S)}}}if(!u&&n){let x=l.getAgentWiki(n);if(h==="/"||h===""){let y=x.rebuildIndex(),v=l.getAgentEntries(n),m=`<h1>${c(n)}</h1>`;if(m+='<div class="stats">',m+=`<div class="stat-card"><div class="number">${y.articles.length}</div><div class="label">Articles</div></div>`,m+=`<div class="stat-card"><div class="number">${v.length}</div><div class="label">Entries</div></div>`,m+="</div>",y.articles.length>0){m+="<h2>Articles</h2><table><tr><th>Title</th><th>Type</th><th>Updated</th></tr>";for(let k of y.articles)m+=`<tr><td><a href="/article/${encodeURIComponent(k.path)}">${c(k.title)}</a></td><td><span class="tag">${(k.tags||[]).slice(0,3).join(", ")}</span></td><td>${k.lastUpdated||""}</td></tr>`;m+="</table>"}u=$(n,_(x,n),m)}else if(h.startsWith("/article/")){let y=h.slice(9),v=x.readArticle(y);if(v){let m=x.rebuildIndex(),k=new Map;for(let w of m.articles)k.set(w.title,w.path);let b=`<h1>${c(v.meta.title)}</h1>`;b+='<dl class="meta">',b+=`<dt>Tags</dt><dd>${(v.meta.tags||[]).map(w=>`<span class="tag">${w}</span>`).join(" ")}</dd>`,b+=`<dt>Updated</dt><dd>${v.meta.lastUpdated}</dd>`,v.meta.sources?.length&&(b+=`<dt>Sources</dt><dd>${v.meta.sources.length} entries</dd>`),b+="</dl>",b+=B(v.content,k),u=$(v.meta.title,_(x,n,y),b)}}else if(h==="/lint"){let y=x.lint(),v="<h1>Health Check</h1>";if(y.length===0)v+='<p style="color:green;">No issues.</p>';else{v+="<table><tr><th>Type</th><th>Article</th><th>Issue</th></tr>";for(let m of y)v+=`<tr><td><span class="tag">${m.type}</span></td><td>${c(m.article)}</td><td>${c(m.message)}</td></tr>`;v+="</table>"}u=$("Health Check",_(x,n),v)}else if(h==="/search"){let y=f.searchParams.get("q")||"",v=await x.findRelevantReranked(y,void 0,20),m=`<h1>Search: "${c(y)}"</h1>`;for(let k of v)m+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent(k.path)}">${c(k.meta.title)}</a></h3><p>${c(k.content.slice(0,200))}...</p></div>`;v.length===0&&(m+="<p>No results.</p>"),u=$(`Search: ${y}`,_(x,n),m)}else if(h.startsWith("/tag/")){let y=decodeURIComponent(h.slice(5)),v=x.findByTags([y],void 0,100),m=`<h1>Tag: <a class="tag" href="#">${c(y)}</a></h1>`;m+=`<p>${v.length} article${v.length===1?"":"s"} tagged <code>${c(y)}</code></p>`;for(let k of v)m+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent(k.path)}">${c(k.meta.title)}</a></h3><div class="meta-line">${z((k.meta.tags||[]).slice(0,6))}</div></div>`;v.length===0&&(m+="<p>No articles with this tag.</p>"),u=$(`Tag: ${y}`,_(x,n),m)}}else{let x=i?await i.getRemoteAgents():[],y=l.summary(),v=new Map(y.map(b=>[b.agentId,b])),m=[],k=new Set;for(let b of y){let w=x.find(R=>R.agentId===b.agentId);w&&w.totalArticles>b.totalArticles?m.push({...w,totalEntries:Math.max(b.totalEntries,w.totalEntries),unabsorbed:Math.max(b.unabsorbed,w.unabsorbed)}):m.push(b),k.add(b.agentId)}for(let b of x)k.has(b.agentId)||(m.push(b),k.add(b.agentId));if(h==="/"||h==="")u=Ve(l,m,x);else if(h==="/entries")u=et(l,m);else if(h==="/search")u=tt(l,f.searchParams.get("q")||"",m);else if(h.startsWith("/tag/"))u=nt(l,decodeURIComponent(h.slice(5)),m);else if(h.match(/^\/agent\/[^/]+\/tag\/.+/)){let b=h.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);u=at(l,decodeURIComponent(b[1]),decodeURIComponent(b[2]),m)}else if(h.startsWith("/agent/")){let b=h.slice(7),w=b.indexOf("/article/");if(w===-1)u=Qe(l,b,m);else{let R=b.slice(0,w),N=b.slice(w+9);if(u=Ze(l,R,N,m),!u&&i){let S=x.find(T=>T.agentId===R);if(S){let T=await i.getRemoteArticle(S.peerUrl,R,N);if(T){let I=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${c(S.nodeId)}</span> / ${c(R)}</div>`;I+=`<h1>${c(T.meta.title)}</h1>`,I+='<dl class="meta">',I+=`<dt>Tags</dt><dd>${(T.meta.tags||[]).map(Ee=>`<span class="tag">${Ee}</span>`).join(" ")}</dd>`,I+=`<dt>Source</dt><dd><span class="tag">remote</span> ${c(S.nodeId)}</dd>`,I+=`<dt>Updated</dt><dd>${T.meta.lastUpdated}</dd>`,I+="</dl>",I+=B(T.content,new Map),u=$(T.meta.title,C(m),I)}}}}}}if(!u){A=404;let x=n?_(l.getAgentWiki(n),n):C(l.summary());u=$("Not Found",x,"<h1>Page not found</h1>")}}catch(x){A=500,u=$("Error","",`<h1>Error</h1><pre>${c(x.message)}</pre>`)}g.writeHead(A,{"Content-Type":"text/html; charset=utf-8"}),g.end(s?ot(u,s):u)}}function ot(e,t){e=e.replace(/(\s(?:href|action)=")\/(?!\/)/g,`$1${t}/`),e=e.replace(new RegExp(`(${t})${t}/`,"g"),`${t}/`);let n=`<a href="/admin" style="position:fixed;top:10px;right:14px;z-index:9999;padding:5px 11px;background:rgba(0,0,0,0.55);color:#fff;font:12px/1.2 'IBM Plex Sans',system-ui,sans-serif;text-decoration:none;border-radius:6px;border:1px solid rgba(255,255,255,0.18);backdrop-filter:blur(6px)">\u2190 Dashboard</a>`;return e=e.replace(/<body([^>]*)>/,`<body$1>${n}`),e}function Qt(e,t=4200,n,a=[],r="graph"){let o=rt({wikiDir:e,agentFilter:n,peerUrls:a,mode:r});Je((l,i)=>{o(l,i)}).listen(t)}Ce();function tn(e,t,n=20){return e.prepare(`SELECT task_id, agent_id, channel, chat_id, status, started_at, message_preview
738
+ </div>`;return $(`${t} \xB7 ${n}`,C(r),i)}function _(e,t,n){let a=e.rebuildIndex(),r=X(a.articles.map(s=>({title:s.title,path:s.path,tags:s.tags}))),o='<div class="nav-section">';o+=`<div class="nav-section-title">${c(t)}</div>`,o+=`<a class="nav-item${n?"":" active"}" href="/">Home</a>`,o+='<a class="nav-item" href="/lint">Health check</a>',o+="</div>";for(let[s,l]of r){o+='<div class="nav-section">',o+=`<div class="nav-section-title">${V(s)}</div>`;for(let i of l){let p=i.path===n;o+=`<a class="nav-item${p?" active":""}" href="/article/${encodeURIComponent(i.path)}">${c(i.title)}</a>`}o+="</div>"}return o}function st(e){let{wikiDir:t,agentFilter:n,peerUrls:a=[],mode:r="graph",pathPrefix:o=""}=e,s=o.replace(/\/+$/,""),l=new ne(t,void 0,r),i=a.length>0?new O(a):null;return async(p,g)=>{let f=new URL(p.url||"/","http://localhost"),d=decodeURIComponent(f.pathname),h=s&&d.startsWith(s)?d.slice(s.length)||"/":d,u=null,A=200;try{if(h.startsWith("/remote/")&&i){let x=h.slice(8).split("/article/");if(x.length===2){let[y,v]=x,m=y.indexOf("/"),k=decodeURIComponent(y.slice(0,m)),b=y.slice(m+1),w=await i.getRemoteArticle(k,b,v);if(w){let R=await i.getRemoteAgents(),N=[...l.summary(),...R.map(I=>({...I,agentId:`${I.agentId} @${I.nodeId}`}))],S=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${c(b)} @ ${c(k)}</div>`;S+=`<h1>${c(w.meta.title)}</h1>`,S+='<dl class="meta">',S+=`<dt>Tags</dt><dd>${(w.meta.tags||[]).map(I=>`<span class="tag">${I}</span>`).join(" ")}</dd>`,S+=`<dt>Owner</dt><dd>${c(w.meta.owner)}</dd>`,S+=`<dt>Source</dt><dd><span class="tag">remote</span> ${c(k)}</dd>`,S+=`<dt>Updated</dt><dd>${w.meta.lastUpdated}</dd>`,S+="</dl>";let T=new Map;S+=B(w.content,T),u=$(w.meta.title,C(N),S)}}}if(!u&&n){let x=l.getAgentWiki(n);if(h==="/"||h===""){let y=x.rebuildIndex(),v=l.getAgentEntries(n),m=`<h1>${c(n)}</h1>`;if(m+='<div class="stats">',m+=`<div class="stat-card"><div class="number">${y.articles.length}</div><div class="label">Articles</div></div>`,m+=`<div class="stat-card"><div class="number">${v.length}</div><div class="label">Entries</div></div>`,m+="</div>",y.articles.length>0){m+="<h2>Articles</h2><table><tr><th>Title</th><th>Type</th><th>Updated</th></tr>";for(let k of y.articles)m+=`<tr><td><a href="/article/${encodeURIComponent(k.path)}">${c(k.title)}</a></td><td><span class="tag">${(k.tags||[]).slice(0,3).join(", ")}</span></td><td>${k.lastUpdated||""}</td></tr>`;m+="</table>"}u=$(n,_(x,n),m)}else if(h.startsWith("/article/")){let y=h.slice(9),v=x.readArticle(y);if(v){let m=x.rebuildIndex(),k=new Map;for(let w of m.articles)k.set(w.title,w.path);let b=`<h1>${c(v.meta.title)}</h1>`;b+='<dl class="meta">',b+=`<dt>Tags</dt><dd>${(v.meta.tags||[]).map(w=>`<span class="tag">${w}</span>`).join(" ")}</dd>`,b+=`<dt>Updated</dt><dd>${v.meta.lastUpdated}</dd>`,v.meta.sources?.length&&(b+=`<dt>Sources</dt><dd>${v.meta.sources.length} entries</dd>`),b+="</dl>",b+=B(v.content,k),u=$(v.meta.title,_(x,n,y),b)}}else if(h==="/lint"){let y=x.lint(),v="<h1>Health Check</h1>";if(y.length===0)v+='<p style="color:green;">No issues.</p>';else{v+="<table><tr><th>Type</th><th>Article</th><th>Issue</th></tr>";for(let m of y)v+=`<tr><td><span class="tag">${m.type}</span></td><td>${c(m.article)}</td><td>${c(m.message)}</td></tr>`;v+="</table>"}u=$("Health Check",_(x,n),v)}else if(h==="/search"){let y=f.searchParams.get("q")||"",v=await x.findRelevantReranked(y,void 0,20),m=`<h1>Search: "${c(y)}"</h1>`;for(let k of v)m+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent(k.path)}">${c(k.meta.title)}</a></h3><p>${c(k.content.slice(0,200))}...</p></div>`;v.length===0&&(m+="<p>No results.</p>"),u=$(`Search: ${y}`,_(x,n),m)}else if(h.startsWith("/tag/")){let y=decodeURIComponent(h.slice(5)),v=x.findByTags([y],void 0,100),m=`<h1>Tag: <a class="tag" href="#">${c(y)}</a></h1>`;m+=`<p>${v.length} article${v.length===1?"":"s"} tagged <code>${c(y)}</code></p>`;for(let k of v)m+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent(k.path)}">${c(k.meta.title)}</a></h3><div class="meta-line">${z((k.meta.tags||[]).slice(0,6))}</div></div>`;v.length===0&&(m+="<p>No articles with this tag.</p>"),u=$(`Tag: ${y}`,_(x,n),m)}}else{let x=i?await i.getRemoteAgents():[],y=l.summary(),v=new Map(y.map(b=>[b.agentId,b])),m=[],k=new Set;for(let b of y){let w=x.find(R=>R.agentId===b.agentId);w&&w.totalArticles>b.totalArticles?m.push({...w,totalEntries:Math.max(b.totalEntries,w.totalEntries),unabsorbed:Math.max(b.unabsorbed,w.unabsorbed)}):m.push(b),k.add(b.agentId)}for(let b of x)k.has(b.agentId)||(m.push(b),k.add(b.agentId));if(h==="/"||h==="")u=et(l,m,x);else if(h==="/entries")u=at(l,m);else if(h==="/search")u=rt(l,f.searchParams.get("q")||"",m);else if(h.startsWith("/tag/"))u=ot(l,decodeURIComponent(h.slice(5)),m);else if(h.match(/^\/agent\/[^/]+\/tag\/.+/)){let b=h.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);u=it(l,decodeURIComponent(b[1]),decodeURIComponent(b[2]),m)}else if(h.startsWith("/agent/")){let b=h.slice(7),w=b.indexOf("/article/");if(w===-1)u=tt(l,b,m);else{let R=b.slice(0,w),N=b.slice(w+9);if(u=nt(l,R,N,m),!u&&i){let S=x.find(T=>T.agentId===R);if(S){let T=await i.getRemoteArticle(S.peerUrl,R,N);if(T){let I=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${c(S.nodeId)}</span> / ${c(R)}</div>`;I+=`<h1>${c(T.meta.title)}</h1>`,I+='<dl class="meta">',I+=`<dt>Tags</dt><dd>${(T.meta.tags||[]).map(Re=>`<span class="tag">${Re}</span>`).join(" ")}</dd>`,I+=`<dt>Source</dt><dd><span class="tag">remote</span> ${c(S.nodeId)}</dd>`,I+=`<dt>Updated</dt><dd>${T.meta.lastUpdated}</dd>`,I+="</dl>",I+=B(T.content,new Map),u=$(T.meta.title,C(m),I)}}}}}}if(!u){A=404;let x=n?_(l.getAgentWiki(n),n):C(l.summary());u=$("Not Found",x,"<h1>Page not found</h1>")}}catch(x){A=500,u=$("Error","",`<h1>Error</h1><pre>${c(x.message)}</pre>`)}g.writeHead(A,{"Content-Type":"text/html; charset=utf-8"}),g.end(s?dt(u,s):u)}}function dt(e,t){e=e.replace(/(\s(?:href|action)=")\/(?!\/)/g,`$1${t}/`),e=e.replace(new RegExp(`(${t})${t}/`,"g"),`${t}/`);let n=`<a href="/admin" style="position:fixed;top:10px;right:14px;z-index:9999;padding:5px 11px;background:rgba(0,0,0,0.55);color:#fff;font:12px/1.2 'IBM Plex Sans',system-ui,sans-serif;text-decoration:none;border-radius:6px;border:1px solid rgba(255,255,255,0.18);backdrop-filter:blur(6px)">\u2190 Dashboard</a>`;return e=e.replace(/<body([^>]*)>/,`<body$1>${n}`),e}function nn(e,t=4200,n,a=[],r="graph"){let o=st({wikiDir:e,agentFilter:n,peerUrls:a,mode:r});Ge((l,i)=>{o(l,i)}).listen(t)}Pe();function on(e,t,n=20){return e.prepare(`SELECT task_id, agent_id, channel, chat_id, status, started_at, message_preview
739
739
  FROM task_traces
740
740
  WHERE person = ? AND (channel IS NULL OR channel != 'a2a')
741
- ORDER BY started_at DESC LIMIT ?`).all(t,Math.max(1,Math.min(n,500))).map(r=>({taskId:r.task_id,agentId:r.agent_id,channel:r.channel,chatId:r.chat_id,status:r.status,startedAt:r.started_at,messagePreview:r.message_preview}))}function nn(e,t){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'requests'").get()?e.prepare("PRAGMA table_info(requests)").all().some(o=>o.name==="person")?e.prepare(`SELECT id, state, channel, agent_id, text, created_at FROM requests
742
- WHERE person = ? AND state IN (${L.map(()=>"?").join(",")})
743
- ORDER BY created_at`).all(t,...L).map(o=>({id:o.id,state:o.state,channel:o.channel,agentId:o.agent_id,text:o.text,createdAt:o.created_at})):[]:[]}Te();var V="member:",it=90,st="members",dt="tailscale-user-login",lt=400,ct=60*60*1e3;function pt(e){let t=e.scopes.find(n=>n.startsWith(V));return t?t.slice(V.length):null}function we(e,t){if(!e)return null;let n=t.verify(e),a=n?pt(n):null;return n&&a?{rec:n,personId:a}:null}function ln(e,t){let n=e.people().find(l=>l.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:a,record:r}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${V}${n.id}`],expiresInDays:it}),{code:o,expiresAt:s}=e.codes.create({token:a,tokenId:r.id,name:n.id});return e.members.log({person:n.id,device:r.id,event:"invited"}),{ok:!0,code:o,expiresAt:s,tokenId:r.id,person:n}}var gt="The private network says someone else is connecting from this machine. Ask the owner for a new code.",mt="Too many machines are waiting for the owner's answer. Try again later.",$e=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function Ae(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function ut(e){if(!Ae(e))return null;let t=$e(e,dt).toLowerCase();return t?t.slice(0,80):null}function ft(e){let t=e.socket?.remoteAddress||"unknown";if(!Ae(e))return t;let n=$e(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function ht(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function vt(e){return e.identities.map(Q).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function cn(e,t){let n=Date.now(),a=t.now??Date.now,r=t.log??(m=>console.log(m)),o=ft(e),s=t.limiter.retryAfter(o);if(s>0)return r(`[member] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let l=null,i="";try{let m=await oe(e,2048);l=m.code,i=ht(m.machine)}catch{}let p=t.codes.redeem(l),g=p?we(p.token,t.tokens):null;if(await xt(n,t.minMs??lt),!p||!g)return t.limiter.fail(o),r(`[member] pair-code failed from ${o}`),{status:401,body:{error:j}};t.limiter.succeed(o);let{rec:f,personId:d}=g,h=t.people().find(m=>m.id===d);if(!h)return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:"person no longer listed"}),r(`[member] pair-code for ${d} refused from ${o}: person no longer listed`),{status:403,body:{error:j}};let u=ut(e),A=vt(h);if(A.length&&(!u||!A.includes(u)))return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:`network login ${u??"missing"}; expected ${A.join(" or ")}`}),r(`[member] ${d}: pairing from ${o} refused: the network says "${u??"nobody"}", expected ${A.join(" or ")}`),{status:403,body:{error:gt}};let x=i||"Unnamed machine",y=h.name.slice(0,40),v=re(t.root,{title:`New machine for ${y}`,ask:`From ${o}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${x}". Let it see ${y}'s own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:st},{now:a()});return v.ok?(t.members.add({tokenId:f.id,personId:d,name:x,state:"pending",cardId:v.card.id,address:o,...u?{network:u}:{},createdAt:new Date(a()).toISOString()}),t.members.log({person:d,device:f.id,event:"paired",address:o,detail:x}),r(`[member] ${d} paired "${x}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:d,name:x,state:"pending"},token:p.token}):(t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:v.error}),r(`[member] ${d}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:mt}})}var H="this machine is not paired",bt="waiting for the owner to approve this machine";function pn(e,t,n){let a=t.now??Date.now,r=t.log??(g=>console.log(g)),o=we(e,t.tokens);if(!o)return{ok:!1,status:401,error:H};let{rec:s,personId:l}=o,i=t.members.byToken(s.id);if(!i||i.state==="removed"||i.personId!==l)return{ok:!1,status:401,error:H};if(t.people&&!t.people().some(g=>g.id===l))return Se(t,s.id,"person no longer listed"),r(`[member] ${l}: "${i.name}" ended: person no longer listed`),{ok:!1,status:401,error:H};if(i.state==="pending"){let g=i.cardId?ae(t.root,i.cardId):null,f=g?g.status==="decided"?g.verdict:g.status==="expired"?"no":null:null;if(f==="yes")i=t.members.update(s.id,{state:"active",approvedAt:new Date(a()).toISOString()})??i,t.members.log({person:l,device:s.id,event:"approved",detail:g?.decided_by}),r(`[member] ${l}: "${i.name}" approved`);else if(f==="no"){let d=g?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(s.id),t.members.update(s.id,{state:"removed",removedAt:new Date(a()).toISOString(),removedReason:d}),t.members.log({person:l,device:s.id,event:"refused",detail:d}),r(`[member] ${l}: "${i.name}" refused: ${d}`),{ok:!1,status:401,error:H}}else return{ok:!1,status:403,error:bt,waiting:!0}}let p=i.lastSeenAt?Date.parse(i.lastSeenAt):0;return n&&(a()-p>=ct||i.lastAddress!==n)&&(i=t.members.update(s.id,{lastSeenAt:new Date(a()).toISOString(),lastAddress:n})??i,t.members.log({person:l,device:s.id,event:"signed-in",address:n})),{ok:!0,device:i,personId:l,rec:s}}function Se(e,t,n="removed by the owner"){let a=e.members.byToken(t);if(!a)return null;e.tokens.revoke(t);let r=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:a.personId,device:t,event:"removed",detail:n}),r}function gn(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Se(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function xt(e,t){let n=e+t-Date.now();n>0&&await new Promise(a=>setTimeout(a,n))}var Ie=["gitlab","github"];function yt(e,t,n){let a=String(t||"").trim().toLowerCase();if(!Ie.includes(a))throw new Error(`Request status works on ${Ie.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let r=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...r,a])]:r.filter(o=>o!==a),`request status on ${a} is ${n?"on":"off"}`}function fn(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function hn(e){let{summary:t}=W(n=>yt(n,e?.channel,!!e?.enabled));return{summary:t}}var kt="https://ntfy.sh";function bn(e){return{enabled:!!e?.enabled,server:e?.server||kt,topicSet:!!e?.topic,tokenSet:!!e?.token}}function xn(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let a=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(a))throw new Error("ntfy server must be an http(s) URL");n.server=a}if("topic"in t){let a=String(t.topic).trim();if(!a)throw new Error("ntfy topic cannot be empty");n.topic=a}if("token"in t){let a=String(t.token??"").trim();a?n.token=a:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{W as a,ve as b,Nt as c,Ut as d,Wt as e,Ft as f,qt as g,jt as h,tn as i,nn as j,it as k,ln as l,ft as m,cn as n,pn as o,Se as p,gn as q,Ie as r,yt as s,fn as t,hn as u,bn as v,xn as w,rt as x,Qt as y};
744
- //# sourceMappingURL=chunk-F7LZTO6I.js.map
741
+ ORDER BY started_at DESC LIMIT ?`).all(t,Math.max(1,Math.min(n,500))).map(r=>({taskId:r.task_id,agentId:r.agent_id,channel:r.channel,chatId:r.chat_id,status:r.status,startedAt:r.started_at,messagePreview:r.message_preview}))}function lt(e){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'requests'").get()?e.prepare("PRAGMA table_info(requests)").all().some(a=>a.name==="person"):!1}function $e(e,t,n,a,...r){return lt(e)?e.prepare(`SELECT id, state, channel, agent_id, text, created_at FROM requests
742
+ WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
743
+ ${a}`).all(t,...n,...r).map(s=>({id:s.id,state:s.state,channel:s.channel,agentId:s.agent_id,text:s.text,createdAt:s.created_at})):[]}function sn(e,t){return $e(e,t,L,"ORDER BY created_at")}function dn(e,t,n=50){return $e(e,t,[...L,...Z],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}ze();var Q="member:",ct=90,pt="members",gt="tailscale-user-login",mt=400,ut=60*60*1e3;function ft(e){let t=e.scopes.find(n=>n.startsWith(Q));return t?t.slice(Q.length):null}function Ae(e,t){if(!e)return null;let n=t.verify(e),a=n?ft(n):null;return n&&a?{rec:n,personId:a}:null}function un(e,t){let n=e.people().find(l=>l.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:a,record:r}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${Q}${n.id}`],expiresInDays:ct}),{code:o,expiresAt:s}=e.codes.create({token:a,tokenId:r.id,name:n.id});return e.members.log({person:n.id,device:r.id,event:"invited"}),{ok:!0,code:o,expiresAt:s,tokenId:r.id,person:n}}var ht="The private network says someone else is connecting from this machine. Ask the owner for a new code.",vt="Too many machines are waiting for the owner's answer. Try again later.",Se=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function Ie(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function bt(e){if(!Ie(e))return null;let t=Se(e,gt).toLowerCase();return t?t.slice(0,80):null}function xt(e){let t=e.socket?.remoteAddress||"unknown";if(!Ie(e))return t;let n=Se(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function yt(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function kt(e){return e.identities.map(ee).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function fn(e,t){let n=Date.now(),a=t.now??Date.now,r=t.log??(m=>console.log(m)),o=xt(e),s=t.limiter.retryAfter(o);if(s>0)return r(`[member] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let l=null,i="";try{let m=await ie(e,2048);l=m.code,i=yt(m.machine)}catch{}let p=t.codes.redeem(l),g=p?Ae(p.token,t.tokens):null;if(await $t(n,t.minMs??mt),!p||!g)return t.limiter.fail(o),r(`[member] pair-code failed from ${o}`),{status:401,body:{error:J}};t.limiter.succeed(o);let{rec:f,personId:d}=g,h=t.people().find(m=>m.id===d);if(!h)return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:"person no longer listed"}),r(`[member] pair-code for ${d} refused from ${o}: person no longer listed`),{status:403,body:{error:J}};let u=bt(e),A=kt(h);if(A.length&&(!u||!A.includes(u)))return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:`network login ${u??"missing"}; expected ${A.join(" or ")}`}),r(`[member] ${d}: pairing from ${o} refused: the network says "${u??"nobody"}", expected ${A.join(" or ")}`),{status:403,body:{error:ht}};let x=i||"Unnamed machine",y=h.name.slice(0,40),v=oe(t.root,{title:`New machine for ${y}`,ask:`From ${o}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${x}". Let it see ${y}'s own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:pt},{now:a()});return v.ok?(t.members.add({tokenId:f.id,personId:d,name:x,state:"pending",cardId:v.card.id,address:o,...u?{network:u}:{},createdAt:new Date(a()).toISOString()}),t.members.log({person:d,device:f.id,event:"paired",address:o,detail:x}),r(`[member] ${d} paired "${x}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:d,name:x,state:"pending"},token:p.token}):(t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:v.error}),r(`[member] ${d}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:vt}})}var H="this machine is not paired",wt="waiting for the owner to approve this machine";function Ee(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function hn(e,t){return t.state==="pending"&&t.cardId?Ee(j(e,t.cardId)):null}function vn(e,t,n){let a=t.now??Date.now,r=t.log??(g=>console.log(g)),o=Ae(e,t.tokens);if(!o)return{ok:!1,status:401,error:H};let{rec:s,personId:l}=o,i=t.members.byToken(s.id);if(!i||i.state==="removed"||i.personId!==l)return{ok:!1,status:401,error:H};if(t.people&&!t.people().some(g=>g.id===l))return Ce(t,s.id,"person no longer listed"),r(`[member] ${l}: "${i.name}" ended: person no longer listed`),{ok:!1,status:401,error:H};if(i.state==="pending"){let g=i.cardId?j(t.root,i.cardId):null,f=Ee(g);if(f==="yes")i=t.members.update(s.id,{state:"active",approvedAt:new Date(a()).toISOString()})??i,t.members.log({person:l,device:s.id,event:"approved",detail:g?.decided_by}),r(`[member] ${l}: "${i.name}" approved`);else if(f==="no"){let d=g?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(s.id),t.members.update(s.id,{state:"removed",removedAt:new Date(a()).toISOString(),removedReason:d}),t.members.log({person:l,device:s.id,event:"refused",detail:d}),r(`[member] ${l}: "${i.name}" refused: ${d}`),{ok:!1,status:401,error:H}}else return{ok:!1,status:403,error:wt,waiting:!0}}let p=i.lastSeenAt?Date.parse(i.lastSeenAt):0;return n&&(a()-p>=ut||i.lastAddress!==n)&&(i=t.members.update(s.id,{lastSeenAt:new Date(a()).toISOString(),lastAddress:n})??i,t.members.log({person:l,device:s.id,event:"signed-in",address:n})),{ok:!0,device:i,personId:l,rec:s}}function Ce(e,t,n="removed by the owner"){let a=e.members.byToken(t);if(!a)return null;e.tokens.revoke(t);let r=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:a.personId,device:t,event:"removed",detail:n}),r}function bn(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Ce(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function $t(e,t){let n=e+t-Date.now();n>0&&await new Promise(a=>setTimeout(a,n))}var Te=["gitlab","github"];function At(e,t,n){let a=String(t||"").trim().toLowerCase();if(!Te.includes(a))throw new Error(`Request status works on ${Te.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let r=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...r,a])]:r.filter(o=>o!==a),`request status on ${a} is ${n?"on":"off"}`}function kn(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function wn(e){let{summary:t}=W(n=>At(n,e?.channel,!!e?.enabled));return{summary:t}}var St="https://ntfy.sh";function An(e){return{enabled:!!e?.enabled,server:e?.server||St,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Sn(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let a=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(a))throw new Error("ntfy server must be an http(s) URL");n.server=a}if("topic"in t){let a=String(t.topic).trim();if(!a)throw new Error("ntfy topic cannot be empty");n.topic=a}if("token"in t){let a=String(t.token??"").trim();a?n.token=a:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{W as a,be as b,Bt as c,Ht as d,Lt as e,Kt as f,Yt as g,Gt as h,on as i,sn as j,dn as k,ct as l,un as m,xt as n,fn as o,hn as p,vn as q,Ce as r,bn as s,Te as t,At as u,kn as v,wn as w,An as x,Sn as y,st as z,nn as A};
744
+ //# sourceMappingURL=chunk-BUELCBBV.js.map