agentix-cli 0.213.3 → 0.214.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{board-dashboard-RWX4F43G.js → board-dashboard-SHU4BWRO.js} +3 -3
- package/dist/{board-dashboard-RWX4F43G.js.map → board-dashboard-SHU4BWRO.js.map} +1 -1
- package/dist/{chunk-YR6GDF4W.js → chunk-2KNI7ZRN.js} +87 -147
- package/dist/chunk-2KNI7ZRN.js.map +1 -0
- package/dist/{chunk-SMZQLUJH.js → chunk-4ZD2C76P.js} +2 -2
- package/dist/{chunk-3327JD6L.js → chunk-C3O2ER6D.js} +2 -2
- package/dist/chunk-CSC45PA7.js +62 -0
- package/dist/chunk-CSC45PA7.js.map +1 -0
- package/dist/{chunk-3GWIV2YO.js → chunk-OQNJIIR2.js} +2 -2
- package/dist/{chunk-3GWIV2YO.js.map → chunk-OQNJIIR2.js.map} +1 -1
- package/dist/{chunk-D7B35QCZ.js → chunk-Z4WM7MKP.js} +297 -297
- package/dist/chunk-Z4WM7MKP.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{doctor-TK7LVXJ6.js → doctor-GP2KVKWE.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{program-GXEVAQRW.js → program-L3BX5FJ3.js} +232 -232
- package/dist/program-L3BX5FJ3.js.map +1 -0
- package/dist/{tool-2VRNH43W.js → tool-ZCSGJ2ZF.js} +9 -9
- package/dist/tool-ZCSGJ2ZF.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-D7B35QCZ.js.map +0 -1
- package/dist/chunk-YR6GDF4W.js.map +0 -1
- package/dist/program-GXEVAQRW.js.map +0 -1
- package/dist/tool-2VRNH43W.js.map +0 -1
- /package/dist/{chunk-SMZQLUJH.js.map → chunk-4ZD2C76P.js.map} +0 -0
- /package/dist/{chunk-3327JD6L.js.map → chunk-C3O2ER6D.js.map} +0 -0
- /package/dist/{doctor-TK7LVXJ6.js.map → doctor-GP2KVKWE.js.map} +0 -0
|
@@ -1,76 +1,16 @@
|
|
|
1
|
-
import{a as ft}from"./chunk-GTJIKXDB.js";import{H as
|
|
2
|
-
`).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var
|
|
3
|
-
`),
|
|
4
|
-
`).pop()?.slice(0,300)||"no output";async function
|
|
5
|
-
`,{mode:384}),
|
|
1
|
+
import{a as ft}from"./chunk-GTJIKXDB.js";import{H as kr,O as _r,k as K}from"./chunk-OQNJIIR2.js";import{f as Sr,g as $r,h as Er,l as Ar}from"./chunk-PSYHAO57.js";import{b as vr}from"./chunk-2VDO2HEK.js";import{t as wr,u as xr}from"./chunk-JEBU5JUM.js";import{d as br,e as yr}from"./chunk-AQASR6KR.js";import{h as pe,j as sr,l as ir,m as ar,n as lr}from"./chunk-RX5O5637.js";import{a as cr,c as dr,e as ur,f as dt,h as pr,j as gr,k as fr,l as ut,m as pt,n as gt}from"./chunk-5ELIX7BQ.js";import{c as mr,d as hr}from"./chunk-CSC45PA7.js";import{a as Qn,c as Zn}from"./chunk-KP7KDLZ2.js";import{Aa as ue,Ca as ct,b as it,f as Vn,s as at,u as lt,xa as Te,ya as Gn,za as U}from"./chunk-FR4DTMCA.js";import{a as _e,b as de,e as qn}from"./chunk-7AB3QUGH.js";import{h as er,i as tr,j as nr,l as rr,m as or}from"./chunk-H4DWZIU7.js";import{s as Kn}from"./chunk-CAH6TNC6.js";import{a as zn,b as Re,e as Xn}from"./chunk-N476XZD3.js";import{c as Ie,d as Jn,e as Yn}from"./chunk-XVV7ZZ77.js";import{b as ee}from"./chunk-5ONH4ITT.js";import{a as Hn,c as st}from"./chunk-ILEC3IAV.js";import{a as Ln,i as Un,l as jn,n as rt,o as ot,r as ce,s as Z,u as Bn}from"./chunk-OQQTV3OF.js";import{a as Pn,b as Mn,d as Fn,e as Wn}from"./chunk-4NZ4T3TQ.js";import{a as Nn}from"./chunk-7IW25T4K.js";import{a as On}from"./chunk-QUFIUXMQ.js";import{E as Ee,F as $n,Fa as Rn,G as En,H as bi,Ha as Tn,Ia as xi,Ib as nt,Sb as In,Tb as Dn,bc as Cn,ca as Ae,ea as An,f as Qe,g as C,i as $e,j as $,k as le,l as vn,o as Sn,p as Ze,ya as _n}from"./chunk-KAM4ZWRE.js";import{a as et,h as yi}from"./chunk-KEUW6YLL.js";import{j as tt,r as wi}from"./chunk-N47Y5ADQ.js";import{existsSync as ki,readdirSync as vi,readFileSync as Si,statSync as $i}from"fs";import{resolve as Ei}from"path";function Rr(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],d=a.filter(f=>n-f.at<=o),l=a.filter(f=>n-f.at>o&&n-f.at<=o*2),c=d.filter(f=>f.status==="failed").length,p=a.filter(f=>f.status==="paused").length,u=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?l.length>0&&d.length===0?"dormant":d.length>0&&c*2>=d.length?"failing":d.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:u,recent:d.length,prior:l.length,failed:c,paused:p}}).sort((i,a)=>{let d={dormant:0,failing:1,active:2,quiet:3,never:4};return d[i.state]-d[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var De=new Map;function Su(t,e=1e3){if(!ki(t))return[];let n=vi(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ei(t,s);return{path:i,mtime:$i(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of De.keys())r.has(s)||De.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=De.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let d=Ai(s,i);De.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Ai(t,e){try{let n=Si(t,"utf-8").split(`
|
|
2
|
+
`).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Tr=7,_i={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},R={routines:200,summary:160,filters:6,filterValue:60,text:120},Ri=(t,e,n)=>{try{return Kn(t,e,n)}catch{return null}},Ir=864e5;function _u(t){let e=t.now??Date.now(),n={..._i,...t.thresholds},r=t.nextFire??Ri,o=[];for(let a of t.crons){let d=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",c=d.map(g=>({at:Date.parse(g.startedAt),status:g.status})),p=d[0],u={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:F(a.id,R.text),trigger:{schedule:F(a.schedule,R.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?mt(a.nextRun)??mt(r(a.schedule,new Date(e),l)):null,lastRun:p?{at:p.startedAt,status:p.status,summary:Ni(p.status==="success"?void 0:p.errorSummary,R.summary)}:null,lastSuccessAt:d.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Dr(c),sampledRuns:d.length,flags:[],attention:null,recent:d.slice(0,Tr).map(g=>({at:g.startedAt,status:g.status}))};u.flags=Cr(u,c,a.schedule,l,null,e,n,r),o.push(Or(u))}let s=new Map(Rr(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let d=i.get(a.workflowId);d?d.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let d=a.nodes.find(k=>k.type.startsWith("trigger."));if(!d||d.type!=="trigger.cron"&&d.type!=="trigger.hook")continue;let l=d.config??{},c=a.state||"active",p=c==="active",u=(i.get(a.id)??[]).slice().sort((k,D)=>D.at-k.at),g=u.map(k=>({at:k.at,status:Di(k.status)})),f=g[0],m=d.type==="trigger.cron",w=typeof l.spec=="string"?l.spec:"",x=typeof l.timezone=="string"?l.timezone:"UTC",b={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:F(a.title||a.id,R.text),trigger:m?{schedule:F(w,R.text),timezone:x}:{event:F(typeof l.event=="string"?l.event:"",R.text),filters:Oi(l.filter,a)},agent:Ci(a),enabled:p,state:c,nextRunAt:m&&p&&w?mt(r(w,new Date(e),x)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let k=g.find(D=>D.status==="success");return k?new Date(k.at).toISOString():null})(),consecutiveFailures:Dr(g),sampledRuns:u.length,flags:[],attention:null,recent:g.slice(0,Tr).map(k=>({at:new Date(k.at).toISOString(),status:k.status}))},y=Date.parse(a.updated||a.created||"");b.flags=m?Cr(b,g,w,x,Number.isFinite(y)?y:null,e,n,r):Ti(b,s.get(a.id)?.state==="dormant",Number.isFinite(y)?y:null,e,n),o.push(Or(b))}return o.sort(Ii).slice(0,R.routines)}function Dr(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function Cr(t,e,n,r,o,s,i,a){let d=[],l=e.length?e[0].at:null;if(!t.enabled){let u=Lr(l,o,s,i);return u&&d.push(u),d}if(t.consecutiveFailures>=i.failStreak&&d.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return d.push({reason:"never-ran",detail:"No persisted attempt"}),d;let c=new Date(l),p=null;for(let u=0;u<i.missedFires&&(p=a(n,c,r),!!p);u++)c=p;return p&&s>p.getTime()+i.graceMs&&d.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),d}function Ti(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Lr(i,n,r,o);return a&&s.push(a),s}return t.consecutiveFailures>=o.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function Lr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Ir?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Ir)} days`:"Disabled and never ran"}}function Or(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var Nr={critical:0,warning:1,info:2};function Ii(t,e){let n=t.attention?Nr[t.attention]:3,r=e.attention?Nr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Di(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function Ci(t){if(t.ownerAgent)return F(t.ownerAgent,R.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?F(String(e.config.agentId),R.text):null}function Oi(t,e){let n=[],r=e?.project;if(r&&n.push(F(`project=${r}`,R.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Object.entries(t)){let i=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];i.length&&n.push(F(`${o}=${i.join(",")}`,R.filterValue))}return n.slice(0,R.filters)}function mt(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function F(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Ni(t,e){return t===void 0?void 0:F(t,e)}import{mkdirSync as Li,readFileSync as Pi,renameSync as Mi,writeFileSync as Fi}from"fs";import{resolve as Wi}from"path";function Pr(t){return Wi(ot(t),"_state.json")}function O(t){try{let e=JSON.parse(Pi(Pr(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function ge(t,e){Li(ot(t),{recursive:!0});let n=Pr(t),r=`${n}.${process.pid}.tmp`;Fi(r,JSON.stringify(e,null,2)+`
|
|
3
|
+
`),Mi(r,n)}function Mr(t,e,n,r=Date.now()){let o=O(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),ge(t,{...o,snoozed:s})}function Cu(t,e){ge(t,{...O(t),lastDigest:e})}function ht(t,e,n,r=Date.now()){let o=O(t),s=new Set(n),i={};for(let[d,l]of Object.entries(o.popped??{}))s.has(d)&&(i[d]=l);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(d=>d!==e&&s.has(d));ge(t,{...o,popped:i,wanted:a})}function Fr(t,e){let n=O(t);ge(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function Ou(t,e=Date.now()){ge(t,{...O(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as Ui,readFileSync as ji}from"fs";Cn();yi();function Wr(t){let e=zn(t),n={};if(Ui(e))try{n=In(JSON.parse(ji(e,"utf-8")))}catch{n={}}let r=nt.safeParse(n?.requests);return r.success?r.data:nt.parse(void 0)}async function Wu(t,e={}){let n=(t.channels??[]).filter(r=>!et.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...et].join(", ")}`}:Re(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[s]!==void 0&&(o[s]=t[s]);if(t.plans){let s=o.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(s[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((o.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let s=o.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(s[i]=t.catchPromises[i])}if(t.autoResend){let s=o.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(s[i]=t.autoResend[i])}if(t.flow){let s=o.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(s[i]=t.flow[i])}if(t.checkers){let s=o.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(s[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as V,readdirSync as sa,readFileSync as wt,statSync as ia}from"fs";import{dirname as ro,resolve as _}from"path";import{randomBytes as Br}from"crypto";import{existsSync as Hi,mkdirSync as Vi,readdirSync as qi,readFileSync as zi,renameSync as Hr,unlinkSync as Xi,writeFileSync as Ki}from"fs";import{resolve as Vr}from"path";function Ur(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Bi=t=>t.trim().split(`
|
|
4
|
+
`).pop()?.slice(0,300)||"no output";async function jr(t,e,n,r=ft){let o=await r(t.bin,[...Ur(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Bi(o.stderr||o.stdout)}`}}async function Bu(t,e,n,r,o=ft){return(await o(t.bin,[...Ur(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Gi=2e3,Ji=t=>jr(t.wacli,t.to,t.text);function bt(t){return Vr(t,".agentx","whatsapp-triage","drafts")}var Yi=t=>/^[a-z0-9-]{8,64}$/.test(t),Ce=(t,e)=>Vr(bt(t),`${e}.json`);function qr(t,e){Vi(bt(t),{recursive:!0});let n=Ce(t,e.id),r=`${n}.${process.pid}.tmp`;Ki(r,JSON.stringify(e,null,2)+`
|
|
5
|
+
`,{mode:384}),Hr(r,n)}function Ku(t,e,n=Date.now()){let r=e.text.trim().slice(0,Gi);if(!r)throw new Error("empty draft");let o={...e,text:r,id:`${n.toString(36)}-${Br(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return qr(t,o),o}function Oe(t,e){if(!Yi(e))return null;try{return JSON.parse(zi(Ce(t,e),"utf-8"))}catch{return null}}function zr(t,e){let n=bt(t);return Hi(n)?qi(n).filter(r=>r.endsWith(".json")).map(r=>Oe(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,o)=>r.created_at.localeCompare(o.created_at)):[]}async function Xr(t,e,n,r={}){let o=Oe(t,e);if(!o||o.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${Ce(t,e)}.${process.pid}.${Br(3).toString("hex")}.claim`;try{Hr(Ce(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let i={...o,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString()};if(n==="no")i.status="rejected";else{let a=await(r.send??Ji)(o).catch(d=>({ok:!1,error:String(d?.message??d)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}qr(t,i);try{Xi(s)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as Qi,writeFileSync as Zi}from"fs";import{resolve as Gr}from"path";var Jr="ready",ea="202510";function ta(t){let e=t.date??t.created_at.slice(0,10);return Gr(t.workspace,Jr,`${e}-${t.platform}-${t.id}.txt`)}function Kr(t){let e=ta(t);return Qi(Gr(t.workspace,Jr),{recursive:!0}),Zi(e,t.text.endsWith(`
|
|
6
6
|
`)?t.text:`${t.text}
|
|
7
|
-
`),e}function to(t,e,n){let r=Wn(t.config,e,n);if(!r)return null;let o=t.env??process.env,s=r.integration.credentials?.tokenEnv,i=s?o[s]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function no(t,e,n){return to(t,e,n)!==null}async function ia(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let o=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??oa),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!o.ok)throw new Error(`LinkedIn said ${o.status}: ${(await o.text().catch(()=>"")).slice(0,200)}`);let s=o.headers.get("x-restli-id");return s?{url:`https://www.linkedin.com/feed/update/${s}/`}:{}}async function aa(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let o=await r.json().catch(()=>({}));return o.data?.id?{url:`https://x.com/i/web/status/${o.data.id}`}:{}}async function la(t,e){let n=to(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Qr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await ia(t.text,n,r):await aa(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Qr(t);return{ok:!1,error:`not posted on ${pe[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function ro(t){return e=>la(e,t)}In();Ln();Ln();In();var dp=["done","skipped"],ca=1e3;function da(t){t.exec(`
|
|
8
|
-
|
|
9
|
-
request_id TEXT PRIMARY KEY,
|
|
10
|
-
created_by TEXT NOT NULL,
|
|
11
|
-
created_at INTEGER NOT NULL,
|
|
12
|
-
state TEXT NOT NULL,
|
|
13
|
-
finished_at INTEGER,
|
|
14
|
-
notified_at INTEGER,
|
|
15
|
-
FOREIGN KEY (request_id) REFERENCES requests(id) ON DELETE CASCADE
|
|
16
|
-
);
|
|
17
|
-
CREATE INDEX IF NOT EXISTS idx_request_plans_state ON request_plans(state);
|
|
18
|
-
CREATE TABLE IF NOT EXISTS request_plan_steps (
|
|
19
|
-
request_id TEXT NOT NULL,
|
|
20
|
-
idx INTEGER NOT NULL,
|
|
21
|
-
name TEXT NOT NULL,
|
|
22
|
-
kind TEXT NOT NULL,
|
|
23
|
-
agent_id TEXT NOT NULL,
|
|
24
|
-
done_when TEXT NOT NULL,
|
|
25
|
-
state TEXT NOT NULL,
|
|
26
|
-
needs_approval INTEGER NOT NULL DEFAULT 0,
|
|
27
|
-
approval TEXT NOT NULL DEFAULT 'none',
|
|
28
|
-
card_id TEXT,
|
|
29
|
-
message TEXT,
|
|
30
|
-
to_channel TEXT,
|
|
31
|
-
to_chat TEXT,
|
|
32
|
-
to_account TEXT,
|
|
33
|
-
check_url TEXT,
|
|
34
|
-
check_contains TEXT,
|
|
35
|
-
stall_minutes REAL,
|
|
36
|
-
evidence TEXT,
|
|
37
|
-
note TEXT,
|
|
38
|
-
dispatched_at INTEGER,
|
|
39
|
-
updated_at INTEGER NOT NULL,
|
|
40
|
-
nudges INTEGER NOT NULL DEFAULT 0,
|
|
41
|
-
last_nudge_at INTEGER,
|
|
42
|
-
notified_at INTEGER,
|
|
43
|
-
PRIMARY KEY (request_id, idx),
|
|
44
|
-
FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE
|
|
45
|
-
);
|
|
46
|
-
CREATE TABLE IF NOT EXISTS request_plan_events (
|
|
47
|
-
request_id TEXT NOT NULL,
|
|
48
|
-
step INTEGER,
|
|
49
|
-
at INTEGER NOT NULL,
|
|
50
|
-
kind TEXT NOT NULL,
|
|
51
|
-
detail TEXT NOT NULL,
|
|
52
|
-
FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE
|
|
53
|
-
);
|
|
54
|
-
CREATE INDEX IF NOT EXISTS idx_request_plan_events ON request_plan_events(request_id, at);
|
|
55
|
-
CREATE TABLE IF NOT EXISTS request_plan_continues (
|
|
56
|
-
goal_key TEXT NOT NULL,
|
|
57
|
-
day TEXT NOT NULL,
|
|
58
|
-
turns INTEGER NOT NULL DEFAULT 0,
|
|
59
|
-
cost_usd REAL NOT NULL DEFAULT 0,
|
|
60
|
-
told_at INTEGER,
|
|
61
|
-
PRIMARY KEY (goal_key, day)
|
|
62
|
-
);
|
|
63
|
-
`),Rn(t,"request_plan_steps",[["check_count","TEXT"],["last_count","INTEGER"],["last_count_at","INTEGER"]])}function so(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function wt(t){return{requestId:t.request_id,createdBy:t.created_by,createdAt:t.created_at,state:t.state,finishedAt:t.finished_at??null,notifiedAt:t.notified_at??null}}function oo(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,checkCount:t.check_count??null,lastCount:t.last_count??null,lastCountAt:t.last_count_at??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var ua={state:"state",approval:"approval",cardId:"card_id",message:"message",evidence:"evidence",note:"note",dispatchedAt:"dispatched_at",updatedAt:"updated_at",nudges:"nudges",lastNudgeAt:"last_nudge_at",notifiedAt:"notified_at",lastCount:"last_count",lastCountAt:"last_count_at"},Oe=class{constructor(e){this.db=e;da(e)}create(e,n,r,o){let s=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),i=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
|
|
64
|
-
to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at, check_count)
|
|
65
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,o),r.forEach((a,d)=>{let l=d===0,c=l&&a.agentId===n&&a.kind!=="message";i.run(e,d+1,a.name,a.kind,a.agentId,a.doneWhen,l?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,c?o:null,o,a.checkCount??null)}),this.event(e,null,"created",`${r.length} steps, written by ${n}`,o)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?wt(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(oo)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?oo(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(wt)}updateStep(e,n,r){let o=[],s=[];for(let[i,a]of Object.entries(r)){let d=ua[i];!d||a===void 0||(o.push(`${d} = ?`),s.push(typeof a=="boolean"?a?1:0:a))}o.length&&this.db.prepare(`UPDATE request_plan_steps SET ${o.join(", ")} WHERE request_id = ? AND idx = ?`).run(...s,e,n)}finish(e,n,r){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(n,r,e).changes>0}markNotified(e,n){this.db.prepare("UPDATE request_plans SET notified_at = ? WHERE request_id = ?").run(n,e)}awaitingSummary(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'done' AND notified_at IS NULL ORDER BY finished_at").all().map(wt)}event(e,n,r,o,s){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,s,r,o.replace(/\s+/g," ").trim().slice(0,ca))}continues(e,n){let r=this.db.prepare("SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?").get(e,n);return r?{turns:r.turns,costUsd:r.cost_usd,toldAt:r.told_at??null}:{turns:0,costUsd:0,toldAt:null}}addContinue(e,n,r){this.db.prepare(`INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)
|
|
66
|
-
ON CONFLICT(goal_key, day) DO UPDATE SET turns = turns + excluded.turns, cost_usd = cost_usd + excluded.cost_usd,
|
|
67
|
-
told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,o=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,o).reverse().map(s=>({requestId:s.request_id,step:s.step??null,at:s.at,kind:s.kind,detail:s.detail}))}},up=Cn;var uo=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],ma=280;function O(t,e=ma){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function te(t){if(t.configPath)return T(t.configPath);let e=[T(t.root,"agentx.json"),T(t.root,".agentx","config.json")];return e.find(n=>q(n))??e[0]}function V(t){return t.wikiDir?T(t.wikiDir):T(t.root,".agentx","wiki")}function fa(t){return Z(t.root,"pending").map(ha)}function ha(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:O([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function ba(t){let e=te(t);if(!q(e))return[];let n;try{n=JSON.parse(kt(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),o=[];for(let[s,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let d=i.timezone||"UTC",l=i.schedule?ir(i.schedule):"",c=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",p=String(i.prompt??i.command??""),u=a.action==="create";o.push({key:`schedule:${s}`,kind:"schedule",title:u?`New schedule "${s}" for ${i.agent??"an agent"}`:`Delete schedule "${s}"`,ask:u?`Let ${i.agent??"the agent"} run this ${c}?`:`Remove the schedule "${s}" (${c})?`,yes:u?"enable it":"remove it",no:u?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:O(`${p}${u&&i.schedule?` \xB7 first run ${lr(ar(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function po(t){let e=T(t,".agentx","memory");return q(e)?pa(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ya(t){let e=po(t.root);if(e.length===0)return[];let n=new at(t.root),r=[];for(let o of e)for(let s of n.held(o))r.push({key:`memory:${o}/${s.id}`,kind:"memory",title:`Fact ${o} learned from ${s.source.channel}`,ask:`Let ${o} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:o,created_at:s.createdAt,detail:O(s.content),more:`agentx memory facts held --agent ${o}`});return r}function wa(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function xa(t){return vr(V(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:O(`${wa(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var io=new Map;function go(t,e){let n=ga(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=io.get(t);if(o?.version===r)return o.value;let s=e();return io.set(t,{version:r,value:s}),s}function ka(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${O(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:O(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function va(t,e){let n=V(t);if(!q(T(n,"_facts.json")))return;let r=Ie(new ee(n),"pending").find(o=>o.id===e);return r?ka(r):void 0}function Sa(t){let e=T(V(t),"_facts.json");if(!q(e))return;let n=go(e,()=>Ie(new ee(co(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function Ea(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function mo(t){let e=V(t),n=new it(e);if(!q(n.path))return[];let r=go(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new ee(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:Ea(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function _a(t){return Yr(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:O(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function $a(t){return Ar(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:O(`Last try not sent: ${e.error}`)}:{}}))}function Ta(t){let e=Object.entries(lt(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Le(t).agents??{};return e.map(([r,o])=>{let s=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${s.name||r}", created by ${o.by}`,ask:`Let ${s.name||r} (${s.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:o.by,created_at:o.at,detail:O(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Le(t){try{return JSON.parse(kt(te(t),"utf-8"))}catch{return{}}}function xt(t){let e={};try{e=Object.fromEntries(Un(kt(T(co(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function Aa(t){let e=gr(t.root,"pending");if(e.length===0)return[];let n=Le(t),r=xt(t);return e.map(o=>{let s=pe[o.platform]??o.platform;return{key:`content:${o.id}`,kind:"content",title:`${s} post${o.topic?`: ${o.topic}`:""}${o.date?` (for ${o.date})`:""}`,ask:`Publish this on ${s}? "${o.text}"`,yes:no({config:n,env:r},o.agent,o.platform)?`post it on ${s}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:o.agent,created_at:o.created_at,detail:O(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:ur(o.text)}})}function G(t){if(t.requests)return t.requests;if(T(t.root)!==process.cwd()||!q(T(t.root,".agentx","db.sqlite")))return null;let e=nt({quiet:!0});if(!e)return null;let n=ao.get(e);return!n&&!Nn(e)?null:(n||ao.set(e,n=new On(e)),n)}var ao=new WeakMap;function Up(t){if(t.plans)return t.plans;if(t.requests||T(t.root)!==process.cwd()||!q(T(t.root,".agentx","db.sqlite")))return null;let e=nt({quiet:!0});if(!e||!so(e))return null;let n=lo.get(e);return n||lo.set(e,n=new Oe(e)),n}var lo=new WeakMap;function Ra(t){let e=G(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:K(n,120).headline,ask:`Not finished. Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:O(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var fo={card:fa,schedule:ba,agent:Ta,memory:ya,wiki:xa,fact:()=>[],question:mo,whatsapp:_a,email:$a,content:Aa,request:Ra};function Ia(t,e){let n=t.expires?Date.parse(t.expires):1/0,r=e.expires?Date.parse(e.expires):1/0;return n!==r?n-r:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function ho(t,e={}){let n=t.now??Date.now(),{snoozed:r}=N(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??uo){if(d==="fact"){try{let c=Sa(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=fo[d](t)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let p=r[c.key];if(p&&Date.parse(p)>n){if(!e.includeSnoozed){a++;continue}c.snoozed_until=p}o.push(c)}}return o.sort(Ia),{items:o,snoozed:a,errors:s,backlog:i}}function bo(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!uo.includes(n)||!r?null:{kind:n,ref:r}}function Da(t,e,n){switch(e){case"card":return ce(t.root,n)?.status==="pending";case"wiki":return kr(V(t),n)?.status==="pending";case"whatsapp":return Ne(t.root,n)?.status==="pending";case"email":return Tr(t.root,n)?.status==="pending";case"content":return pr(t.root,n)?.status==="pending";default:return!!yo(t,e,n)}}function yo(t,e,n){return e==="fact"?va(t,n):fo[e](t).find(r=>r.key===`${e}:${n}`)}async function wo(t,e,n,r={}){let o=n==="later"?null:bo(e),s;if(o)try{s=yo(t,o.kind,o.ref)}catch{s=void 0}let i=await Ca(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;jn(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:i.verdict??n,...a?{choice:a}:{},...r.text&&i.verdict!=="no"?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function Ca(t,e,n,r){let o=bo(e);if(!o)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:i}=o,a=t.now??Date.now(),d=r.by??"operator";if(n==="later"){if(!Da(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,p=new Date(a+c*36e5);return jr(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=Kn(t.root,i,l?"yes":"no",{by:d,note:r.note,now:a,choice:r.choice,text:r.text,popup:r.popup});if(!c.ok)return c;let p=c.card.verdict??(l?"yes":"no"),u=l&&p==="no"?", an option that means no":"";return{ok:!0,verdict:p,message:`${e}: ${c.card.raised_by} will be told ${p}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""}${u})`:""}`}}case"schedule":{let c=await(l?cr:dr)(i,{configPath:te(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(lt(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return ct(t.root,i,"approval"),{ok:!0,message:`${e}: approved. It runs once the daemon has loaded it; if it was added while the daemon was running, run: agentx daemon restart`};let c=[],p=await Ae(u=>{Zn(u,`agents.${i}`);for(let[g,m]of Object.entries(u.crons??{}))m?.agent===i&&(delete u.crons[g],c.push(g))},{configPath:te(t),reload:t.reload});return p.success?(ct(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${c.length?`, with its schedules ${c.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:p.error||"could not remove it from agentx.json"}}case"memory":{let c=i.indexOf("/");if(c<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let p=i.slice(0,c),u=i.slice(c+1);if(!po(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new at(t.root);return g.held(p).some(m=>m.id===u)?(g.review(p,u,l?"approved":"rejected",d),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${u}" isn't waiting for review`}}case"wiki":{let c=V(t),p=l?Sr(c,i,{by:d,force:r.force,now:a}):Er(c,i,{by:d,reason:r.note,now:a});return p.ok?{ok:!0,message:l?`${p.proposal.article.path} written to the shared wiki`:`${e} rejected`}:p}case"fact":return Na(t,e,i,l,d,r);case"question":return La(t,e,i,l,d,r);case"whatsapp":{let c=await Jr(t.root,i,l?"yes":"no",{by:d,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:l?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??Ir(Le(t),xt(t)),p=await Rr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,send:c});return p.ok?{ok:!0,message:l?`${e}: sent to ${p.draft.to}${p.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:p}case"content":{let c=t.publishContent??ro({config:Le(t),env:xt(t)}),p=await mr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,seen:r.seen,publish:c});if(!p.ok)return p;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let u=pe[p.draft.platform];return{ok:!0,message:p.draft.status==="posted"?`${e}: posted on ${u}${p.draft.url?` (${p.draft.url})`:""}`:`${e}: no ${u} connector is set, so it is saved ready to paste: ${p.draft.file}`}}case"request":{let c=G(t),p=c?.get(i);return!c||!p||p.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?Hr(te(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${d}`,a,null,d==="operator"?Dn:d),{ok:!0,message:`${e}: dropped`})}}}function Na(t,e,n,r,o,s){let i=new ee(V(t));try{let a=Ie(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return rr(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=nr(i,a.id,o);return{ok:!0,message:`${e}: ${d.write.fact.subject} \xB7 ${d.write.fact.attribute} recorded as "${d.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function Oa(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function La(t,e,n,r,o,s){let i=V(t),a=new it(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Gn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=mo(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${d.id} "<value>"`};let c=Oa(l.choices,s.choice);if(!c)return{ok:!1,error:`pick one of: ${l.choices.map((g,m)=>`${m+1}. ${g}`).join(", ")}`};let p=new ee(i),u=d.factId?p.get(d.factId):void 0;return u&&p.write({subject:u.subject,attribute:u.attribute,value:c,source:"owner said",verifiedBy:o,volatility:u.volatility},{confirmedBy:o}),a.resolve(d.id,"answered",c),{ok:!0,message:`${e}: answered "${c}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var Pa=3,Ma=7,Fa=50,St=120,Ua=280,vt=600,ko=36e5,Wa=24*ko;function Bp(t){let e=new Set;for(let n of t)for(let r of n.runningTasks??[])r.traceId&&e.add(r.traceId);return e}function ne(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var Pe=t=>new Date(t).toISOString();function ja(t,e,n){let r=e.key.slice(0,Math.max(0,e.key.indexOf(":")))||"card";return{key:e.key,kind:r,column:"yours",node:t.node,nodeName:t.nodeName,title:ne(e.title,St),...e.ask?{ask:ne(e.ask,vt)}:{},...e.detail?{facts:ne(e.detail,Ua)}:{},...e.recommend?{recommend:e.recommend}:{},...e.raisedBy?{agent:e.raisedBy}:{},...e.yes?{yes:e.yes}:{},...e.no?{no:e.no}:{},...e.choices?.length?{choices:e.choices}:{},...e.draft?{draft:e.draft}:{},...e.expires?{expires:e.expires}:{},...e.ifSilent?{ifSilent:e.ifSilent}:{},...e.createdAt?{askedAt:e.createdAt}:{},can:{answer:!0,later:!0,reply:n&&r==="request"}}}var Ba={done:"Done",declined:"Declined",dropped:"Dropped"};function vo(t,e,n){let{record:r,links:o}=e,s=K(r,St),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:ne(s.said,vt)}:{},agent:r.agentId,askedAt:Pe(r.createdAt),changedAt:Pe(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return o.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:ne(r.question,vt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),d=t.now-r.updatedAt<(t.quietHours??Pa)*ko;return{...i,column:a||d?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:Pe(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:Ba[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function Ha(t){return t.status==="decided"?t.verdict==="yes"?`Answered yes${t.choice?`: ${t.choice}`:""}`:"Answered no":t.status==="expired"?`No answer in time: ${t.outcome==="discard"?"discarded":t.outcome==="pause"?"paused":"kept"}`:"Closed by the agent"}function qa(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:ne(e.title,St),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:Ha(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,xo=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(r))[0];function Et(t){let e=[],n=[];for(let o of t.inbox){o.error&&n.push(`What waits on ${o.nodeName} could not be read: ${o.error}`);for(let s of o.items)e.push(ja(o,s,o.node===t.node))}let r=So(t,e);for(let o of t.requests??[]){let s=vo(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function So(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Hp(t){let e=Et(t.owner?{...t,requests:null}:t),n=t.owner?[...t.owner.items,...e.cards]:e.cards,r=t.owner?[...t.owner.errors,...e.errors]:e.errors,o=So(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=vo(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??Ma)*Wa;for(let u of t.cards)u.status!=="pending"&&L(u.decided_at)>=d&&a.push(qa(t,u));s.sort((u,g)=>L(g.changedAt)-L(u.changedAt)),i.sort((u,g)=>L(u.changedAt)-L(g.changedAt)),a.sort((u,g)=>L(g.changedAt)-L(u.changedAt));let l=a.filter(u=>L(u.changedAt)>=d).slice(0,Fa),c=xo(n,"askedAt"),p=xo(i,"changedAt");return{ts:Pe(t.now),cards:[...n,...s,...i,...l],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:s.length},quiet:{count:i.length,...p?{oldest:p}:{}},done:{count:l.length}},errors:r}}function Va(t){return{key:t.key,title:t.title,ask:t.ask,recommend:t.recommend,yes:t.yes,no:t.no,raisedBy:t.raised_by,expires:t.expires,...t.if_silent?{ifSilent:t.if_silent}:{},...t.choices?{choices:t.choices}:{},...t.draft?{draft:t.draft}:{},...t.detail?{detail:t.detail}:{},...t.created_at?{createdAt:t.created_at}:{}}}function Xa(t,e,n){let r=t.map(o=>o.askedAt).filter(o=>!!o&&!!Date.parse(o)).sort((o,s)=>Date.parse(o)-Date.parse(s));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function zp(t,e){let n=t.now??Date.now(),r=[],o=ho(t,{includeSnoozed:!0});for(let c of o.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let s=o.items.filter(c=>!c.snoozed_until),i=new Set(o.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=G(t);c&&(a=c.listByState("waiting_owner").map(p=>({record:p,links:c.links(p.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:d,errors:l}=Et({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Va)}],requests:a,deferred:i});return Xa(d,i.size,[...r,...l])}import{readFileSync as za}from"fs";var Ka=1e4,Eo=/^[0-9a-f]{7,64}$/i;function Yp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&Eo.test(i)?{source:n,commit:i}:{source:n,commit:null,error:"this build does not carry its commit (run from source?)"}}let r;try{r=await e(n,{signal:AbortSignal.timeout(Ka)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let o=await r.json().catch(()=>null),s=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,o);return typeof s=="string"&&Eo.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Jp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=za(n.tokenFile,"utf-8").trim().split(`
|
|
68
|
-
`)[0].trim()||void 0}catch{}let o=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??o?.host??"https://gitlab.com",token:e?.gitlab?.token??o?.token}}}var Me=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function Zp(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/assistant"||t.startsWith("/api/assistant/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/api/org"||t.startsWith("/api/org/")||t==="/content"||t.startsWith("/content/")||t==="/integrations"||t.startsWith("/integrations/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||t==="/events/hub"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"||t==="/lookup"}function eg(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/events"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)||/^\/channels\/[^/]+\/switch$/.test(t)||/^\/workflow-runs\/[^/]+\/cancel$/.test(t)||t==="/api/signals/stop"||t==="/api/signals/resume"||t==="/api/signals/drop"||t==="/api/signals/stop-all"||t==="/api/signals/stop-all/report"||t==="/api/review-gate/replay"}function tg(t){return Me.has(t)}function ng(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Me.has(t.remoteAddress))return{allowed:!0,reason:"loopback"};if(t.acceptedTokens.size===0)return{allowed:!0,reason:"no-tokens-configured"};let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.acceptedTokens.has(n)?{allowed:!0,reason:"token"}:{allowed:!1,reason:"missing-or-invalid-token"}}function rg(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.chatSecret&&n===t.chatSecret?!0:t.foreignBrowser?!1:n&&t.acceptedTokens.has(n)?!0:!t.chatSecret&&Me.has(t.remoteAddress)}function og(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return t.chatSecret?n===t.chatSecret:Me.has(t.remoteAddress)||!!n&&t.acceptedTokens.has(n)}function sg(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let r of t.mesh?.peers||[])r.token&&n.add(r.token);return n}function ig(t,e,n=process.env){let r=s=>s.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(s=>r(s.url)===e)?.token)||n.MESH_TOKEN||void 0}function Fe(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Ga(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ya(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function lg(t,e=Ya()){let n=Fe(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=Ga(n),s=[Fe(t.host),Fe(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=Fe(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function cg(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var _t="/api/admin/pictures",Ja=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Qa=/^\/api\/admin\/pictures\/(agent|person)\/([^/]+)$/;function _(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}function Za(t){let e={agent:{},person:{}};for(let n of fr)for(let[r,o]of Object.entries(yr(t,n)))e[n][r]=wr(n,r,o);return e}function pg(t,e,n,r,o){let s=n.match(Ja);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return _(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=xr(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":hr,"Content-Length":String(a.length),"Cache-Control":"private, max-age=31536000, immutable","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'"}),e.end(a),!0):(_(e,404,{error:"no such picture"}),!0)}async function gg(t,e,n,r){if(n!==_t&&!n.startsWith(`${_t}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===_t)return o!=="GET"?(_(e,405,{error:"GET only"}),!0):(_(e,200,{...Za(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(Qa);if(!s)return _(e,404,{error:"not found"}),!0;if(o!=="PUT"&&o!=="DELETE")return _(e,405,{error:"PUT or DELETE only"}),!0;let i=t.headers["x-requested-with"];if(i!=="agentx-board"&&i!=="agentx-admin")return _(e,400,{error:"missing X-Requested-With: agentx-board"}),!0;let a=s[1],d=decodeURIComponent(s[2]),l=a==="agent"?r.agentIds():r.personIds();if(!br.test(d)||!l.includes(d))return _(e,404,{error:a==="agent"?`no agent "${d}" in agentx.json`:`no person "${d}" in agentx.json`}),!0;if(o==="DELETE"){let c=gt(r.root,a,d);return _(e,200,{ok:!0,removed:c}),!0}try{let c=await mt(t),p=await pt(r.root,a,d,c);_(e,200,{ok:!0,url:p.url})}catch(c){if(c instanceof ut)return _(e,c.status,{error:c.message}),!0;throw c}return!0}async function mg(t,e,n,r){let o=(t.method||"GET").toUpperCase();if(o!=="PUT"&&o!=="DELETE"){_(e,405,{error:"PUT or DELETE only"});return}let s=n.searchParams.get("agent")?.trim()||void 0,i=r.provenAgent(s);if(!i){_(e,403,{error:"Only an agent sets its own picture, from its own run: send X-AgentX-Task (or X-AgentX-Channel and X-AgentX-Chat) of a running turn. The owner sets pictures in Settings."});return}if(s&&s!==i){_(e,403,{error:`An agent can only change its own picture: this run is "${i}", not "${s}".`});return}if(o==="DELETE"){_(e,200,{ok:!0,agent:i,removed:gt(r.root,"agent",i)});return}try{let a=await pt(r.root,"agent",i,await mt(t));_(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof ut){_(e,a.status,{error:a.message});return}throw a}}var _o={};function bg(t){_o=t}function yg(){return _o}var wg=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
|
7
|
+
`),e}function Yr(t,e,n){let r=Nn(t.config,e,n);if(!r)return null;let o=t.env??process.env,s=r.integration.credentials?.tokenEnv,i=s?o[s]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function Qr(t,e,n){return Yr(t,e,n)!==null}async function na(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let o=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??ea),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!o.ok)throw new Error(`LinkedIn said ${o.status}: ${(await o.text().catch(()=>"")).slice(0,200)}`);let s=o.headers.get("x-restli-id");return s?{url:`https://www.linkedin.com/feed/update/${s}/`}:{}}async function ra(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let o=await r.json().catch(()=>({}));return o.data?.id?{url:`https://x.com/i/web/status/${o.data.id}`}:{}}async function oa(t,e){let n=Yr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Kr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await na(t.text,n,r):await ra(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Kr(t);return{ok:!1,error:`not posted on ${pe[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function Zr(t){return e=>oa(e,t)}wi();xi();var oo=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],aa=280;function N(t,e=aa){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function te(t){if(t.configPath)return _(t.configPath);let e=[_(t.root,"agentx.json"),_(t.root,".agentx","config.json")];return e.find(n=>V(n))??e[0]}function q(t){return t.wikiDir?_(t.wikiDir):_(t.root,".agentx","wiki")}function la(t){return Z(t.root,"pending").map(ca)}function ca(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:N([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function da(t){let e=te(t);if(!V(e))return[];let n;try{n=JSON.parse(wt(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),o=[];for(let[s,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let d=i.timezone||"UTC",l=i.schedule?er(i.schedule):"",c=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",p=String(i.prompt??i.command??""),u=a.action==="create";o.push({key:`schedule:${s}`,kind:"schedule",title:u?`New schedule "${s}" for ${i.agent??"an agent"}`:`Delete schedule "${s}"`,ask:u?`Let ${i.agent??"the agent"} run this ${c}?`:`Remove the schedule "${s}" (${c})?`,yes:u?"enable it":"remove it",no:u?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:N(`${p}${u&&i.schedule?` \xB7 first run ${nr(tr(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function so(t){let e=_(t,".agentx","memory");return V(e)?sa(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ua(t){let e=so(t.root);if(e.length===0)return[];let n=new it(t.root),r=[];for(let o of e)for(let s of n.held(o))r.push({key:`memory:${o}/${s.id}`,kind:"memory",title:`Fact ${o} learned from ${s.source.channel}`,ask:`Let ${o} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:o,created_at:s.createdAt,detail:N(s.content),more:`agentx memory facts held --agent ${o}`});return r}function pa(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function ga(t){return yr(q(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:N(`${pa(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var eo=new Map;function io(t,e){let n=ia(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=eo.get(t);if(o?.version===r)return o.value;let s=e();return eo.set(t,{version:r,value:s}),s}function fa(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${N(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:N(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function ma(t,e){let n=q(t);if(!V(_(n,"_facts.json")))return;let r=Ie(new ee(n),"pending").find(o=>o.id===e);return r?fa(r):void 0}function ha(t){let e=_(q(t),"_facts.json");if(!V(e))return;let n=io(e,()=>Ie(new ee(ro(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function ba(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function ao(t){let e=q(t),n=new st(e);if(!V(n.path))return[];let r=io(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new ee(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:ba(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function ya(t){return zr(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:N(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function wa(t){return $r(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:N(`Last try not sent: ${e.error}`)}:{}}))}function xa(t){let e=Object.entries(at(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Ne(t).agents??{};return e.map(([r,o])=>{let s=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${s.name||r}", created by ${o.by}`,ask:`Let ${s.name||r} (${s.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:o.by,created_at:o.at,detail:N(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Ne(t){try{return JSON.parse(wt(te(t),"utf-8"))}catch{return{}}}function yt(t){let e={};try{e=Object.fromEntries(On(wt(_(ro(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function ka(t){let e=ar(t.root,"pending");if(e.length===0)return[];let n=Ne(t),r=yt(t);return e.map(o=>{let s=pe[o.platform]??o.platform;return{key:`content:${o.id}`,kind:"content",title:`${s} post${o.topic?`: ${o.topic}`:""}${o.date?` (for ${o.date})`:""}`,ask:`Publish this on ${s}? "${o.text}"`,yes:Qr({config:n,env:r},o.agent,o.platform)?`post it on ${s}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:o.agent,created_at:o.created_at,detail:N(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:sr(o.text)}})}function G(t){if(t.requests)return t.requests;if(_(t.root)!==process.cwd()||!V(_(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e)return null;let n=to.get(e);return!n&&!Rn(e)?null:(n||to.set(e,n=new Tn(e)),n)}var to=new WeakMap;function _p(t){if(t.plans)return t.plans;if(t.requests||_(t.root)!==process.cwd()||!V(_(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e||!mr(e))return null;let n=no.get(e);return n||no.set(e,n=new hr(e)),n}var no=new WeakMap;function va(t){let e=G(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:K(n,120).headline,ask:`Not finished. Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:N(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var lo={card:la,schedule:da,agent:xa,memory:ua,wiki:ga,fact:()=>[],question:ao,whatsapp:ya,email:wa,content:ka,request:va};function Sa(t,e){let n=t.expires?Date.parse(t.expires):1/0,r=e.expires?Date.parse(e.expires):1/0;return n!==r?n-r:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function co(t,e={}){let n=t.now??Date.now(),{snoozed:r}=O(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??oo){if(d==="fact"){try{let c=ha(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=lo[d](t)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let p=r[c.key];if(p&&Date.parse(p)>n){if(!e.includeSnoozed){a++;continue}c.snoozed_until=p}o.push(c)}}return o.sort(Sa),{items:o,snoozed:a,errors:s,backlog:i}}function uo(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!oo.includes(n)||!r?null:{kind:n,ref:r}}function $a(t,e,n){switch(e){case"card":return ce(t.root,n)?.status==="pending";case"wiki":return br(q(t),n)?.status==="pending";case"whatsapp":return Oe(t.root,n)?.status==="pending";case"email":return Sr(t.root,n)?.status==="pending";case"content":return ir(t.root,n)?.status==="pending";default:return!!po(t,e,n)}}function po(t,e,n){return e==="fact"?ma(t,n):lo[e](t).find(r=>r.key===`${e}:${n}`)}async function go(t,e,n,r={}){let o=n==="later"?null:uo(e),s;if(o)try{s=po(t,o.kind,o.ref)}catch{s=void 0}let i=await Ea(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;Ln(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:i.verdict??n,...a?{choice:a}:{},...r.text&&i.verdict!=="no"?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function Ea(t,e,n,r){let o=uo(e);if(!o)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:i}=o,a=t.now??Date.now(),d=r.by??"operator";if(n==="later"){if(!$a(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,p=new Date(a+c*36e5);return Mr(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=Bn(t.root,i,l?"yes":"no",{by:d,note:r.note,now:a,choice:r.choice,text:r.text,popup:r.popup});if(!c.ok)return c;let p=c.card.verdict??(l?"yes":"no"),u=l&&p==="no"?", an option that means no":"";return{ok:!0,verdict:p,message:`${e}: ${c.card.raised_by} will be told ${p}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""}${u})`:""}`}}case"schedule":{let c=await(l?rr:or)(i,{configPath:te(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(at(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return lt(t.root,i,"approval"),{ok:!0,message:`${e}: approved. It runs once the daemon has loaded it; if it was added while the daemon was running, run: agentx daemon restart`};let c=[],p=await Re(u=>{Xn(u,`agents.${i}`);for(let[g,f]of Object.entries(u.crons??{}))f?.agent===i&&(delete u.crons[g],c.push(g))},{configPath:te(t),reload:t.reload});return p.success?(lt(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${c.length?`, with its schedules ${c.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:p.error||"could not remove it from agentx.json"}}case"memory":{let c=i.indexOf("/");if(c<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let p=i.slice(0,c),u=i.slice(c+1);if(!so(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new it(t.root);return g.held(p).some(f=>f.id===u)?(g.review(p,u,l?"approved":"rejected",d),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${u}" isn't waiting for review`}}case"wiki":{let c=q(t),p=l?wr(c,i,{by:d,force:r.force,now:a}):xr(c,i,{by:d,reason:r.note,now:a});return p.ok?{ok:!0,message:l?`${p.proposal.article.path} written to the shared wiki`:`${e} rejected`}:p}case"fact":return Aa(t,e,i,l,d,r);case"question":return Ra(t,e,i,l,d,r);case"whatsapp":{let c=await Xr(t.root,i,l?"yes":"no",{by:d,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:l?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??Ar(Ne(t),yt(t)),p=await Er(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,send:c});return p.ok?{ok:!0,message:l?`${e}: sent to ${p.draft.to}${p.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:p}case"content":{let c=t.publishContent??Zr({config:Ne(t),env:yt(t)}),p=await lr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,seen:r.seen,publish:c});if(!p.ok)return p;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let u=pe[p.draft.platform];return{ok:!0,message:p.draft.status==="posted"?`${e}: posted on ${u}${p.draft.url?` (${p.draft.url})`:""}`:`${e}: no ${u} connector is set, so it is saved ready to paste: ${p.draft.file}`}}case"request":{let c=G(t),p=c?.get(i);return!c||!p||p.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?Wr(te(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${d}`,a,null,d==="operator"?_n:d),{ok:!0,message:`${e}: dropped`})}}}function Aa(t,e,n,r,o,s){let i=new ee(q(t));try{let a=Ie(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return Yn(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=Jn(i,a.id,o);return{ok:!0,message:`${e}: ${d.write.fact.subject} \xB7 ${d.write.fact.attribute} recorded as "${d.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function _a(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function Ra(t,e,n,r,o,s){let i=q(t),a=new st(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Hn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=ao(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${d.id} "<value>"`};let c=_a(l.choices,s.choice);if(!c)return{ok:!1,error:`pick one of: ${l.choices.map((g,f)=>`${f+1}. ${g}`).join(", ")}`};let p=new ee(i),u=d.factId?p.get(d.factId):void 0;return u&&p.write({subject:u.subject,attribute:u.attribute,value:c,source:"owner said",verifiedBy:o,volatility:u.volatility},{confirmedBy:o}),a.resolve(d.id,"answered",c),{ok:!0,message:`${e}: answered "${c}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var Ta=3,Ia=7,Da=50,kt=120,Ca=280,xt=600,mo=36e5,Oa=24*mo;function Ip(t){let e=new Set;for(let n of t)for(let r of n.runningTasks??[])r.traceId&&e.add(r.traceId);return e}function ne(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var Le=t=>new Date(t).toISOString();function Na(t,e,n){let r=e.key.slice(0,Math.max(0,e.key.indexOf(":")))||"card";return{key:e.key,kind:r,column:"yours",node:t.node,nodeName:t.nodeName,title:ne(e.title,kt),...e.ask?{ask:ne(e.ask,xt)}:{},...e.detail?{facts:ne(e.detail,Ca)}:{},...e.recommend?{recommend:e.recommend}:{},...e.raisedBy?{agent:e.raisedBy}:{},...e.yes?{yes:e.yes}:{},...e.no?{no:e.no}:{},...e.choices?.length?{choices:e.choices}:{},...e.draft?{draft:e.draft}:{},...e.expires?{expires:e.expires}:{},...e.ifSilent?{ifSilent:e.ifSilent}:{},...e.createdAt?{askedAt:e.createdAt}:{},can:{answer:!0,later:!0,reply:n&&r==="request"}}}var La={done:"Done",declined:"Declined",dropped:"Dropped"};function ho(t,e,n){let{record:r,links:o}=e,s=K(r,kt),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:ne(s.said,xt)}:{},agent:r.agentId,askedAt:Le(r.createdAt),changedAt:Le(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return o.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:ne(r.question,xt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),d=t.now-r.updatedAt<(t.quietHours??Ta)*mo;return{...i,column:a||d?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:Le(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:La[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function Pa(t){return t.status==="decided"?t.verdict==="yes"?`Answered yes${t.choice?`: ${t.choice}`:""}`:"Answered no":t.status==="expired"?`No answer in time: ${t.outcome==="discard"?"discarded":t.outcome==="pause"?"paused":"kept"}`:"Closed by the agent"}function Ma(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:ne(e.title,kt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:Pa(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,fo=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(r))[0];function vt(t){let e=[],n=[];for(let o of t.inbox){o.error&&n.push(`What waits on ${o.nodeName} could not be read: ${o.error}`);for(let s of o.items)e.push(Na(o,s,o.node===t.node))}let r=bo(t,e);for(let o of t.requests??[]){let s=ho(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function bo(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Dp(t){let e=vt(t.owner?{...t,requests:null}:t),n=t.owner?[...t.owner.items,...e.cards]:e.cards,r=t.owner?[...t.owner.errors,...e.errors]:e.errors,o=bo(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=ho(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??Ia)*Oa;for(let u of t.cards)u.status!=="pending"&&L(u.decided_at)>=d&&a.push(Ma(t,u));s.sort((u,g)=>L(g.changedAt)-L(u.changedAt)),i.sort((u,g)=>L(u.changedAt)-L(g.changedAt)),a.sort((u,g)=>L(g.changedAt)-L(u.changedAt));let l=a.filter(u=>L(u.changedAt)>=d).slice(0,Da),c=fo(n,"askedAt"),p=fo(i,"changedAt");return{ts:Le(t.now),cards:[...n,...s,...i,...l],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:s.length},quiet:{count:i.length,...p?{oldest:p}:{}},done:{count:l.length}},errors:r}}function Fa(t){return{key:t.key,title:t.title,ask:t.ask,recommend:t.recommend,yes:t.yes,no:t.no,raisedBy:t.raised_by,expires:t.expires,...t.if_silent?{ifSilent:t.if_silent}:{},...t.choices?{choices:t.choices}:{},...t.draft?{draft:t.draft}:{},...t.detail?{detail:t.detail}:{},...t.created_at?{createdAt:t.created_at}:{}}}function Wa(t,e,n){let r=t.map(o=>o.askedAt).filter(o=>!!o&&!!Date.parse(o)).sort((o,s)=>Date.parse(o)-Date.parse(s));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function Lp(t,e){let n=t.now??Date.now(),r=[],o=co(t,{includeSnoozed:!0});for(let c of o.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let s=o.items.filter(c=>!c.snoozed_until),i=new Set(o.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=G(t);c&&(a=c.listByState("waiting_owner").map(p=>({record:p,links:c.links(p.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:d,errors:l}=vt({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Fa)}],requests:a,deferred:i});return Wa(d,i.size,[...r,...l])}import{readFileSync as Ua}from"fs";var ja=1e4,yo=/^[0-9a-f]{7,64}$/i;function Fp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&yo.test(i)?{source:n,commit:i}:{source:n,commit:null,error:"this build does not carry its commit (run from source?)"}}let r;try{r=await e(n,{signal:AbortSignal.timeout(ja)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let o=await r.json().catch(()=>null),s=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,o);return typeof s=="string"&&yo.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Wp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Ua(n.tokenFile,"utf-8").trim().split(`
|
|
8
|
+
`)[0].trim()||void 0}catch{}let o=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??o?.host??"https://gitlab.com",token:e?.gitlab?.token??o?.token}}}var Pe=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function jp(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/assistant"||t.startsWith("/api/assistant/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/api/org"||t.startsWith("/api/org/")||t==="/content"||t.startsWith("/content/")||t==="/integrations"||t.startsWith("/integrations/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||t==="/events/hub"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"||t==="/lookup"}function Bp(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/events"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)||/^\/channels\/[^/]+\/switch$/.test(t)||/^\/workflow-runs\/[^/]+\/cancel$/.test(t)||t==="/api/signals/stop"||t==="/api/signals/resume"||t==="/api/signals/drop"||t==="/api/signals/stop-all"||t==="/api/signals/stop-all/report"||t==="/api/review-gate/replay"}function Hp(t){return Pe.has(t)}function Vp(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Pe.has(t.remoteAddress))return{allowed:!0,reason:"loopback"};if(t.acceptedTokens.size===0)return{allowed:!0,reason:"no-tokens-configured"};let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.acceptedTokens.has(n)?{allowed:!0,reason:"token"}:{allowed:!1,reason:"missing-or-invalid-token"}}function qp(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.chatSecret&&n===t.chatSecret?!0:t.foreignBrowser?!1:n&&t.acceptedTokens.has(n)?!0:!t.chatSecret&&Pe.has(t.remoteAddress)}function zp(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return t.chatSecret?n===t.chatSecret:Pe.has(t.remoteAddress)||!!n&&t.acceptedTokens.has(n)}function Xp(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let r of t.mesh?.peers||[])r.token&&n.add(r.token);return n}function Kp(t,e,n=process.env){let r=s=>s.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(s=>r(s.url)===e)?.token)||n.MESH_TOKEN||void 0}function Me(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Ba(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ha(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function Jp(t,e=Ha()){let n=Me(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=Ba(n),s=[Me(t.host),Me(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=Me(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function Yp(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var St="/api/admin/pictures",Va=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,qa=/^\/api\/admin\/pictures\/(agent|person)\/([^/]+)$/;function E(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}function za(t){let e={agent:{},person:{}};for(let n of cr)for(let[r,o]of Object.entries(pr(t,n)))e[n][r]=gr(n,r,o);return e}function eg(t,e,n,r,o){let s=n.match(Va);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return E(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=fr(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":dr,"Content-Length":String(a.length),"Cache-Control":"private, max-age=31536000, immutable","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'"}),e.end(a),!0):(E(e,404,{error:"no such picture"}),!0)}async function tg(t,e,n,r){if(n!==St&&!n.startsWith(`${St}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===St)return o!=="GET"?(E(e,405,{error:"GET only"}),!0):(E(e,200,{...za(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(qa);if(!s)return E(e,404,{error:"not found"}),!0;if(o!=="PUT"&&o!=="DELETE")return E(e,405,{error:"PUT or DELETE only"}),!0;let i=t.headers["x-requested-with"];if(i!=="agentx-board"&&i!=="agentx-admin")return E(e,400,{error:"missing X-Requested-With: agentx-board"}),!0;let a=s[1],d=decodeURIComponent(s[2]),l=a==="agent"?r.agentIds():r.personIds();if(!ur.test(d)||!l.includes(d))return E(e,404,{error:a==="agent"?`no agent "${d}" in agentx.json`:`no person "${d}" in agentx.json`}),!0;if(o==="DELETE"){let c=pt(r.root,a,d);return E(e,200,{ok:!0,removed:c}),!0}try{let c=await gt(t),p=await ut(r.root,a,d,c);E(e,200,{ok:!0,url:p.url})}catch(c){if(c instanceof dt)return E(e,c.status,{error:c.message}),!0;throw c}return!0}async function ng(t,e,n,r){let o=(t.method||"GET").toUpperCase();if(o!=="PUT"&&o!=="DELETE"){E(e,405,{error:"PUT or DELETE only"});return}let s=n.searchParams.get("agent")?.trim()||void 0,i=r.provenAgent(s);if(!i){E(e,403,{error:"Only an agent sets its own picture, from its own run: send X-AgentX-Task (or X-AgentX-Channel and X-AgentX-Chat) of a running turn. The owner sets pictures in Settings."});return}if(s&&s!==i){E(e,403,{error:`An agent can only change its own picture: this run is "${i}", not "${s}".`});return}if(o==="DELETE"){E(e,200,{ok:!0,agent:i,removed:pt(r.root,"agent",i)});return}try{let a=await ut(r.root,"agent",i,await gt(t));E(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof dt){E(e,a.status,{error:a.message});return}throw a}}var wo={};function sg(t){wo=t}function ig(){return wo}var ag=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
|
69
9
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
|
70
10
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
71
11
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
72
12
|
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&family=Roboto+Mono:wght@400;500;600&display=swap" rel="stylesheet">
|
|
73
|
-
<script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`,
|
|
13
|
+
<script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`,lg=`
|
|
74
14
|
.ax-topbar{display:flex;align-items:center;justify-content:space-between;
|
|
75
15
|
padding:8px 18px;border-bottom:1px solid var(--ax-border);
|
|
76
16
|
background:var(--ax-bg-elev);position:sticky;top:0;z-index:20;gap:10px;flex-wrap:nowrap}
|
|
@@ -151,7 +91,7 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as _r,O as Dr,k as K}from"./ch
|
|
|
151
91
|
background:var(--ax-bg-elev);border-bottom:1px solid var(--ax-border);
|
|
152
92
|
flex-wrap:wrap}
|
|
153
93
|
.ax-subheader > * {flex-shrink:0}
|
|
154
|
-
.ax-subheader .spacer{flex:1}`,
|
|
94
|
+
.ax-subheader .spacer{flex:1}`,cg=`<script>
|
|
155
95
|
(function(){
|
|
156
96
|
function wireTheme(){
|
|
157
97
|
var sw = document.querySelectorAll('[data-theme-opt]');
|
|
@@ -346,16 +286,16 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as _r,O as Dr,k as K}from"./ch
|
|
|
346
286
|
document.addEventListener('DOMContentLoaded', wire);
|
|
347
287
|
} else { wire(); }
|
|
348
288
|
})();
|
|
349
|
-
</script>`;function
|
|
289
|
+
</script>`;function dg(t){let e=n=>typeof n=="string"&&n?n:null;return{node:e(t?.node?.id),version:e(t?.version),commit:e(t?.commit),startedAt:e(t?.startedAt),diskNewer:t?.build?.newer===!0}}var Xa='<span class="ax-build" hidden></span>';function ug(t){let e=t.peers&&t.peers.length>0?t.peers:[{id:"local",name:"this daemon",dashboardUrl:"",primary:!0}],n=t.currentPeerId||e.find(l=>l.primary)?.id||e[0].id,r=e.find(l=>l.id===n)||e[0],o=e.map(l=>{let c=l.id===n,p=l.primary?' <span style="color:var(--ax-muted);font-size:10px">\xB7 primary</span>':"",u=!!l.tokenScope&&!l.primary,g=u?"#":l.dashboardUrl?`${l.dashboardUrl.replace(/\/+$/,"")}/admin`:"#",f=u?` data-peer-id="${j(l.id)}" data-peer-action="proxy"`:l.primary?' data-peer-id="primary" data-peer-action="proxy"':"",m=u?'<div class="url" style="color:var(--ax-accent)">manage from this dashboard \u2713</div>':l.tokenScope?`<div class="url">${j(l.tokenScope)}</div>`:l.dashboardUrl?'<div class="url" style="color:var(--ax-muted)">(open peer dashboard \u2197)</div>':"";return`<a href="${j(g)}" class="${c?"is-current":""}"${f}>
|
|
350
290
|
<div class="row"><span class="dot"></span><span>${j(l.name)}${p}</span></div>
|
|
351
291
|
${l.dashboardUrl?`<div class="url">${j(l.dashboardUrl)}</div>`:""}
|
|
352
|
-
${
|
|
292
|
+
${m}
|
|
353
293
|
</a>`}).join(""),s=`<div class="ax-mesh-sel" aria-haspopup="menu">
|
|
354
294
|
<span class="lbl">managing</span>
|
|
355
295
|
<span class="name">${j(r.name)}</span>
|
|
356
296
|
<span class="chev">\u25BE</span>
|
|
357
297
|
<div class="ax-mesh-menu" role="menu">${o}</div>
|
|
358
|
-
</div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:
|
|
298
|
+
</div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:_e,href:de},{id:"live",label:"Live",href:`${de}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:qn},{id:"people",label:"People",href:`${de}#page=people`},{id:"org",label:"Org",href:"/org"},{id:"activity",label:"Activity",href:"/activity"},{id:"workflows",label:"Workflows",href:"/workflows"},{id:"admin",label:"Settings",href:`${de}#page=settings`}]}].map(l=>{let c=l.tabs.map(p=>{let u=p.id===t.activeTab?"ax-topbar__tab is-active":"ax-topbar__tab",g=p.external?' target="_blank" rel="noopener"':"",f=p.external?' <span style="font-size:9px;opacity:0.6">\u2197</span>':"";return`<a href="${p.href}" class="${u}"${g}>${p.label}${f}</a>`}).join("");return`<div class="ax-topbar__group" title="${j(l.name)} tier"><span class="ax-topbar__group-label">${j(l.name)}</span>${c}</div>`}).join("");return`<header class="ax-topbar">
|
|
359
299
|
<div class="ax-topbar__left">
|
|
360
300
|
<div class="ax-brand">
|
|
361
301
|
<span class="ax-brand__mark">AX</span>
|
|
@@ -366,14 +306,14 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as _r,O as Dr,k as K}from"./ch
|
|
|
366
306
|
</div>
|
|
367
307
|
<div class="ax-topbar__right">
|
|
368
308
|
${t.rightExtras||""}
|
|
369
|
-
${
|
|
309
|
+
${Xa}
|
|
370
310
|
${s}
|
|
371
311
|
<div class="ax-theme-switch" role="tablist" aria-label="Theme">
|
|
372
312
|
<button data-theme-opt="dark">Dark</button>
|
|
373
313
|
<button data-theme-opt="light">Light</button>
|
|
374
314
|
</div>
|
|
375
315
|
</div>
|
|
376
|
-
</header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function j(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}import{existsSync as
|
|
316
|
+
</header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function j(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}import{existsSync as Vo,mkdirSync as vl,readFileSync as Sl,renameSync as $l,writeFileSync as El}from"fs";import{homedir as Al}from"os";import{dirname as _l,join as Rl}from"path";import{execFile as ol,execFileSync as sl}from"child_process";import{execFileSync as Ka}from"child_process";import{existsSync as ko,mkdirSync as Ga,readdirSync as Ja,readFileSync as vo,renameSync as Ya,writeFileSync as Qa}from"fs";import{homedir as So}from"os";import{join as Et}from"path";var P="siri:",$o="com.apple.ttsbundle.gryphon-neural_",Eo=t=>!!t&&t.startsWith($o),Za=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],el=()=>{try{return Ka("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},$t;function At(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&$t!==void 0)return $t;let{platform:n=process.platform,exists:r=ko,prefDomain:o=el}=t,s=n==="darwin"&&Za.every(i=>r(i))&&o();return e||($t=s),s}var Ao=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],_o={aaron:"male",damon:"male",daniel:"male",pierre:"male",samer:"male",arthur:"male",gordon:"male",martin:"male",nora:"female",simone:"female",marie:"female",soha:"female",martha:"female",catherine:"female",helena:"female",nicky:"female"},_t=t=>_o[t.toLowerCase()]??null;function Fe(t){let e=/^com\.apple\.ttsbundle\.gryphon-neural_([a-z]+)_([a-z]{2}-[A-Z]{2})_premium$/.exec(t);return e?{name:e[1],locale:e[2]}:null}var tl=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function nl(t){let e=new Map;for(let n of t)for(let[,r,o,s]of n.matchAll(tl)){let i=`${r}-${o}`,a=`${$o}${s}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:s[0].toUpperCase()+s.slice(1),locale:i,quality:"premium",gender:_o[s]??null,siri:!0})}return[...e.values()]}function We(t=Ao,e={}){if(!At(e))return[];let n=[];for(let r of t){let o;try{o=Ja(r)}catch{continue}for(let s of o)try{n.push(vo(Et(r,s,"Info.plist"),"latin1"))}catch{}}return nl(n)}var xo=`#!/bin/sh
|
|
377
317
|
# Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
|
|
378
318
|
# siri-say.sh [voice] < text speak one line. A Siri voice id switches
|
|
379
319
|
# the OS default for it; any other id is
|
|
@@ -385,7 +325,7 @@ D=com.apple.Accessibility K=SpokenContentDefaultVoiceSelectionsByLanguage
|
|
|
385
325
|
dir="$HOME/.agentx/voice" lock="$HOME/.agentx/voice/siri.lock" saved="$HOME/.agentx/voice/siri-saved.plist"
|
|
386
326
|
stops="$dir/stop"
|
|
387
327
|
read_s=\${AGENTX_SAY_READ_S:-5} stale_s=\${AGENTX_SAY_STALE_S:-30} max_s=\${AGENTX_SAY_MAX_S:-300}
|
|
388
|
-
assets=\${AGENTX_SIRI_ASSET_DIRS:-"${
|
|
328
|
+
assets=\${AGENTX_SIRI_ASSET_DIRS:-"${Ao.join(" ")}"}
|
|
389
329
|
if [ "$1" = --stop ]; then
|
|
390
330
|
mkdir -p "$dir" || exit 1
|
|
391
331
|
# Queued lines see this change and drop. The owner's trap stops say,
|
|
@@ -478,20 +418,20 @@ wait "$say_pid"
|
|
|
478
418
|
status=$?
|
|
479
419
|
say_pid=
|
|
480
420
|
finish $status
|
|
481
|
-
`,
|
|
421
|
+
`,rl=(t=So())=>Et(t,".agentx","voice","siri-say.sh");function Ro(t=So()){let e=rl(t);return ko(e)&&vo(e,"utf8")===xo||(Ga(Et(t,".agentx","voice"),{recursive:!0}),Qa(`${e}.tmp`,xo,{mode:493}),Ya(`${e}.tmp`,e)),e}var To=`ObjC.import("AVFoundation")
|
|
482
422
|
const vs = $.AVSpeechSynthesisVoice.speechVoices, out = []
|
|
483
423
|
for (let i = 0; i < vs.count; i++) {
|
|
484
424
|
const v = vs.objectAtIndex(i)
|
|
485
425
|
out.push([v.identifier.js, v.name.js, v.language.js, Number(v.quality), Number(v.gender)].join("\\t"))
|
|
486
426
|
}
|
|
487
|
-
out.join("\\n")`,
|
|
488
|
-
`)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!
|
|
489
|
-
`)[0]}`),re={at:t,voices:We()}}return re.voices}var
|
|
490
|
-
`),
|
|
491
|
-
${
|
|
427
|
+
out.join("\\n")`,il=new Set(["Fred","Kathy","Ralph","Junior"]),al={Flo:"female",Sandy:"female",Shelley:"female",Grandma:"female",Kathy:"female",Eddy:"male",Reed:"male",Rocko:"male",Grandpa:"male",Fred:"male",Ralph:"male",Junior:"male"};function Io(t){let e=[];for(let n of t.split(`
|
|
428
|
+
`)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!il.has(o)||e.push({id:r,name:o,locale:s,quality:i==="3"?"premium":i==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":al[o]??null})}return e}var ll=10*60*1e3,xg=60*1e3,re=null,Rt=!1;function Tt(t=Date.now(),e=ll){if(process.platform!=="darwin")return[];if(re)t-re.at>e&&!Rt&&(Rt=!0,ol("osascript",["-l","JavaScript","-e",To],{timeout:1e4},(n,r)=>{Rt=!1,n||(re={at:Date.now(),voices:[...Io(String(r)),...We()]})}));else try{re={at:t,voices:[...Io(sl("osascript",["-l","JavaScript","-e",To],{encoding:"utf8",timeout:1e4})),...We()]}}catch(n){It(`[voice] could not list system voices: ${String(n?.message??n).split(`
|
|
429
|
+
`)[0]}`),re={at:t,voices:We()}}return re.voices}var It=t=>process.stderr.write(t+`
|
|
430
|
+
`),Ue=new Set;function kg(t){It=t}function J(t,e){Ue.has(t)||(Ue.add(t),It(e))}function Oo(t){for(let e of Ue)t(e)&&Ue.delete(e)}var No=()=>{};function vg(t){No=t}function Lo(t){try{No(t)}catch(e){J("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var cl={premium:3,enhanced:2,standard:1},dl=new Set(["Grandma","Grandpa"]);function Do(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!dl.has(t.name)?1:0;return cl[t.quality]*10+e}var oe=t=>t.toLowerCase().split(/[-_]/)[0],Co=t=>t.id.startsWith("com.apple.voice.");function Dt(t,e,n,r=new Set){let o=fe(t.filter(a=>!a.siri&&oe(a.locale)===oe(e)),e);if(o.some(Co)&&(o=o.filter(Co)),n==="female"||n==="male"){let a=o.filter(d=>d.gender===n);a.length&&(o=a)}if(!o.length)return null;let s=o.filter(a=>a.quality===o[0].quality),i=new Set([...r].map(a=>a.toLowerCase()));return s.find(a=>!i.has(a.name.toLowerCase()))??s[0]}function fe(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=oe(e),o=t.filter(s=>oe(s.locale)===r);return(o.length?o:t).slice().sort((s,i)=>Do(i)-Do(s)||+(i.locale.toLowerCase()===n)-+(s.locale.toLowerCase()===n)||s.name.localeCompare(i.name)||s.locale.localeCompare(i.locale))}function me(t,e,n="en"){let r=t.trim();if(!r)return null;let o=e.find(l=>l.id===r);if(o)return o;if(r.toLowerCase().startsWith(P)){let l=r.slice(P.length).trim().toLowerCase(),c=fe(e.filter(u=>u.siri&&u.name.toLowerCase()===l),n)[0];if(c||!l)return c??null;let p=me(l,e.filter(u=>oe(u.locale)===oe(n)),n);return p&&J(`siri:${l}`,`[voice] Siri voice "${l}" is not installed; speaking with ${p.name} (${p.locale}) instead.`),p}e=e.filter(l=>!l.siri);let s=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(s?s[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=fe(e.filter(l=>l.name.toLowerCase()===i),n);return(s?a.find(l=>l.quality===s[2].toLowerCase()):void 0)??a[0]??null}function Po(t,e,n=new Set){let r=new Map;if(!e.length)return r;let o=new Set([...n].map(i=>i.toLowerCase())),s="female";for(let i of t){let a=i.gender==="female"||i.gender==="male",d=a?i.gender:s,l=e.filter(p=>!o.has(p.name.toLowerCase())),c=l.find(p=>p.gender===d)??(a?e.find(p=>p.gender===d):void 0)??l[0]??e[r.size%e.length];r.set(i.id,c),o.add(c.name.toLowerCase()),a||(s=s==="female"?"male":"female")}return r}$n();var Ct="system",ul=t=>t.trim().toLowerCase()===Ct,pl="21m00Tcm4TlvDq8ikWAM";function Ot(t,e,n={},r=Tt()){let o=e[t],s=o?.name||t,i=o?.voice,a=Lt(e,n,r).get(t)??null,d=hl(t,i?.system,i?.gender,n,r);return{agentId:t,name:s,provider:i?.provider??n.provider??"system",elevenlabsVoiceId:i?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?Be(a):null,systemByLanguage:d,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||yl(s,o?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var Be=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function gl(t,e,n,r){if(!e||!n.length)return null;let o=me(e,n,r);return o||(J(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),Lo(e)),o}function Uo(t,e){let n=t.trim();if(n.toLowerCase().startsWith(P))return{locale:e,gender:_t(n.slice(P.length).trim())};let r=Fe(n);return r?{locale:r.locale,gender:_t(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var jo=t=>t.toLowerCase().split(/[-_]/)[0],Mo=(t,e)=>typeof t=="string"?t:t?.[jo(e)];function je(t,e,n,r){if(e!==void 0)return ul(e)?null:gl(t,e,n,r)??void 0}var Nt=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function fl(t,e,n,r=new Set){let o=e.locale??"en",s=new Map,i=[],a=je("voice.system",Mo(e.system,o),n,o),d=()=>new Set([...r,...[...s.values()].flatMap(c=>c?[c.name]:[])]);for(let c of t){let p=Mo(c.system,o),u=je(c.id,p,n,o),g=u!==void 0?u:p!==void 0&&n.length?ml(c,p,o,a,n,d()):a!==void 0&&Nt(a,c.gender)?a:void 0;g!==void 0?s.set(c.id,g):i.push({id:c.id,gender:c.gender??null})}let l=d();for(let[c,p]of Po(i,fe(n.filter(u=>!u.siri),o),l))s.set(c,p);return s}function ml(t,e,n,r,o,s){for(let a of t.fallbacks??[]){let d=je(`${t.id}.fallbacks`,a,o,n);if(d!==void 0)return d}if(r!==void 0&&Nt(r,t.gender))return r;let i=Uo(e,n);return Dt(o,i.locale,t.gender??i.gender,s)??void 0}function hl(t,e,n,r,o){if(typeof e=="string")return{};let s={},i=(a,d,l)=>{if(!(!d||typeof d=="string"))for(let[c,p]of Object.entries(d)){let u=je(`${a}.${c}`,p,o,c);u===void 0&&o.length&&(u=Dt(o,c,n??Uo(p,c).gender)??void 0),u!==void 0&&l(u)&&(s[jo(c)]=u)}};return i("voice.system",r.system,a=>Nt(a,n)),i(t,e,()=>!0),s}function _g(t,e){let n=e?Ee(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?Be(r):null}}function Lt(t,e={},n=Tt()){let r=Object.entries(t).map(([o,s])=>({id:o,system:s.voice?.system,gender:s.voice?.gender,fallbacks:s.voice?.fallbacks}));return fl(r,e,n)}function Pt(t,e){let n={provider:t.provider,elevenlabs:bl(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},r=Object.entries(t.systemByLanguage??{});return r.length&&(n.languages=Object.fromEntries(r.map(([o,s])=>[o,s?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function bl(t,e){return t||e||process.env.AGENTX_VOICE_ID||pl}function yl(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",r=/^You are (.+?)\.?$/i.exec(n.trim());if(!r)return`Hello, this is ${t}.`;let o=r[1].replace(/\s*\([^)]*\)/g,"").trim(),[s,...i]=o.split(/,\s*/),a=i.join(", ");return a&&s.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(o)&&o.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${o}.`:`Hello, this is ${t}, ${o}.`}var wl=8*60*60*1e3,xl=500,Fo=class{constructor(e=wl){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let o=this.lastSpoke.get(Wo(e,n));return o===void 0||r-o>this.gapMs}spoke(e,n,r=Date.now()){let o=Wo(e,n);this.lastSpoke.delete(o),this.lastSpoke.set(o,r),this.lastSpoke.size>xl&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},Wo=(t,e)=>`${t}\0${e}`;function Bo(t,e){let n=t.style?` Your speaking manner: ${t.style}.`:"";return e?`[VOICE INTRO] This is your first spoken exchange with this person in a while. Open with one short sentence introducing yourself in your own manner, along the lines of "${t.intro}", then answer.${n}`:"[VOICE CASUAL] You have already introduced yourself in this voice conversation. Do not introduce yourself or greet again; talk casually, like a colleague in the same office."+n}function Rg(t,e,n,r={}){let o=e[t],s=Ot(t,e,r),i=(o?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:s.name,voice:Pt(s),persona:i||`You are ${s.name}.`,introLine:Bo(s,n)}}var kl="[VOICE MODE] This question arrived by voice and your reply will be spoken aloud by a TTS engine. Answer in two or three short sentences. Plain language, no markdown, no code blocks, no bullet points, no URLs. Speak conversationally.";function Tg(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=s=>typeof s=="string"?s.replace(/\s+/g," ").slice(0,200):"",r=n(e.voice.intro),o={agentId:"",name:"",provider:"system",elevenlabsVoiceId:null,systemVoice:null,systemVoiceName:null,systemByLanguage:{},fallback:!0,gender:null,style:n(e.voice.style)||null,intro:r||"Hello."};return`${kl}
|
|
431
|
+
${Bo(o,e.voice.introduce===!0&&!!r)}`}var Tl="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",qo=(t=Al())=>Rl(t,".agentx","voice","health.json");function Il(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===Ct)return!0;if(r.toLowerCase().startsWith(P)){let o=r.slice(P.length).trim().toLowerCase();return e.some(s=>s.siri&&s.name.toLowerCase()===o)}return me(r,e,n)!==null}function Dl(t){let e=t.voice?.locale??"en",n=[],r=(o,s)=>{if(typeof s=="string")n.push({owner:o,name:s,locale:e,perLanguage:!1});else for(let[i,a]of Object.entries(s??{}))n.push({owner:o,name:a,locale:i,perLanguage:!0})};r("voice.system",t.voice?.system);for(let[o,s]of Object.entries(t.agents))(s.voice?.provider??t.voice?.provider??"system")!=="system"&&t.voice?.fallback==="none"||r(o,s.voice?.system);return n}function Cl(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:o,name:s,locale:i,perLanguage:a}of Dl(t)){if(Il(s,e,i))continue;r??=Lt(t.agents,t.voice,e);let d=n.get(s)??{voice:s,agents:[],speaksWith:{}};d.agents.includes(o)||d.agents.push(o);let l=r.get(o);o!=="voice.system"&&!a&&(d.speaksWith[o]=l?Be(l):"the OS default voice"),n.set(s,d)}return[...n.values()]}function Mt(t){let e=Fe(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(P)){let n=t.slice(P.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function Ol(t){let e=t.map(n=>{let r=n.agents.map(o=>n.speaksWith[o]?`${o} (now ${n.speaksWith[o]})`:o).join(", ");return`\u2022 ${Mt(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
|
|
492
432
|
`)}
|
|
493
|
-
Reinstall in ${
|
|
494
|
-
`)
|
|
433
|
+
Reinstall in ${Tl}. Agents switch back on their own once it is installed.`}}function Nl(t=qo()){if(!Vo(t))return null;try{let e=JSON.parse(Sl(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function Ll(t,e){vl(_l(t),{recursive:!0}),El(`${t}.tmp`,JSON.stringify(e,null,2)+`
|
|
434
|
+
`),$l(`${t}.tmp`,t)}var Ho=class{constructor(e){this.deps=e}running=!1;missingNow=!1;hasMissing(){return this.missingNow}async check(e,n,r=new Date){if(this.running||!n.length)return null;this.running=!0;try{let o=this.deps.file??qo(),s=new Map((Nl(o)?.missing??[]).map(p=>[p.voice,p])),i=Cl(e,n),a=i.map(p=>({...p,since:s.get(p.voice)?.since??r.toISOString(),...s.get(p.voice)?.notifiedAt?{notifiedAt:s.get(p.voice).notifiedAt}:{}})),d=[...s.keys()].filter(p=>!i.some(u=>u.voice===p));for(let p of d)this.deps.log(`[voice] ${Mt(p)} is installed again; its agents speak with it again`);d.length&&Oo(p=>d.some(u=>p===u||p.endsWith(`:${u}`)));let l=a.filter(p=>!p.notifiedAt);if(l.length){let{title:p,message:u}=Ol(l);try{await this.deps.notify(p,u);for(let g of l)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${l.map(g=>Mt(g.voice)).join(", ")} not installed`)}catch(g){this.deps.log(`[voice] could not send the missing-voice notice: ${g?.message??g}`)}}this.missingNow=a.length>0;let c={checkedAt:r.toISOString(),missing:a};return(!Vo(o)||JSON.stringify(a)!==JSON.stringify([...s.values()]))&&Ll(o,c),c}finally{this.running=!1}}};import{randomBytes as zo}from"crypto";var Y={content:32e3,messagesPerConversation:200,conversationsPerDevice:100,toolsPerMessage:50,filesPerMessage:U.perMessage},Pl=/^[a-f0-9]{32}$/,Ml=/^c[a-z0-9]{8,32}$/,Fl=/^#[0-9a-fA-F]{6}$/;function Ft(t){return Ml.test(t)}var Xo=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS app_chat_conversations (
|
|
495
435
|
id TEXT PRIMARY KEY, device_id TEXT NOT NULL, title TEXT NOT NULL,
|
|
496
436
|
node TEXT NOT NULL, node_name TEXT NOT NULL, agent TEXT NOT NULL, agent_name TEXT,
|
|
497
437
|
created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
|
@@ -504,34 +444,34 @@ Reinstall in ${Pl}. Agents switch back on their own once it is installed.`}}func
|
|
|
504
444
|
id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, message_id INTEGER NOT NULL,
|
|
505
445
|
path TEXT NOT NULL, name TEXT NOT NULL, mime TEXT NOT NULL, kind TEXT NOT NULL, created_at INTEGER NOT NULL);
|
|
506
446
|
CREATE INDEX IF NOT EXISTS app_chat_files_conversation ON app_chat_files(conversation_id);`),e.prepare("PRAGMA table_info(app_chat_messages)").all().some(o=>o.name==="files")||e.exec("ALTER TABLE app_chat_messages ADD COLUMN files TEXT");let r=e.prepare("PRAGMA table_info(app_chat_conversations)").all();r.some(o=>o.name==="read_at")||e.transaction(()=>{e.prepare("PRAGMA table_info(app_chat_conversations)").all().some(s=>s.name==="read_at")||(e.exec("ALTER TABLE app_chat_conversations ADD COLUMN read_at INTEGER"),e.exec("UPDATE app_chat_conversations SET read_at = updated_at"))}).immediate(),r.some(o=>o.name==="color")||e.exec("ALTER TABLE app_chat_conversations ADD COLUMN color TEXT"),e.exec(`CREATE TABLE IF NOT EXISTS app_chat_delivered (
|
|
507
|
-
key TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, at INTEGER NOT NULL)`)}ownerOf(e){return
|
|
508
|
-
(id, device_id, title, node, node_name, agent, agent_name, color, created_at, updated_at, read_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e,l.title,l.node,l.nodeName,l.agent,l.agentName??null,d??null,o,o,o),this.pruneDevice(e),l}get(e,n){if(!
|
|
447
|
+
key TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, at INTEGER NOT NULL)`)}ownerOf(e){return Ft(e)?this.db.prepare("SELECT device_id FROM app_chat_conversations WHERE id = ?").get(e)?.device_id??null:null}appendOnce(e,n,r,o,s=[],i=Date.now()){return!r||r.length>200?null:this.db.transaction(()=>!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e)||this.db.prepare("INSERT OR IGNORE INTO app_chat_delivered (key, conversation_id, at) VALUES (?, ?, ?)").run(r,n,i).changes===0?null:(this.db.prepare("DELETE FROM app_chat_delivered WHERE at < ?").run(i-30*24*60*6e4),this.appendWithFiles(e,n,o,s))).immediate()}create(e,n,r,o=Date.now()){let s=`c${o.toString(36)}${zo(4).toString("hex")}`,{color:i,...a}=n,d=i&&Fl.test(i)?i:void 0,l={id:s,title:Go(r),...a,...d?{color:d}:{},createdAt:o,updatedAt:o,messages:[]};return this.db.prepare(`INSERT INTO app_chat_conversations
|
|
448
|
+
(id, device_id, title, node, node_name, agent, agent_name, color, created_at, updated_at, read_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e,l.title,l.node,l.nodeName,l.agent,l.agentName??null,d??null,o,o,o),this.pruneDevice(e),l}get(e,n){if(!Ft(n))return null;let r=this.db.prepare("SELECT * FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e);if(!r)return null;let o=this.db.prepare("SELECT * FROM app_chat_messages WHERE conversation_id = ? ORDER BY id").all(n).map(Wl);return{...Ko(r),messages:o}}list(e,n=Y.conversationsPerDevice){return this.db.prepare(`SELECT c.*,
|
|
509
449
|
(SELECT COUNT(*) FROM app_chat_messages m WHERE m.conversation_id = c.id) AS n,
|
|
510
450
|
(SELECT substr(m.content, 1, 240) FROM app_chat_messages m WHERE m.conversation_id = c.id ORDER BY m.id DESC LIMIT 1) AS last
|
|
511
|
-
FROM app_chat_conversations c WHERE c.device_id = ? ORDER BY c.updated_at DESC, c.rowid DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>{let s=typeof o.last=="string"?o.last.replace(/\s+/g," ").trim().slice(0,120):"";return{...
|
|
451
|
+
FROM app_chat_conversations c WHERE c.device_id = ? ORDER BY c.updated_at DESC, c.rowid DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>{let s=typeof o.last=="string"?o.last.replace(/\s+/g," ").trim().slice(0,120):"";return{...Ko(o),messages:o.n,...s?{last:s}:{}}})}markRead(e,n,r=Date.now()){Ft(n)&&this.db.prepare("UPDATE app_chat_conversations SET read_at = MAX(COALESCE(read_at, 0), ?) WHERE id = ? AND device_id = ?").run(r,n,e)}latestWith(e,n){let r=this.db.prepare(`SELECT id, device_id FROM app_chat_conversations WHERE node = ? AND agent = ?
|
|
512
452
|
ORDER BY updated_at DESC, rowid DESC LIMIT 1`).get(e,n);return r?{id:r.id,deviceId:r.device_id}:null}latestDevice(){return this.db.prepare("SELECT device_id FROM app_chat_conversations ORDER BY updated_at DESC, rowid DESC LIMIT 1").get()?.device_id??null}unread(e,n){return this.db.prepare(`SELECT c.id, c.title, c.agent, c.agent_name, c.color,
|
|
513
453
|
substr(m.content, 1, 240) AS answer, m.status, m.at
|
|
514
454
|
FROM app_chat_conversations c
|
|
515
455
|
JOIN app_chat_messages m ON m.id = (SELECT MAX(id) FROM app_chat_messages WHERE conversation_id = c.id)
|
|
516
456
|
WHERE c.device_id = ? AND m.role = 'assistant' AND m.at > COALESCE(c.read_at, 0)
|
|
517
|
-
ORDER BY m.at DESC, m.id DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>({id:o.id,title:o.title,agent:o.agent,...o.agent_name?{agentName:o.agent_name}:{},...o.color?{color:o.color}:{},answer:String(o.answer??"").trim(),status:o.status==="error"||o.status==="stopped"?o.status:"done",at:o.at}))}append(e,n,r){return this.appendWithFiles(e,n,r)!==null}appendWithFiles(e,n,r,o=[]){if(!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e))return null;let i=r.content.length>
|
|
457
|
+
ORDER BY m.at DESC, m.id DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>({id:o.id,title:o.title,agent:o.agent,...o.agent_name?{agentName:o.agent_name}:{},...o.color?{color:o.color}:{},answer:String(o.answer??"").trim(),status:o.status==="error"||o.status==="stopped"?o.status:"done",at:o.at}))}append(e,n,r){return this.appendWithFiles(e,n,r)!==null}appendWithFiles(e,n,r,o=[]){if(!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e))return null;let i=r.content.length>Y.content?r.content.slice(0,Y.content)+`
|
|
518
458
|
|
|
519
|
-
[Cut here: the full answer is in the agent's task history.]`:r.content,a=r.tools?.slice(0,
|
|
459
|
+
[Cut here: the full answer is in the agent's task history.]`:r.content,a=r.tools?.slice(0,Y.toolsPerMessage),d=[];for(let u of o){if(d.length>=Y.filesPerMessage)break;let g=u.filename.trim(),f=ue(g);if(!f||!g||g.length>U.pathChars||g.includes("\0"))continue;let m=(g.split(/[\\/]/).pop()||g).slice(0,120);d.push({id:zo(16).toString("hex"),name:m,mime:f.mime,kind:f.kind,path:g})}let l=d.map(u=>({id:u.id,name:u.name,mime:u.mime,kind:u.kind})),c=this.db.prepare(`INSERT INTO app_chat_messages (conversation_id, role, content, status, error, ui, tools, files, at)
|
|
520
460
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,r.role,i,r.status??null,r.error?.slice(0,500)??null,r.ui?JSON.stringify(r.ui):null,a?.length?JSON.stringify(a):null,l.length?JSON.stringify(l):null,r.at),p=this.db.prepare(`INSERT INTO app_chat_files (id, conversation_id, message_id, path, name, mime, kind, created_at)
|
|
521
461
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let u of d)p.run(u.id,n,Number(c.lastInsertRowid),u.path,u.name,u.mime,u.kind,r.at);return this.db.prepare(`DELETE FROM app_chat_messages WHERE conversation_id = ? AND id NOT IN
|
|
522
|
-
(SELECT id FROM app_chat_messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?)`).run(n,n,
|
|
523
|
-
(SELECT id FROM app_chat_messages WHERE conversation_id = ?)`).run(n,n),this.db.prepare("UPDATE app_chat_conversations SET updated_at = ? WHERE id = ?").run(r.at,n),l}getFile(e,n){if(!
|
|
462
|
+
(SELECT id FROM app_chat_messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?)`).run(n,n,Y.messagesPerConversation),this.db.prepare(`DELETE FROM app_chat_files WHERE conversation_id = ? AND message_id NOT IN
|
|
463
|
+
(SELECT id FROM app_chat_messages WHERE conversation_id = ?)`).run(n,n),this.db.prepare("UPDATE app_chat_conversations SET updated_at = ? WHERE id = ?").run(r.at,n),l}getFile(e,n){if(!Pl.test(n))return null;let r=this.db.prepare(`SELECT f.*, c.node, c.agent FROM app_chat_files f
|
|
524
464
|
JOIN app_chat_conversations c ON c.id = f.conversation_id WHERE f.id = ? AND c.device_id = ?`).get(n,e);return r?{id:r.id,name:r.name,mime:r.mime,kind:r.kind,path:r.path,conversationId:r.conversation_id,node:r.node,agent:r.agent}:null}pruneDevice(e){let n=this.db.prepare(`SELECT id FROM app_chat_conversations WHERE device_id = ?
|
|
525
|
-
ORDER BY updated_at DESC, rowid DESC LIMIT -1 OFFSET ?`).all(e,
|
|
526
|
-
`),
|
|
527
|
-
`)}};function
|
|
528
|
-
`):[]}writeMd(e){let n=
|
|
529
|
-
`))}async listOpen(e){if(this.store.exists())return this.store.list().filter(s=>s.status!=="done"&&(!s.assignee||s.assignee.toLowerCase()===e.toLowerCase())).map(s=>this.toWorkItem(s));let n=this.readMd(),r=[];for(let o=0;o<n.length;o++){let s=n[o].match(
|
|
530
|
-
`);for(let i=0;i<s.length;i++){let a=s[i].match(
|
|
531
|
-
`);n.status==="done"&&i[o]&&(i[o]=i[o].replace(/- \[ \]/,"- [x]"),
|
|
532
|
-
`)))}},Kt=class{constructor(e,n,r,o,s){this.host=e;this.token=n;this.projects=r;this.agentUsernames=o;this.log=s}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[n,r]of Object.entries(this.agentUsernames))if(r.some(o=>o.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,o=[],s;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(s=e.labels.map(l=>({name:l.name,color:l.color,text_color:l.text_color})),o=s.map(l=>l.name)):o=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),d=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:d?this.usernameToAgent(d)||d:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:o,labelDetails:s,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,n={}){let r=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);return r.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let r=[],o=this.projects.length?this.projects:["__ALL__"];for(let s of n)for(let i of o)try{let a=`assignee_username=${encodeURIComponent(s)}&state=opened&scope=all&per_page=20`,d=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,l=await this.api(d);for(let c of l){let p=this.mapIssue(c,i);p.assignee=e,r.push(p)}}catch(a){this.log(`[business] GitLab listOpen failed for ${s} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:o,type:s}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${s==="issue"?"issues":"merge_requests"}/${o}?add_labels=Doing&remove_labels=To Do`;try{await this.api(i,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),d=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/add_spent_time?duration=${encodeURIComponent(d)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,r=new Date(Date.now()-n*24*36e5).toISOString(),o=new URLSearchParams,s=e.state??"opened";o.set("state",s),o.set("updated_after",r),o.set("scope","all"),o.set("per_page","100"),o.set("with_labels_details","true"),o.set("order_by","updated_at"),o.set("sort","desc"),e.labels?.length&&o.set("labels",e.labels.join(",")),e.milestone&&o.set("milestone",e.milestone),e.search&&o.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let l of i)try{let c=l==="__ALL__"?`/issues?${o.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${o.toString()}`,p=await this.api(c);for(let u of p)a.push(this.mapIssue(u,l))}catch(c){this.log(`[business] GitLab listAll failed on ${l}: ${c.message}`)}let d=a;if(e.notLabels?.length){let l=new Set(e.notLabels);d=d.filter(c=>!(c.labels||[]).some(p=>l.has(p)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";d=d.filter(c=>!(c.labels||[]).some(p=>p.startsWith(l)))}return d}async setState(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let o=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(o,n),descriptionHtml:o.description_html||void 0,createdAt:o.created_at,author:o.author?{username:o.author.username,name:o.author.name,avatarUrl:o.author.avatar_url}:void 0,allLabels:Array.isArray(o.labels)?typeof o.labels[0]=="object"?o.labels.map(i=>i.name):o.labels:[]}}catch(o){return this.log(`[board] GitLab getItem failed for ${e}: ${o.message}`),null}}async updateItem(e,n){let{project:r,iid:o}=this.parseId(e),s;n.assigneeUsernames&&(s=(await Promise.all(n.assigneeUsernames.map(async c=>{try{let p=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(p)&&p[0]?.id?p[0].id:null}catch{return null}}))).filter(c=>typeof c=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let l=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),s!==void 0&&(a.assignee_ids=s),i!==void 0&&(a.milestone_id=i);let d=await this.api(`/projects/${encodeURIComponent(r)}/issues/${o}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(d,r)}async listMembers(){let e=new Map;for(let n of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(n)}/members/all?per_page=100`);for(let o of r)o.username&&!e.has(o.username)&&e.set(o.username,{username:o.username,name:o.name,avatarUrl:o.avatar_url})}catch(r){this.log(`[board] listMembers failed for ${n}: ${r.message}`)}return[...e.values()].sort((n,r)=>n.username.localeCompare(r.username))}async listMilestones(){let e=new Map;for(let r of this.projects)try{let o=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let s of o)s.title&&!e.has(s.title)&&e.set(s.title,{id:s.id,title:s.title,state:s.state,dueDate:s.due_date})}catch(o){this.log(`[board] listMilestones failed for ${r}: ${o.message}`)}let n=[...e.values()];return n.sort((r,o)=>r.state!==o.state?r.state==="active"?-1:1:r.title.localeCompare(o.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let r,o=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];o.length&&(r=(await Promise.all(o.map(async l=>{try{let c=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${l}: ${c.message}`),null}}))).filter(l=>typeof l=="number"));let s;if(e.milestoneTitle)try{let d=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(d)&&d[0]?.id&&(s=d[0].id)}catch(d){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${d.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),s!==void 0&&(i.milestone_id=s);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(i)});return this.mapIssue(a,n)}async transition(e,n,r){await this.transitionMany(e,n?[n]:[],r?[r]:[])}async transitionMany(e,n,r){let{project:o,iid:s,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",d=new URLSearchParams;n.length&&d.set("add_labels",n.join(",")),r.length&&d.set("remove_labels",r.join(",")),d.toString()&&await this.api(`/projects/${encodeURIComponent(o)}/${a}/${s}?${d.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),o=r.pop(),s=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:s,iid:o}}};function cm(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new Xt(r.path,e,n);case"wiki":return new zt(r.path,r.glob);case"gitlab":{let o=e.channels.gitlab;if(!o?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let s={};for(let a of o.agentMappings)a.gitlabUsernames.length&&(s[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:o.routes.map(a=>a.project);return new Kt(o.host,o.token,i,s,n)}}}et();var Gt="unmapped";function Yt(t,e=[]){if(!t)return Gt;let n=e.find(o=>o.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function ic(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},o=new Map;for(let i of le(t)){let a=C(i.from),d=C(i.to);i.type==="reports-to"&&a.kind==="agent"&&d.kind==="agent"&&o.set(a.id,d.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,Yt(i.id,n)));let s=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let d=o.get(i);if(!d)return;let l=s(d,a);return l&&e.set(i,l),l};for(let i of Object.keys(r))s(i);return e}function ac(t,e,n=[]){if(!n.length)return;let r=n.filter(o=>!o.channel||o.channel===t);return r.find(o=>o.chatId&&e.chatId&&o.chatId===e.chatId)??r.find(o=>o.username&&e.username&&o.username===e.username)??r.find(o=>o.senderId&&e.senderId&&o.senderId===e.senderId)??r.find(o=>o.channel&&!o.chatId&&!o.username&&!o.senderId)}function pm(t,e){let n=ac(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Yt(t.project,e.projects);if(t.agentId){let r=ic(e).get(t.agentId);if(r)return r}return Gt}function gm(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,o,...s]=n,i=s.join(":"),a={agentId:e||r,channel:o};return o==="gitlab"||o==="github"?a.project=i.split(":")[0]:o==="cron"||o==="api"||(a.chatId=i.split("@")[0]),a}var lc=t=>t===Gt?"internal":"client";function cc(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??lc(t),respondWithinMinutes:dc(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function mm(t){let e=new Set;for(let n of t.projects??[])e.add(Yt(n.id,t.projects));for(let n of t.contactMap??[])e.add(n.client);for(let n of Object.keys(t.clients??{}))e.add(n);return[...e].sort().map(n=>cc(n,t))}function dc(t){let e=/^(\d+)\s*([mhd])$/.exec(String(t??"").trim());if(!e)return;let n=Number(e[1]);return e[2]==="m"?n:e[2]==="h"?n*60:n*1440}import{createHash as uc}from"crypto";var bm={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},pc=40,gc=20,ym=90,mc=2e3,ls=36e5;function fc(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
|
|
533
|
-
${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<
|
|
534
|
-
`);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function
|
|
465
|
+
ORDER BY updated_at DESC, rowid DESC LIMIT -1 OFFSET ?`).all(e,Y.conversationsPerDevice);for(let{id:r}of n)this.db.prepare("DELETE FROM app_chat_files WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_messages WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_conversations WHERE id = ?").run(r)}};function Ko(t){return{id:t.id,title:t.title,node:t.node,nodeName:t.node_name,agent:t.agent,...t.agent_name?{agentName:t.agent_name}:{},...t.color?{color:t.color}:{},createdAt:t.created_at,updatedAt:t.updated_at}}function Wl(t){let e=s=>{if(s)try{return JSON.parse(s)}catch{return}},n=e(t.ui),r=e(t.tools),o=e(t.files);return{role:t.role,content:t.content,at:t.at,...t.status?{status:t.status}:{},...t.error?{error:t.error}:{},...n?{ui:n}:{},...r?{tools:r}:{},...o?{files:o}:{}}}function Go(t){let e=/^\[Call answered\][^"]*"([^"]+)"/.exec(t);if(e)return Go(`Call: ${e[1]}`);let n=t.replace(/\s+/g," ").trim();return(n.length>60?n.slice(0,59)+"\u2026":n)||"Untitled"}import{readFileSync as Ut,writeFileSync as ts,existsSync as jt,readdirSync as Gl,statSync as Jl}from"fs";import{resolve as Bt,join as Yl}from"path";import{existsSync as Jo,mkdirSync as Ul,readFileSync as jl,writeFileSync as Yo}from"fs";import{dirname as Bl,resolve as Qo}from"path";import{z as v}from"zod";var Hl=v.object({type:v.enum(["gitlab","github"]),host:v.string().optional(),project:v.string(),iid:v.number().int().positive(),url:v.string()}),Vl=v.object({id:v.string(),title:v.string(),description:v.string().optional(),assignee:v.string().optional(),labels:v.array(v.string()).default([]),milestone:v.string().optional(),status:v.enum(["todo","doing","blocked","done"]).default("todo"),priority:v.number().int().optional(),estimatedSeconds:v.number().int().optional(),source:Hl.optional(),importedAt:v.string().optional(),createdAt:v.string(),updatedAt:v.string(),blocker:v.string().optional(),doneNote:v.string().optional()}),ql=v.object({version:v.literal(1),items:v.array(Vl).default([])}),He=class{constructor(e){this.path=e}jsonPath(){return Qo(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return Qo(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return Jo(this.jsonPath())}load(){let e=this.jsonPath();if(!Jo(e))return{version:1,items:[]};let n=jl(e,"utf-8");try{return ql.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();Ul(Bl(n),{recursive:!0}),Yo(n,JSON.stringify(e,null,2)+`
|
|
466
|
+
`),Yo(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(n=>n.id===e)}add(e){let n=this.load();if(n.items.some(s=>s.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let r=new Date().toISOString(),o={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??r,updatedAt:r};return n.items.push(o),this.save(n),o}addMany(e){let n=this.load(),r=new Set(n.items.map(i=>i.id)),o=new Date().toISOString(),s=[];for(let i of e){if(r.has(i.id))continue;let a={...i,labels:i.labels??[],status:i.status??"todo",createdAt:i.createdAt??o,updatedAt:o};n.items.push(a),s.push(a),r.add(a.id)}return s.length&&this.save(n),s}update(e,n){let r=this.load(),o=r.items.findIndex(i=>i.id===e);if(o<0)throw new Error(`backlog item ${e} not found`);let s={...r.items[o],...n,id:r.items[o].id,createdAt:r.items[o].createdAt,updatedAt:new Date().toISOString()};return r.items[o]=s,this.save(r),s}remove(e){let n=this.load(),r=n.items.length;return n.items=n.items.filter(o=>o.id!==e),n.items.length===r?!1:(this.save(n),!0)}toMarkdown(e){let n=["# Backlog","","_Generated from `backlog.json`. Do not edit by hand \u2014 use `agentx backlog` commands._",""],r={doing:[],blocked:[],todo:[],done:[]};for(let s of e.items)r[s.status].push(s);let o=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[s,i]of o)if(r[s].length){n.push(`## ${i}`,"");for(let a of r[s]){let d=s==="done"?"x":" ",l=a.assignee?`@${a.assignee} `:"",c=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",p=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${d}] ${l}${a.title}${c}${p}`),a.source?.url&&n.push(` - <${a.source.url}>`),a.labels.length&&n.push(` - labels: ${a.labels.join(", ")}`),a.milestone&&n.push(` - milestone: ${a.milestone}`),a.blocker&&n.push(` - BLOCKED: ${a.blocker}`)}n.push("")}return n.join(`
|
|
467
|
+
`)}};function Vg(t){return`${t.type}:${t.project}:${t.iid}`}function Zo(t,e,n){let r=[];if(e.type==="gitlab"){let o=n.channels.gitlab?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.gitlabUsernames?.length?r.push(i.gitlabUsernames[0]):r.push(s)}}else if(e.type==="github"){let o=n.channels.github?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.githubUsernames?.length?r.push(i.githubUsernames[0]):r.push(s)}}return r}async function Wt(t,e,n,r=()=>{}){return t.source?zl(t.source,e,n,r):{ok:!0,attempts:[]}}async function zl(t,e,n,r=()=>{}){return t.type==="gitlab"?Xl(t,e,n,r):t.type==="github"?Kl(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function Xl(t,e,n,r){let o=n.channels.gitlab,s=o?.token,i=o?.host||(t.host?`https://${t.host}`:void 0);if(!s||!i)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],d=async(g,f={})=>fetch(`${i}/api/v4${g}`,{...f,headers:{"PRIVATE-TOKEN":s,"Content-Type":"application/json",...f.headers||{}}}),l=encodeURIComponent(t.project),c;e.assigneeUsernames!==void 0&&(c=(await Promise.all(e.assigneeUsernames.map(async f=>{try{let m=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(f)}`,{headers:{"PRIVATE-TOKEN":s}});if(!m.ok)return null;let w=await m.json();return Array.isArray(w)&&w[0]?.id?w[0].id:null}catch{return null}}))).filter(f=>typeof f=="number"));let p;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")p=0;else try{let g=await d(`/projects/${l}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let f=await g.json();Array.isArray(f)&&f[0]?.id&&(p=f[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let u={};if(e.title!==void 0&&(u.title=e.title),e.description!==void 0&&(u.description=e.description),e.labels!==void 0&&(u.labels=e.labels.join(",")),e.addLabels?.length&&(u.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(u.remove_labels=e.removeLabels.join(",")),c!==void 0&&(u.assignee_ids=c),p!==void 0&&(u.milestone_id=p),e.state&&(u.state_event=e.state==="closed"?"close":"reopen"),Object.keys(u).length)try{let g=await d(`/projects/${l}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(u)});if(a.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let f=await g.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${g.status}: ${f.slice(0,200)}`,url:t.url}}}catch(g){return a.push({kind:"PUT issue",ok:!1,error:g.message}),{ok:!1,attempts:a,error:g.message,url:t.url}}if(e.note)try{let g=await d(`/projects/${l}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:g.ok,status:g.status})}catch(g){a.push({kind:"POST note",ok:!1,error:g.message})}return{ok:a.every(g=>g.ok),attempts:a,url:t.url}}async function Kl(t,e,n,r){let s=n.channels.github?.token;if(!s)return{ok:!1,error:"github token not configured",attempts:[]};let i=[],a=async(u,g={})=>fetch(`https://api.github.com${u}`,{...g,headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),d=t.project,l;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")l=null;else try{let u=await a(`/repos/${d}/milestones?state=all&per_page=100`);if(u.ok){let g=await u.json(),f=Array.isArray(g)?g.find(m=>m.title===e.milestoneTitle):null;f?.number&&(l=f.number)}}catch(u){r(`[backlog-sync] github milestone lookup failed: ${u.message}`)}let c;if(e.labels!==void 0)c=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let u=await a(`/repos/${d}/issues/${t.iid}`);if(u.ok){let g=await u.json(),f=Array.isArray(g.labels)?g.labels.map(w=>typeof w=="string"?w:w.name):[],m=new Set([...f,...e.addLabels??[]]);for(let w of e.removeLabels??[])m.delete(w);c=[...m]}}catch(u){r(`[backlog-sync] github label fetch failed: ${u.message}`)}if(c===void 0)return{ok:!1,attempts:i,error:"could not read the issue's labels; nothing written",url:t.url}}let p={};if(e.title!==void 0&&(p.title=e.title),e.description!==void 0&&(p.body=e.description),c!==void 0&&(p.labels=c),e.assigneeUsernames!==void 0&&(p.assignees=e.assigneeUsernames),l!==void 0&&(p.milestone=l),e.state&&(p.state=e.state),Object.keys(p).length)try{let u=await a(`/repos/${d}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(p)});if(i.push({kind:"PATCH issue",ok:u.ok,status:u.status}),!u.ok){let g=await u.text().catch(()=>"");return{ok:!1,attempts:i,error:`PATCH issue ${u.status}: ${g.slice(0,200)}`,url:t.url}}}catch(u){return i.push({kind:"PATCH issue",ok:!1,error:u.message}),{ok:!1,attempts:i,error:u.message,url:t.url}}if(e.note)try{let u=await a(`/repos/${d}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST comment",ok:u.ok,status:u.status})}catch(u){i.push({kind:"POST comment",ok:!1,error:u.message})}return{ok:i.every(u=>u.ok),attempts:i,url:t.url}}var Ht=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,Ve=/@([a-z0-9_-]+)/i,es=/\[time:\s*([0-9hm\s]+)\]/i;function Ql(t){let e=t.match(/(\d+)\s*h/i),n=t.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(n?parseInt(n[1],10)*60:0)}var Vt=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new He(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=Bt(process.cwd(),this.path);return jt(e)?Ut(e,"utf-8").split(`
|
|
468
|
+
`):[]}writeMd(e){let n=Bt(process.cwd(),this.path);ts(n,e.join(`
|
|
469
|
+
`))}async listOpen(e){if(this.store.exists())return this.store.list().filter(s=>s.status!=="done"&&(!s.assignee||s.assignee.toLowerCase()===e.toLowerCase())).map(s=>this.toWorkItem(s));let n=this.readMd(),r=[];for(let o=0;o<n.length;o++){let s=n[o].match(Ht);if(!s||s[2].toLowerCase()==="x")continue;let a=s[3],d=a.match(Ve);if(d&&d[1].toLowerCase()!==e.toLowerCase())continue;let l=a.match(es),c=a.replace(Ve,"").replace(es,"").trim();r.push({id:`backlog:${o}`,title:c||`Task at line ${o+1}`,assignee:d?d[1]:void 0,estimatedSeconds:l?Ql(l[1]):void 0,priority:o})}return r}async listAll(e={}){return this.store.exists()?this.store.list().map(n=>this.toWorkItem(n)):[]}async claim(e,n){if(!this.store.exists())return;let r=this.store.findById(n);if(!r)return;let o=this.store.update(n,{assignee:r.assignee||e,status:"doing"});if(o.source&&this.daemon){let s=Zo([o.assignee||e],o.source,this.daemon);Wt(o,{assigneeUsernames:s,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(i=>this.log(`[backlog-sync] claim failed for ${n}: ${i?.message??i}`))}}async report(e,n){if(this.store.exists()&&this.store.findById(e)){let a={};n.status==="done"?a.status="done":n.status==="blocked"?(a.status="blocked",a.blocker=n.blocker||n.note||void 0):n.status==="in-progress"&&(a.status="doing"),n.timeSeconds&&(a.estimatedSeconds=n.timeSeconds);let d=this.store.update(e,a);if(d.source&&this.daemon){let l={};n.status==="done"?(l.addLabels=["Done"],l.removeLabels=["Doing"]):n.status==="blocked"&&(l.addLabels=["Blocked"]),n.note&&(l.note=n.note),Object.keys(l).length&&Wt(d,l,this.daemon,this.log).catch(c=>this.log(`[backlog-sync] report failed for ${e}: ${c?.message??c}`))}return}if(!e.startsWith("backlog:"))throw new Error(`not a backlog id: ${e}`);let r=parseInt(e.slice(8),10),o=this.readMd(),s=o[r];if(!s)throw new Error(`backlog line ${r} missing`);if(!s.match(Ht))throw new Error(`backlog line ${r} not a checkbox`);if(n.status==="done"){o[r]=s.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";o.splice(r+1,0,a)}else n.status==="blocked"?o.splice(r+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&o.splice(r+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(o)}toWorkItem(e){let n={todo:"todo",doing:"doing",blocked:"onhold",done:"done"}[e.status];return{id:e.id,title:e.title,description:e.description,assignee:e.assignee,estimatedSeconds:e.estimatedSeconds,priority:e.priority,labels:e.labels,stage:n,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},qt=class{constructor(e,n){this.root=e;this.glob=n}type="wiki";capabilities={listAll:!1,create:!1,transition:!1,labels:!1,search:!1};walk(e,n){if(jt(e))for(let r of Gl(e)){let o=Yl(e,r);Jl(o).isDirectory()?this.walk(o,n):r.endsWith(".md")&&n.push(o)}}async listOpen(e){let n=[];this.walk(Bt(process.cwd(),this.root),n);let r=[];for(let o of n){let s=Ut(o,"utf-8").split(`
|
|
470
|
+
`);for(let i=0;i<s.length;i++){let a=s[i].match(Ht);if(!a||a[2].toLowerCase()==="x")continue;let d=a[3].match(Ve);!d||d[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${o}:${i}`,title:a[3].replace(Ve,"").trim(),assignee:d[1],priority:i})}}return r}async claim(){}async report(e,n){let r=e.split(":"),o=parseInt(r[r.length-1],10),s=r.slice(1,-1).join(":");if(!jt(s))return;let i=Ut(s,"utf-8").split(`
|
|
471
|
+
`);n.status==="done"&&i[o]&&(i[o]=i[o].replace(/- \[ \]/,"- [x]"),ts(s,i.join(`
|
|
472
|
+
`)))}},zt=class{constructor(e,n,r,o,s){this.host=e;this.token=n;this.projects=r;this.agentUsernames=o;this.log=s}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[n,r]of Object.entries(this.agentUsernames))if(r.some(o=>o.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,o=[],s;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(s=e.labels.map(l=>({name:l.name,color:l.color,text_color:l.text_color})),o=s.map(l=>l.name)):o=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),d=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:d?this.usernameToAgent(d)||d:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:o,labelDetails:s,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,n={}){let r=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);return r.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let r=[],o=this.projects.length?this.projects:["__ALL__"];for(let s of n)for(let i of o)try{let a=`assignee_username=${encodeURIComponent(s)}&state=opened&scope=all&per_page=20`,d=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,l=await this.api(d);for(let c of l){let p=this.mapIssue(c,i);p.assignee=e,r.push(p)}}catch(a){this.log(`[business] GitLab listOpen failed for ${s} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:o,type:s}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${s==="issue"?"issues":"merge_requests"}/${o}?add_labels=Doing&remove_labels=To Do`;try{await this.api(i,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),d=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/add_spent_time?duration=${encodeURIComponent(d)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,r=new Date(Date.now()-n*24*36e5).toISOString(),o=new URLSearchParams,s=e.state??"opened";o.set("state",s),o.set("updated_after",r),o.set("scope","all"),o.set("per_page","100"),o.set("with_labels_details","true"),o.set("order_by","updated_at"),o.set("sort","desc"),e.labels?.length&&o.set("labels",e.labels.join(",")),e.milestone&&o.set("milestone",e.milestone),e.search&&o.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let l of i)try{let c=l==="__ALL__"?`/issues?${o.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${o.toString()}`,p=await this.api(c);for(let u of p)a.push(this.mapIssue(u,l))}catch(c){this.log(`[business] GitLab listAll failed on ${l}: ${c.message}`)}let d=a;if(e.notLabels?.length){let l=new Set(e.notLabels);d=d.filter(c=>!(c.labels||[]).some(p=>l.has(p)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";d=d.filter(c=>!(c.labels||[]).some(p=>p.startsWith(l)))}return d}async setState(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let o=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(o,n),descriptionHtml:o.description_html||void 0,createdAt:o.created_at,author:o.author?{username:o.author.username,name:o.author.name,avatarUrl:o.author.avatar_url}:void 0,allLabels:Array.isArray(o.labels)?typeof o.labels[0]=="object"?o.labels.map(i=>i.name):o.labels:[]}}catch(o){return this.log(`[board] GitLab getItem failed for ${e}: ${o.message}`),null}}async updateItem(e,n){let{project:r,iid:o}=this.parseId(e),s;n.assigneeUsernames&&(s=(await Promise.all(n.assigneeUsernames.map(async c=>{try{let p=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(p)&&p[0]?.id?p[0].id:null}catch{return null}}))).filter(c=>typeof c=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let l=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),s!==void 0&&(a.assignee_ids=s),i!==void 0&&(a.milestone_id=i);let d=await this.api(`/projects/${encodeURIComponent(r)}/issues/${o}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(d,r)}async listMembers(){let e=new Map;for(let n of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(n)}/members/all?per_page=100`);for(let o of r)o.username&&!e.has(o.username)&&e.set(o.username,{username:o.username,name:o.name,avatarUrl:o.avatar_url})}catch(r){this.log(`[board] listMembers failed for ${n}: ${r.message}`)}return[...e.values()].sort((n,r)=>n.username.localeCompare(r.username))}async listMilestones(){let e=new Map;for(let r of this.projects)try{let o=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let s of o)s.title&&!e.has(s.title)&&e.set(s.title,{id:s.id,title:s.title,state:s.state,dueDate:s.due_date})}catch(o){this.log(`[board] listMilestones failed for ${r}: ${o.message}`)}let n=[...e.values()];return n.sort((r,o)=>r.state!==o.state?r.state==="active"?-1:1:r.title.localeCompare(o.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let r,o=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];o.length&&(r=(await Promise.all(o.map(async l=>{try{let c=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${l}: ${c.message}`),null}}))).filter(l=>typeof l=="number"));let s;if(e.milestoneTitle)try{let d=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(d)&&d[0]?.id&&(s=d[0].id)}catch(d){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${d.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),s!==void 0&&(i.milestone_id=s);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(i)});return this.mapIssue(a,n)}async transition(e,n,r){await this.transitionMany(e,n?[n]:[],r?[r]:[])}async transitionMany(e,n,r){let{project:o,iid:s,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",d=new URLSearchParams;n.length&&d.set("add_labels",n.join(",")),r.length&&d.set("remove_labels",r.join(",")),d.toString()&&await this.api(`/projects/${encodeURIComponent(o)}/${a}/${s}?${d.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),o=r.pop(),s=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:s,iid:o}}};function Yg(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new Vt(r.path,e,n);case"wiki":return new qt(r.path,r.glob);case"gitlab":{let o=e.channels.gitlab;if(!o?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let s={};for(let a of o.agentMappings)a.gitlabUsernames.length&&(s[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:o.routes.map(a=>a.project);return new zt(o.host,o.token,i,s,n)}}}Ze();var Xt="unmapped";function Kt(t,e=[]){if(!t)return Xt;let n=e.find(o=>o.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function Zl(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},o=new Map;for(let i of le(t)){let a=C(i.from),d=C(i.to);i.type==="reports-to"&&a.kind==="agent"&&d.kind==="agent"&&o.set(a.id,d.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,Kt(i.id,n)));let s=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let d=o.get(i);if(!d)return;let l=s(d,a);return l&&e.set(i,l),l};for(let i of Object.keys(r))s(i);return e}function ec(t,e,n=[]){if(!n.length)return;let r=n.filter(o=>!o.channel||o.channel===t);return r.find(o=>o.chatId&&e.chatId&&o.chatId===e.chatId)??r.find(o=>o.username&&e.username&&o.username===e.username)??r.find(o=>o.senderId&&e.senderId&&o.senderId===e.senderId)??r.find(o=>o.channel&&!o.chatId&&!o.username&&!o.senderId)}function ef(t,e){let n=ec(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Kt(t.project,e.projects);if(t.agentId){let r=Zl(e).get(t.agentId);if(r)return r}return Xt}function tf(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,o,...s]=n,i=s.join(":"),a={agentId:e||r,channel:o};return o==="gitlab"||o==="github"?a.project=i.split(":")[0]:o==="cron"||o==="api"||(a.chatId=i.split("@")[0]),a}var tc=t=>t===Xt?"internal":"client";function nc(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??tc(t),respondWithinMinutes:rc(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function nf(t){let e=new Set;for(let n of t.projects??[])e.add(Kt(n.id,t.projects));for(let n of t.contactMap??[])e.add(n.client);for(let n of Object.keys(t.clients??{}))e.add(n);return[...e].sort().map(n=>nc(n,t))}function rc(t){let e=/^(\d+)\s*([mhd])$/.exec(String(t??"").trim());if(!e)return;let n=Number(e[1]);return e[2]==="m"?n:e[2]==="h"?n*60:n*1440}import{createHash as oc}from"crypto";var sf={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},sc=40,ic=20,af=90,ac=2e3,ns=36e5;function lc(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
|
|
473
|
+
${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<sc?null:`text:${oc("sha256").update(r).digest("hex").slice(0,24)}`}function lf(t){let e=t.indexOf(`
|
|
474
|
+
`);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function Gt(t){t.exec(`
|
|
535
475
|
CREATE TABLE IF NOT EXISTS owner_told (
|
|
536
476
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
537
477
|
at INTEGER NOT NULL,
|
|
@@ -549,34 +489,34 @@ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<pc?null:`text:${u
|
|
|
549
489
|
CREATE INDEX IF NOT EXISTS idx_owner_told_key_at ON owner_told(item_key, at);
|
|
550
490
|
CREATE INDEX IF NOT EXISTS idx_owner_told_at ON owner_told(at);
|
|
551
491
|
CREATE INDEX IF NOT EXISTS idx_owner_told_digest ON owner_told(outcome, digested_at);
|
|
552
|
-
`);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of
|
|
553
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,
|
|
492
|
+
`);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of cc)if(!e.has(n))try{t.exec(`ALTER TABLE owner_told ADD COLUMN ${n} ${r}`)}catch(o){if(!/duplicate column/i.test(String(o?.message)))throw o}}var cc=[["urgent","INTEGER NOT NULL DEFAULT 0"],["seen_at","INTEGER"],["seen_via","TEXT"],["answered_at","INTEGER"],["answered_via","TEXT"],["escalated_at","INTEGER"],["escalation_of","INTEGER"]];function qe(t){return{id:t.id,at:t.at,key:t.item_key,requestId:t.request_id??null,kind:t.kind,channel:t.channel,chatId:t.chat_id,from:t.sender??null,title:t.title,text:t.text,outcome:t.outcome,digestedAt:t.digested_at??null,urgent:t.urgent===1,seenAt:t.seen_at??null,seenVia:t.seen_via??null,answeredAt:t.answered_at??null,answeredVia:t.answered_via??null,escalatedAt:t.escalated_at??null,escalationOf:t.escalation_of??null,state:t.answered_at!=null?"answered":t.seen_at!=null?"seen":"sent"}}var rs=class{constructor(e){this.db=e;Gt(e)}add(e){return Number(this.db.prepare(`INSERT INTO owner_told (at, item_key, request_id, kind, channel, chat_id, sender, title, text, outcome, urgent, escalation_of)
|
|
493
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,ac),e.outcome,e.urgent?1:0,e.escalationOf??null).lastInsertRowid)}get(e){let n=this.db.prepare("SELECT * FROM owner_told WHERE id = ?").get(e);return n?qe(n):null}setOutcome(e,n){this.db.prepare("UPDATE owner_told SET outcome = ? WHERE id = ?").run(n,e)}lastTold(e,n,r=!0){let o=this.db.prepare(`SELECT * FROM owner_told WHERE item_key = ? AND at >= ? AND outcome IN ('sent', 'held'${r?", 'digest'":""}) ORDER BY at DESC LIMIT 1`).get(e,n);return o?qe(o):null}waitingForDigest(e=500){return this.db.prepare("SELECT * FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL ORDER BY at LIMIT ?").all(e).map(qe)}waitingCount(){return this.db.prepare("SELECT COUNT(*) AS n FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL").get().n}markDigested(e,n){let r=this.db.prepare("UPDATE owner_told SET digested_at = ? WHERE id = ?");this.db.transaction(()=>{for(let o of e)r.run(n,o)})()}since(e,n=200){return this.db.prepare("SELECT * FROM owner_told WHERE at >= ? ORDER BY at DESC, id DESC LIMIT ?").all(e,n).map(qe)}counts(e){let n={sent:0,held:0,digest:0,repeat:0,failed:0};for(let r of this.db.prepare("SELECT outcome, COUNT(*) AS n FROM owner_told WHERE at >= ? GROUP BY outcome").all(e))n[r.outcome]=r.n;return n}states(e){let n=this.db.prepare(`SELECT SUM(CASE WHEN answered_at IS NULL AND seen_at IS NULL THEN 1 ELSE 0 END) AS sent,
|
|
554
494
|
SUM(CASE WHEN answered_at IS NULL AND seen_at IS NOT NULL THEN 1 ELSE 0 END) AS seen,
|
|
555
495
|
SUM(CASE WHEN answered_at IS NOT NULL THEN 1 ELSE 0 END) AS answered
|
|
556
|
-
FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},
|
|
496
|
+
FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},os=class{constructor(e,n,r=Date.now){this.ledger=e;this.settings=n;this.now=r}isOwnerAddress(e,n){let r=this.settings();return r.enabled?r.channels.includes(e)||r.addresses.includes(`${e}:${n}`):!1}decide(e,n={}){let r=this.settings(),o=this.now(),s=lc(n,e.title,e.text),i=n.kind??"notice",a=(s?.startsWith("text:")?Math.min(r.repeatWindowHours,ic):r.repeatWindowHours)*ns,d=r.digestNags&&r.digestAvailable!==!1,l="send";!n.urgent&&s&&this.ledger.lastTold(s,o-a,d)?l="repeat":!n.urgent&&i==="nag"&&d&&(l="digest");let c=this.ledger.add({at:o,key:s??`once:${o}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:l==="send"?"sent":l,urgent:n.urgent===!0});return{verdict:l,key:s,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:dc(e),ids:e.map(n=>n.id)}:null}markDigested(e){this.ledger.markDigested(e,this.now())}report(e,n=50){return{counts:this.ledger.counts(e),landed:this.ledger.states(e),waitingForDigest:this.ledger.waitingCount(),items:this.ledger.since(e,n)}}prune(e){return this.ledger.prune(this.now()-e*24*ns)}};function cf(t,e){let n=t&&typeof t=="object"?t:{},r=(i,a)=>typeof i=="string"&&i.trim()?i.trim().slice(0,a):void 0,o=n.kind==="nag"||n.kind==="notice"?n.kind:void 0,s=r(n.from,100)??r(e,100);return{...r(n.key,190)?{key:`send:${r(n.key,190)}`}:{},...r(n.requestId,100)?{requestId:r(n.requestId,100)}:{},...o?{kind:o}:{},...n.urgent===!0?{urgent:!0}:{},...n.textKey===!0?{textKey:!0}:{},...s?{from:s}:{}}}function dc(t,e=5,n=3){let r=new Map;for(let a of t){let[d,...l]=a.title.split(": "),c=l.join(": ").trim(),p=r.get(d.trim())??{count:0,names:[]};p.count++,c&&!p.names.includes(c)&&p.names.push(c),r.set(d.trim(),p)}let o=[...r.entries()].sort((a,d)=>d[1].count-a[1].count),s=o.slice(0,e).map(([a,{count:d,names:l}])=>{let c=l.length?` (${l.slice(0,n).join(", ")}${l.length>n?", \u2026":""})`:"";return`${a}${d>1?` \xD7${d}`:""}${c}`}),i=o.length>e?`; ${o.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${s.join("; ")}${i}.`}function uf(t,e){let n=`${e}/call?to=${encodeURIComponent(t.from)}&callId=${encodeURIComponent(t.callId)}`;return t.reason==="camera"?`\u{1F4F7} ${t.from} is sharing a phone camera \u2014 tap to watch: ${n}&watch=1`:`\u{1F4DE} ${t.from} is calling \u2014 tap to join: ${n}`}var uc=5*6e4;function z(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var ss=class{subs=new Set;log;forwarder;localName;allowedCallers;pending=new Map;cleanupTimer;ringHandler;recentRings=new Map;constructor(e,n=[],r=console.error.bind(console,"[webrtc]")){this.localName=e,this.allowedCallers=new Set(n.map(z)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${z(n)}`}cleanupExpired(){let e=Date.now();for(let[n,r]of this.pending){let o=r.filter(s=>s.expiresAt>e);o.length===0?this.pending.delete(n):o.length!==r.length&&this.pending.set(n,o)}for(let[n,r]of this.recentRings)r<=e&&this.recentRings.delete(n)}setForwarder(e){this.forwarder=e}setRingHandler(e){this.ringHandler=e}subscribe(e,n,r){return this.addSubscriber(e,n,{kind:"sse",res:r})}subscribeInternal(e,n,r){return this.addSubscriber(e,n,{kind:"callback",deliver:r})}addSubscriber(e,n,r){let o={callId:e,recipient:n,sink:r};this.subs.add(o);let s=r.kind==="sse"?"sse":"internal";this.log(`subscribe[${s}] call=${e} as=${n} (${this.subs.size} total)`);let i=this.pendingKey(e,n),a=this.pending.get(i);if(a&&a.length){let d=Date.now(),l=a.filter(c=>c.expiresAt>d);for(let{signal:c}of l)this.deliverTo(o,c);this.pending.delete(i),l.length&&this.log(`flushed ${l.length} buffered signal(s) to new subscriber call=${e} as=${n}`)}return()=>{this.subs.delete(o),this.log(`unsubscribe[${s}] call=${e} as=${n} (${this.subs.size} remaining)`)}}deliverTo(e,n){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
|
|
557
497
|
data: ${JSON.stringify(n)}
|
|
558
498
|
|
|
559
|
-
`):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=
|
|
560
|
-
`),
|
|
499
|
+
`):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=z(e.to);if(n===z(this.localName)||this.hasSubscriberFor(e.callId,n))return this.fanOut(e),{ok:!0};if(!this.forwarder)return{ok:!1,error:"mesh forwarder not wired"};let o=await this.forwarder(e.to,e);return o?{ok:o}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&z(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(z(e.from)))return this.log(`reject inbound ${e.kind} from "${e.from}": not in allowedCallers`),{ok:!1,error:"caller not allowed"};if(e.kind==="ring"){let r=Date.now(),o=this.recentRings.get(e.callId);if(o&&o>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+uc),this.ringHandler)try{this.ringHandler(e)}catch(s){this.log(`ringHandler threw: ${s.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let r=this.pendingKey(e.callId,e.to),o=this.pending.get(r)||[];o.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,o),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${o.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=z(e.to);for(let o of this.subs)o.callId===e.callId&&z(o.recipient)===r&&(this.deliverTo(o,e)?n++:this.subs.delete(o));return n}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};import{mkdirSync as pc,readFileSync as is,renameSync as gc,rmSync as fc,writeFileSync as mc}from"fs";import{homedir as hc}from"os";import{dirname as bc,join as yc}from"path";var as=yc(hc(),".agentx","call.json");function wc(t=as,e=Date.now()){try{let n=JSON.parse(is(t,"utf-8"));if(n?.active===!0&&!(n.until&&Date.parse(n.until)<=e))return{active:!0,mode:"call",reason:`in a call${n.reason?`: ${n.reason}`:""}`}}catch{}return{active:!1,mode:null,reason:"not in a call"}}function ls(t=Qn,e=wc){let n=t();return n.active?n:e()}function bf(t,e,n=as,r=Date.now()){let o=null;try{o=JSON.parse(is(n,"utf-8"))}catch{}if(o&&o.source&&o.source!=="daemon")return;if(!t){o&&fc(n,{force:!0});return}pc(bc(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;mc(s,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
|
|
500
|
+
`),gc(s,n)}var cs="owner",ze=6e4,fs=60*ze,xc=24*fs,kc=7*24*fs,vc=2*ze,xf={enabled:!1,escalateAfterMinutes:10,ladder:[]};function Sc(t){t.exec(`
|
|
561
501
|
CREATE TABLE IF NOT EXISTS owner_presence (
|
|
562
502
|
person TEXT NOT NULL,
|
|
563
503
|
surface TEXT NOT NULL,
|
|
564
504
|
at INTEGER NOT NULL,
|
|
565
505
|
PRIMARY KEY (person, surface)
|
|
566
506
|
);
|
|
567
|
-
`)}var
|
|
507
|
+
`)}var ds=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;Sc(e)}written=new Map;touch(e,n=cs){let r=this.now(),o=`${n}
|
|
568
508
|
${e}`;r-(this.written.get(o)??-1/0)<this.throttleMs||(this.written.set(o,r),this.db.prepare(`INSERT INTO owner_presence (person, surface, at) VALUES (?, ?, ?)
|
|
569
|
-
ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=
|
|
509
|
+
ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=cs){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function kf(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var us=class{constructor(e,n=Date.now){this.db=e;this.now=n;Gt(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
|
|
570
510
|
WHERE request_id IS NOT NULL AND answered_at IS NULL AND outcome IN ('sent', 'held') AND at >= ?
|
|
571
|
-
ORDER BY at DESC LIMIT 500`).all(this.now()-
|
|
572
|
-
WHERE seen_at IS NULL AND (${
|
|
573
|
-
WHERE answered_at IS NULL AND (${
|
|
511
|
+
ORDER BY at DESC LIMIT 500`).all(this.now()-kc)}seenByRequest(e,n){return this.byRequest(e,r=>this.seen(r,n))}answeredByRequest(e,n,r=this.now()){return this.byRequest(e,o=>this.answered(o,n,r),r)}seenPush(e,n="phone"){let r=[],o=this.db.prepare("SELECT id, title FROM owner_told WHERE channel = 'push' AND outcome IN ('sent', 'held') AND at BETWEEN ? AND ? ORDER BY at DESC");for(let s of e){let i=s.title.endsWith("\u2026")?s.title.slice(0,-1):s.title,d=o.all(s.at-vc,s.at).find(l=>l.title===s.title||i!==s.title&&l.title.startsWith(i));d&&r.push(d.id)}return this.seen(r,n)}seen(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET seen_at = ?, seen_via = ?
|
|
512
|
+
WHERE seen_at IS NULL AND (${ps(e)})`).run(r,n,...e,...e,...e).changes:0}answered(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET answered_at = ?, answered_via = ?, seen_at = COALESCE(seen_at, ?), seen_via = COALESCE(seen_via, ?)
|
|
513
|
+
WHERE answered_at IS NULL AND (${ps(e)})`).run(r,n,r,n,...e,...e,...e).changes:0}byRequest(e,n,r=1/0){let o=new Set(e.filter(Boolean));if(!o.size)return 0;let s=this.openRequestRows().filter(i=>o.has(i.requestId)&&i.at<=r).map(i=>i.id);return n(s)}};function ps(t){let e=t.map(()=>"?").join(", ");return`id IN (${e}) OR escalation_of IN (${e}) OR id IN (SELECT escalation_of FROM owner_told WHERE id IN (${e}) AND escalation_of IS NOT NULL)`}function vf(t,e,n){let r=t.ladder.length?t.ladder:[...e.channels.map(s=>`${s}:default`),...e.addresses],o=[];for(let s of r){let i=s.trim(),a=he(i);a&&n(a)&&!o.includes(i)&&o.push(i)}return o}function he(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function $c(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function Ec(t){return he(t)==="push"?["phone","desk"]:[t]}function Sf(t,e,n){let r=t.filter(s=>n(he(s)));if(!r.length)return null;let o=null;for(let s of r){let i=Math.max(-1/0,...e.filter(a=>Ec(s).includes(a.surface)).map(a=>a.at));Number.isFinite(i)&&(!o||i>o.at)&&(o={stop:s,at:i})}return o?.stop??r[0]}function Ac(t,e,n){let r=t.indexOf(e);return(r<0?t:[...t.slice(r+1),...t.slice(0,r)]).find(s=>s!==e&&n(he(s)))??null}var _c=3;async function $f(t){let{db:e,ledger:n,settings:r,now:o}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let s=r.escalateAfterMinutes*ze,i=e.prepare(`SELECT id FROM owner_told
|
|
574
514
|
WHERE urgent = 1 AND seen_at IS NULL AND answered_at IS NULL
|
|
575
515
|
AND escalated_at IS NULL AND escalation_of IS NULL AND at >= ?
|
|
576
516
|
AND ((outcome = 'sent' AND at <= ?) OR outcome = 'failed')
|
|
577
|
-
ORDER BY at LIMIT 20`).all(Math.max(o-
|
|
517
|
+
ORDER BY at LIMIT 20`).all(Math.max(o-_c*s,o-xc),o-s),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),d=0;for(let{id:l}of i){if(a.run(o,l).changes!==1)continue;let c=n.get(l);if(!c)continue;let p=`${c.channel}:${c.chatId}`,u=Ac(t.stops,p,t.up);if(!u){t.log(`[reach] urgent "${c.title.slice(0,80)}" ${c.outcome==="failed"?"failed":"unseen"} on ${p}; no other address to try`);continue}let g=Math.round((o-c.at)/ze),f=c.outcome==="failed"?`it could not be sent on ${c.channel}`:`not seen on ${c.channel} for ${g} min`,m=`${c.text?`${c.text}
|
|
578
518
|
|
|
579
|
-
`:""}(Sent again here: ${m}.)`,w=n.add({at:o,key:c.key,requestId:c.requestId,kind:c.kind,channel:he(u),chatId:Dc(u),from:c.from,title:c.title,text:f,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(u,c,f),d++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${m}; sent once to ${u}`)}catch(x){n.setOutcome(w,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${u} failed: ${x?.message??x}`)}}return d}var ws=class{constructor(e){this.opts=e}state=new Map;tick(){let e=(this.opts.now??Date.now)(),n=this.opts.confirmChecks??2;for(let[r,o]of Object.entries(this.opts.read())){let s=this.state.get(r)??{downSince:null,checks:0,told:!1};if(o.up){s.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}s.downSince??=e,s.checks++,s.reason=o.reason,!s.told&&s.checks>=n&&(s.told=!0,this.opts.log(`[reach] channel ${r} is down: ${o.reason??"no reason given"}`),this.opts.notice(r,o.reason??"no reason given")),this.state.set(r,s)}}downSince(e){return this.state.get(e)?.downSince??void 0}};function Lc(t,e){let n={"reports-to":"report to","dotted-line":"have a dotted line to","acts-for":"act for"},r={};for(let l of t.members)r[l.ref]=l;let o=l=>l&&r[l]?r[l].name:String(l||"").replace(/^(agent|person):/,""),s=l=>!!l&&!!r[l]&&r[l].kind==="agent",i=l=>l.length<2?l.join(""):l.slice(0,-1).join(", ")+" and "+l[l.length-1],a=o(e.from),d=o(e.to);if(e.op==="add-relation"&&e.type==="reports-to"){let l=t.relations.find(p=>p.type==="reports-to"&&p.from===e.from),c=s(e.from)?" When "+a+" is stuck, it asks "+d+" first.":"";return l&&l.to!==e.to&&e.from!==e.to?{text:a+" will report to "+d+", not "+o(l.to)+"."+c,steps:[{op:"remove-relation",from:l.from,type:"reports-to",to:l.to},e],undo:[{op:"add-relation",from:l.from,type:"reports-to",to:l.to}]}:{text:a+" will report to "+d+"."+c,steps:[e],undo:[]}}if(e.op==="add-relation")return{text:a+" will "+(n[e.type||""]||e.type)+" "+d+".",steps:[e],undo:[]};if(e.op==="remove-relation"){let l=e.type==="reports-to"&&s(e.from)?" When "+a+" is stuck, it no longer asks "+d+".":"";return{text:a+" will no longer "+(n[e.type||""]||e.type)+" "+d+"."+l,steps:[e],undo:[]}}if(e.op==="remove-member"){let l=t.relations.filter(p=>p.from===e.member||p.to===e.member).length,c=t.relations.filter(p=>p.type==="reports-to"&&p.to===e.member).map(p=>o(p.from));return{text:o(e.member)+" will leave the org chart"+(l?", with "+l+" "+(l===1?"line":"lines"):"")+"."+(c.length?" "+i(c)+" will report to no one.":""),steps:[e],undo:[]}}return null}function Mm(t){let e=c=>String(c??"").replace(/[&<>"']/g,p=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[p]),n={"dotted-line":"dotted line to","acts-for":"acts for"};if(!t||!t.members.length)return"";let r={};for(let c of t.members)r[c.ref]=c;let o={};for(let c of t.relations)c.type==="reports-to"&&r[c.to]&&(o[c.from]=c.to);let s=c=>r[c]?r[c].name:c.replace(/^(agent|person):/,""),i={},a=c=>{i[c.ref]=!0;let p=t.relations.filter(g=>g.from===c.ref&&g.type!=="reports-to").map(g=>(n[g.type]||g.type)+" "+s(g.to)),u=t.members.filter(g=>o[g.ref]===c.ref&&!i[g.ref]);return"<li><b>"+e(c.name)+'</b> <span class="org-kind">'+(c.kind==="person"?"Person":"Agent")+(c.title?" \xB7 "+e(c.title):"")+"</span>"+(p.length?" <small>"+e(p.join(", "))+"</small>":"")+(u.length?"<ul>"+u.map(a).join("")+"</ul>":"")+"</li>"};return'<ul class="oe-tree" aria-label="Org chart">'+t.members.filter(c=>!o[c.ref]).map(a).join("")+t.members.filter(c=>!i[c.ref]).map(a).join("")+"</ul>"}function Pc(t,e,n){let r=h=>String(h??"").replace(/[&<>"']/g,S=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[S]),o={"reports-to":"Reports to","dotted-line":"Dotted line to","acts-for":"Acts for"},s={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"},i=(h,S)=>'<option value="'+r(h)+'">'+r(S)+"</option>";if(!t)return'<p class="org-quiet">Loading\u2026</p>';if(!t.canEdit||!t.setup||!t.choices)return"";let a='<p class="oe-msg'+(e.bad?" is-bad":"")+'" role="status">'+r(e.text)+"</p>",d=n?'<div class="oe-confirm" id="oe-confirm" role="group" aria-label="Confirm the change"><p class="oe-confirm-text">'+r(n)+'</p><span class="oe-acts"><button type="button" class="ax-btn ax-btn--primary" id="oe-confirm-save" data-oe="confirm">Save the move</button><button type="button" class="ax-btn" data-oe="cancel">Cancel</button></span></div>':"",l=t.choices,c=t.setup.members,p={};for(let h of c)p[h.ref]=h;let u=h=>p[h]?p[h].name:h.replace(/^(agent|person):/,""),g=h=>h.filter(S=>!p[S.ref]).map(S=>i(S.ref,S.name)).join(""),m=g(l.agents),f=g(l.people),w='<div class="oe-form" role="group" aria-label="Add a member"><label for="oe-add-member">Member <select id="oe-add-member">'+(m||f?(m?'<optgroup label="Agents">'+m+"</optgroup>":"")+(f?'<optgroup label="People">'+f+"</optgroup>":""):'<option value="">Everyone is in the chart</option>')+'</select></label><label for="oe-add-role">Role <input id="oe-add-role" list="oe-roles" maxlength="80" placeholder="Engineer" autocomplete="off"></label><button type="button" class="ax-btn" data-oe="add-member"'+(m||f?"":" disabled")+'>Add</button></div><datalist id="oe-roles">'+l.roles.map(h=>i(h.title,h.key)).join("")+"</datalist>",x=[["mon","Mon","Monday"],["tue","Tue","Tuesday"],["wed","Wed","Wednesday"],["thu","Thu","Thursday"],["fri","Fri","Friday"],["sat","Sat","Saturday"],["sun","Sun","Sunday"]],b=(h,S)=>{if(h.kind!=="agent")return"";let Qe=h.schedule||{start:"",end:"",days:[]};return'<fieldset class="oe-hours"><legend class="org-kind">Working hours of '+r(h.name)+'</legend><label for="oe-start-'+S+'">Start <input type="time" id="oe-start-'+S+'" value="'+r(Qe.start)+'" aria-label="Start time of '+r(h.name)+'"></label><label for="oe-end-'+S+'">End <input type="time" id="oe-end-'+S+'" value="'+r(Qe.end)+'" aria-label="End time of '+r(h.name)+'"></label><span class="oe-days" role="group" aria-label="Working days of '+r(h.name)+'">'+x.map(Se=>'<label class="oe-day"><input type="checkbox" name="oe-days-'+S+'" value="'+Se[0]+'"'+(Qe.days.indexOf(Se[0])>=0?" checked":"")+' aria-label="'+Se[2]+'">'+Se[1]+"</label>").join("")+'</span><button type="button" class="ax-btn" data-oe="set-schedule" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save hours</button></fieldset>'},y=c.length?'<ul class="oe-rows">'+c.map((h,S)=>'<li class="oe-row"><span class="oe-who"><b>'+r(h.name)+'</b><span class="org-kind">'+(h.kind==="person"?"Person":"Agent")+'</span></span><label class="oe-role" for="oe-role-'+S+'"><span class="org-kind">Role</span><input id="oe-role-'+S+'" list="oe-roles" maxlength="80" value="'+r(h.title||"")+'" aria-label="Role of '+r(h.name)+'"></label><span class="oe-acts"><button type="button" class="ax-btn" data-oe="set-role" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save role</button><button type="button" class="ax-btn" data-oe="remove-member" data-oe-member="'+r(h.ref)+'" aria-label="Remove '+r(h.name)+'">Remove</button><a class="ax-btn" href="/hub#page=settings&section=agents&under='+encodeURIComponent(h.ref)+'" aria-label="Add an agent who reports to '+r(h.name)+'">Add agent here</a></span>'+b(h,S)+"</li>").join("")+"</ul>":'<p class="org-quiet">No one in the org chart yet. Add a member above.</p>',k=t.setup.relations,D=k.length?'<ul class="oe-rows">'+k.map(h=>'<li class="oe-row"><span class="oe-who">'+r(u(h.from))+' <span class="org-kind">'+r(s[h.type]||h.type)+"</span> "+r(u(h.to))+'</span><span class="oe-acts"><button type="button" class="ax-btn" data-oe="remove-relation" data-oe-from="'+r(h.from)+'" data-oe-type="'+r(h.type)+'" data-oe-to="'+r(h.to)+'" aria-label="Remove: '+r(u(h.from)+" "+(s[h.type]||h.type)+" "+u(h.to))+'">Remove</button></span></li>').join("")+"</ul>":'<p class="org-quiet">No relations yet.</p>',ae=c.map(h=>i(h.ref,h.name+(h.kind==="person"?" (person)":""))).join(""),ve=c.length>=2?'<div class="oe-form" role="group" aria-label="Add a relation"><label for="oe-rel-from">Member <select id="oe-rel-from">'+ae+'</select></label><label for="oe-rel-type">Relation <select id="oe-rel-type">'+l.types.map(h=>i(h,o[h]||h)).join("")+'</select></label><label for="oe-rel-to">Target <select id="oe-rel-to">'+ae+'</select></label><button type="button" class="ax-btn" data-oe="add-relation">Add relation</button></div>':'<p class="org-quiet">Add two members to link them.</p>';return'<p class="oe-lead">Each change is checked, saved to agentx.json with a backup, and used at once, with no restart. A change to a line, or a removal, asks you first.</p>'+a+d+'<h2 class="org-h2">Add a member</h2>'+w+'<h2 class="org-h2">Members <span class="org-kind">'+c.length+"</span></h2>"+y+'<h2 class="org-h2">Relations <span class="org-kind">'+k.length+"</span></h2>"+D+ve+'<dl class="oe-legend"><dt>Reports to</dt><dd>The line manager, one at most. Work an agent cannot finish goes up this line.</dd><dt>Dotted line to</dt><dd>A second manager for one topic or project.</dd><dt>Acts for</dt><dd>An agent works on behalf of a person.</dd><dt>Working hours</dt><dd>When an agent is on the clock. An empty start or end, or no day ticked, goes back to 09:00 to 17:00, Monday to Friday.</dd></dl>'}function Fm(t){let e={msg:"",bad:!1,pending:null,focus:!1},n=i=>{let a=document.getElementById(i);return a?a.value:""};async function r(i,a,d){d&&(d.disabled=!0);let l=0,c={};try{for(;l<i.length;l++)c=await t.post(i[l]);e.msg=(c.summary||"Saved")+". Saved.",e.bad=!1}catch(p){if(e.msg=p.message,e.bad=!0,l>0)try{for(let u of a)await t.post(u);e.msg+=" Nothing was changed."}catch(u){e.msg+=" Putting the old line back failed too: "+u.message+". Check the chart below."}}await t.reload(),t.paint(),d&&(d.disabled=!1)}function o(i,a){let d=t.org(),l=d&&d.setup?Lc(d.setup,i):null;if(!l){r([i],[],a);return}e.pending=l,e.msg="",e.bad=!1,e.focus=!0,t.paint()}function s(){e.pending=null,e.msg="Cancelled. Nothing changed.",e.bad=!1,t.paint()}return{E:e,html:()=>Pc(t.org(),{text:e.msg,bad:e.bad},e.pending?e.pending.text:""),focus(){if(e.focus){let i=document.getElementById("oe-confirm-save");i&&i.focus()}e.focus=!1},click(i){let a=i&&i.closest?i.closest("[data-oe]"):null;if(!a)return!1;let d=a.getAttribute("data-oe")||"",l=c=>a.getAttribute("data-oe-"+c)||"";if(d==="confirm"){let c=e.pending;if(!c)return!0;e.pending=null,r(c.steps,c.undo,a)}else if(d==="cancel")s();else if(d==="add-member")n("oe-add-member")&&r([{op:d,member:n("oe-add-member"),role:n("oe-add-role")}],[],a);else if(d==="set-role")r([{op:d,member:l("member"),role:n("oe-role-"+l("i"))}],[],a);else if(d==="set-schedule"){let c=[];document.querySelectorAll('input[name="oe-days-'+l("i")+'"]').forEach(p=>{p.checked&&c.push(p.value)}),r([{op:d,member:l("member"),start:n("oe-start-"+l("i")),end:n("oe-end-"+l("i")),days:c}],[],a)}else d==="add-relation"?o({op:d,from:n("oe-rel-from"),type:n("oe-rel-type"),to:n("oe-rel-to")},a):d==="remove-member"?o({op:d,member:l("member")},a):d==="remove-relation"&&o({op:d,from:l("from"),type:l("type"),to:l("to")},a);return!0},key(i){i.key==="Escape"&&e.pending&&(i.preventDefault(),s())}}}var Um=`
|
|
519
|
+
`:""}(Sent again here: ${f}.)`,w=n.add({at:o,key:c.key,requestId:c.requestId,kind:c.kind,channel:he(u),chatId:$c(u),from:c.from,title:c.title,text:m,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(u,c,m),d++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${f}; sent once to ${u}`)}catch(x){n.setOutcome(w,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${u} failed: ${x?.message??x}`)}}return d}var gs=class{constructor(e){this.opts=e}state=new Map;tick(){let e=(this.opts.now??Date.now)(),n=this.opts.confirmChecks??2;for(let[r,o]of Object.entries(this.opts.read())){let s=this.state.get(r)??{downSince:null,checks:0,told:!1};if(o.up){s.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}s.downSince??=e,s.checks++,s.reason=o.reason,!s.told&&s.checks>=n&&(s.told=!0,this.opts.log(`[reach] channel ${r} is down: ${o.reason??"no reason given"}`),this.opts.notice(r,o.reason??"no reason given")),this.state.set(r,s)}}downSince(e){return this.state.get(e)?.downSince??void 0}};function Rc(t,e){let n={"reports-to":"report to","dotted-line":"have a dotted line to","acts-for":"act for"},r={};for(let l of t.members)r[l.ref]=l;let o=l=>l&&r[l]?r[l].name:String(l||"").replace(/^(agent|person):/,""),s=l=>!!l&&!!r[l]&&r[l].kind==="agent",i=l=>l.length<2?l.join(""):l.slice(0,-1).join(", ")+" and "+l[l.length-1],a=o(e.from),d=o(e.to);if(e.op==="add-relation"&&e.type==="reports-to"){let l=t.relations.find(p=>p.type==="reports-to"&&p.from===e.from),c=s(e.from)?" When "+a+" is stuck, it asks "+d+" first.":"";return l&&l.to!==e.to&&e.from!==e.to?{text:a+" will report to "+d+", not "+o(l.to)+"."+c,steps:[{op:"remove-relation",from:l.from,type:"reports-to",to:l.to},e],undo:[{op:"add-relation",from:l.from,type:"reports-to",to:l.to}]}:{text:a+" will report to "+d+"."+c,steps:[e],undo:[]}}if(e.op==="add-relation")return{text:a+" will "+(n[e.type||""]||e.type)+" "+d+".",steps:[e],undo:[]};if(e.op==="remove-relation"){let l=e.type==="reports-to"&&s(e.from)?" When "+a+" is stuck, it no longer asks "+d+".":"";return{text:a+" will no longer "+(n[e.type||""]||e.type)+" "+d+"."+l,steps:[e],undo:[]}}if(e.op==="remove-member"){let l=t.relations.filter(p=>p.from===e.member||p.to===e.member).length,c=t.relations.filter(p=>p.type==="reports-to"&&p.to===e.member).map(p=>o(p.from));return{text:o(e.member)+" will leave the org chart"+(l?", with "+l+" "+(l===1?"line":"lines"):"")+"."+(c.length?" "+i(c)+" will report to no one.":""),steps:[e],undo:[]}}return null}function Af(t){let e=c=>String(c??"").replace(/[&<>"']/g,p=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[p]),n={"dotted-line":"dotted line to","acts-for":"acts for"};if(!t||!t.members.length)return"";let r={};for(let c of t.members)r[c.ref]=c;let o={};for(let c of t.relations)c.type==="reports-to"&&r[c.to]&&(o[c.from]=c.to);let s=c=>r[c]?r[c].name:c.replace(/^(agent|person):/,""),i={},a=c=>{i[c.ref]=!0;let p=t.relations.filter(g=>g.from===c.ref&&g.type!=="reports-to").map(g=>(n[g.type]||g.type)+" "+s(g.to)),u=t.members.filter(g=>o[g.ref]===c.ref&&!i[g.ref]);return"<li><b>"+e(c.name)+'</b> <span class="org-kind">'+(c.kind==="person"?"Person":"Agent")+(c.title?" \xB7 "+e(c.title):"")+"</span>"+(p.length?" <small>"+e(p.join(", "))+"</small>":"")+(u.length?"<ul>"+u.map(a).join("")+"</ul>":"")+"</li>"};return'<ul class="oe-tree" aria-label="Org chart">'+t.members.filter(c=>!o[c.ref]).map(a).join("")+t.members.filter(c=>!i[c.ref]).map(a).join("")+"</ul>"}function Tc(t,e,n){let r=h=>String(h??"").replace(/[&<>"']/g,S=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[S]),o={"reports-to":"Reports to","dotted-line":"Dotted line to","acts-for":"Acts for"},s={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"},i=(h,S)=>'<option value="'+r(h)+'">'+r(S)+"</option>";if(!t)return'<p class="org-quiet">Loading\u2026</p>';if(!t.canEdit||!t.setup||!t.choices)return"";let a='<p class="oe-msg'+(e.bad?" is-bad":"")+'" role="status">'+r(e.text)+"</p>",d=n?'<div class="oe-confirm" id="oe-confirm" role="group" aria-label="Confirm the change"><p class="oe-confirm-text">'+r(n)+'</p><span class="oe-acts"><button type="button" class="ax-btn ax-btn--primary" id="oe-confirm-save" data-oe="confirm">Save the move</button><button type="button" class="ax-btn" data-oe="cancel">Cancel</button></span></div>':"",l=t.choices,c=t.setup.members,p={};for(let h of c)p[h.ref]=h;let u=h=>p[h]?p[h].name:h.replace(/^(agent|person):/,""),g=h=>h.filter(S=>!p[S.ref]).map(S=>i(S.ref,S.name)).join(""),f=g(l.agents),m=g(l.people),w='<div class="oe-form" role="group" aria-label="Add a member"><label for="oe-add-member">Member <select id="oe-add-member">'+(f||m?(f?'<optgroup label="Agents">'+f+"</optgroup>":"")+(m?'<optgroup label="People">'+m+"</optgroup>":""):'<option value="">Everyone is in the chart</option>')+'</select></label><label for="oe-add-role">Role <input id="oe-add-role" list="oe-roles" maxlength="80" placeholder="Engineer" autocomplete="off"></label><button type="button" class="ax-btn" data-oe="add-member"'+(f||m?"":" disabled")+'>Add</button></div><datalist id="oe-roles">'+l.roles.map(h=>i(h.title,h.key)).join("")+"</datalist>",x=[["mon","Mon","Monday"],["tue","Tue","Tuesday"],["wed","Wed","Wednesday"],["thu","Thu","Thursday"],["fri","Fri","Friday"],["sat","Sat","Saturday"],["sun","Sun","Sunday"]],b=(h,S)=>{if(h.kind!=="agent")return"";let Ye=h.schedule||{start:"",end:"",days:[]};return'<fieldset class="oe-hours"><legend class="org-kind">Working hours of '+r(h.name)+'</legend><label for="oe-start-'+S+'">Start <input type="time" id="oe-start-'+S+'" value="'+r(Ye.start)+'" aria-label="Start time of '+r(h.name)+'"></label><label for="oe-end-'+S+'">End <input type="time" id="oe-end-'+S+'" value="'+r(Ye.end)+'" aria-label="End time of '+r(h.name)+'"></label><span class="oe-days" role="group" aria-label="Working days of '+r(h.name)+'">'+x.map(Se=>'<label class="oe-day"><input type="checkbox" name="oe-days-'+S+'" value="'+Se[0]+'"'+(Ye.days.indexOf(Se[0])>=0?" checked":"")+' aria-label="'+Se[2]+'">'+Se[1]+"</label>").join("")+'</span><button type="button" class="ax-btn" data-oe="set-schedule" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save hours</button></fieldset>'},y=c.length?'<ul class="oe-rows">'+c.map((h,S)=>'<li class="oe-row"><span class="oe-who"><b>'+r(h.name)+'</b><span class="org-kind">'+(h.kind==="person"?"Person":"Agent")+'</span></span><label class="oe-role" for="oe-role-'+S+'"><span class="org-kind">Role</span><input id="oe-role-'+S+'" list="oe-roles" maxlength="80" value="'+r(h.title||"")+'" aria-label="Role of '+r(h.name)+'"></label><span class="oe-acts"><button type="button" class="ax-btn" data-oe="set-role" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save role</button><button type="button" class="ax-btn" data-oe="remove-member" data-oe-member="'+r(h.ref)+'" aria-label="Remove '+r(h.name)+'">Remove</button><a class="ax-btn" href="/hub#page=settings&section=agents&under='+encodeURIComponent(h.ref)+'" aria-label="Add an agent who reports to '+r(h.name)+'">Add agent here</a></span>'+b(h,S)+"</li>").join("")+"</ul>":'<p class="org-quiet">No one in the org chart yet. Add a member above.</p>',k=t.setup.relations,D=k.length?'<ul class="oe-rows">'+k.map(h=>'<li class="oe-row"><span class="oe-who">'+r(u(h.from))+' <span class="org-kind">'+r(s[h.type]||h.type)+"</span> "+r(u(h.to))+'</span><span class="oe-acts"><button type="button" class="ax-btn" data-oe="remove-relation" data-oe-from="'+r(h.from)+'" data-oe-type="'+r(h.type)+'" data-oe-to="'+r(h.to)+'" aria-label="Remove: '+r(u(h.from)+" "+(s[h.type]||h.type)+" "+u(h.to))+'">Remove</button></span></li>').join("")+"</ul>":'<p class="org-quiet">No relations yet.</p>',ae=c.map(h=>i(h.ref,h.name+(h.kind==="person"?" (person)":""))).join(""),ve=c.length>=2?'<div class="oe-form" role="group" aria-label="Add a relation"><label for="oe-rel-from">Member <select id="oe-rel-from">'+ae+'</select></label><label for="oe-rel-type">Relation <select id="oe-rel-type">'+l.types.map(h=>i(h,o[h]||h)).join("")+'</select></label><label for="oe-rel-to">Target <select id="oe-rel-to">'+ae+'</select></label><button type="button" class="ax-btn" data-oe="add-relation">Add relation</button></div>':'<p class="org-quiet">Add two members to link them.</p>';return'<p class="oe-lead">Each change is checked, saved to agentx.json with a backup, and used at once, with no restart. A change to a line, or a removal, asks you first.</p>'+a+d+'<h2 class="org-h2">Add a member</h2>'+w+'<h2 class="org-h2">Members <span class="org-kind">'+c.length+"</span></h2>"+y+'<h2 class="org-h2">Relations <span class="org-kind">'+k.length+"</span></h2>"+D+ve+'<dl class="oe-legend"><dt>Reports to</dt><dd>The line manager, one at most. Work an agent cannot finish goes up this line.</dd><dt>Dotted line to</dt><dd>A second manager for one topic or project.</dd><dt>Acts for</dt><dd>An agent works on behalf of a person.</dd><dt>Working hours</dt><dd>When an agent is on the clock. An empty start or end, or no day ticked, goes back to 09:00 to 17:00, Monday to Friday.</dd></dl>'}function _f(t){let e={msg:"",bad:!1,pending:null,focus:!1},n=i=>{let a=document.getElementById(i);return a?a.value:""};async function r(i,a,d){d&&(d.disabled=!0);let l=0,c={};try{for(;l<i.length;l++)c=await t.post(i[l]);e.msg=(c.summary||"Saved")+". Saved.",e.bad=!1}catch(p){if(e.msg=p.message,e.bad=!0,l>0)try{for(let u of a)await t.post(u);e.msg+=" Nothing was changed."}catch(u){e.msg+=" Putting the old line back failed too: "+u.message+". Check the chart below."}}await t.reload(),t.paint(),d&&(d.disabled=!1)}function o(i,a){let d=t.org(),l=d&&d.setup?Rc(d.setup,i):null;if(!l){r([i],[],a);return}e.pending=l,e.msg="",e.bad=!1,e.focus=!0,t.paint()}function s(){e.pending=null,e.msg="Cancelled. Nothing changed.",e.bad=!1,t.paint()}return{E:e,html:()=>Tc(t.org(),{text:e.msg,bad:e.bad},e.pending?e.pending.text:""),focus(){if(e.focus){let i=document.getElementById("oe-confirm-save");i&&i.focus()}e.focus=!1},click(i){let a=i&&i.closest?i.closest("[data-oe]"):null;if(!a)return!1;let d=a.getAttribute("data-oe")||"",l=c=>a.getAttribute("data-oe-"+c)||"";if(d==="confirm"){let c=e.pending;if(!c)return!0;e.pending=null,r(c.steps,c.undo,a)}else if(d==="cancel")s();else if(d==="add-member")n("oe-add-member")&&r([{op:d,member:n("oe-add-member"),role:n("oe-add-role")}],[],a);else if(d==="set-role")r([{op:d,member:l("member"),role:n("oe-role-"+l("i"))}],[],a);else if(d==="set-schedule"){let c=[];document.querySelectorAll('input[name="oe-days-'+l("i")+'"]').forEach(p=>{p.checked&&c.push(p.value)}),r([{op:d,member:l("member"),start:n("oe-start-"+l("i")),end:n("oe-end-"+l("i")),days:c}],[],a)}else d==="add-relation"?o({op:d,from:n("oe-rel-from"),type:n("oe-rel-type"),to:n("oe-rel-to")},a):d==="remove-member"?o({op:d,member:l("member")},a):d==="remove-relation"&&o({op:d,from:l("from"),type:l("type"),to:l("to")},a);return!0},key(i){i.key==="Escape"&&e.pending&&(i.preventDefault(),s())}}}var Rf=`
|
|
580
520
|
.oe-tree, .oe-tree ul { list-style: none; margin: 0; padding: 0; font-size: var(--ax-fs-sm); }
|
|
581
521
|
.oe-tree ul { margin-left: 10px; padding-left: 12px; border-left: var(--ax-border-w) solid var(--ax-border-2); }
|
|
582
522
|
.oe-tree li { padding: 3px 0; }
|
|
@@ -609,7 +549,7 @@ ${e}`;r-(this.written.get(o)??-1/0)<this.throttleMs||(this.written.set(o,r),this
|
|
|
609
549
|
.oe-form > *, .oe-role { flex: 1 1 100%; }
|
|
610
550
|
.oe-legend { grid-template-columns: 1fr; }
|
|
611
551
|
}
|
|
612
|
-
`;et();function Qt(t){let e=n=>[...new Set((n??[]).filter(Boolean).map(E))];return Object.entries(t?.departments??{}).map(([n,r])=>{let o=e(r?.alsoMembers);return{id:n,name:r?.name?.trim()||n,...r?.head?{head:E(r.head)}:{},members:e(r?.members),...o.length?{alsoMembers:o}:{}}}).sort((n,r)=>n.name.localeCompare(r.name)||n.id.localeCompare(r.id))}function ks(t,e,n,r=new Set,o=new Map){let s=l=>{let c=C(l);return c.kind==="person"?o.get(c.id):void 0},i=l=>`${l.name} is a ${l.role}, and only owners and members of the organisation can be in a department`,a=new Map;for(let l of t){let c=l.head&&Ee(l.head,`Department ${l.name} is headed by`,e,n,r);if(c)return c;let p=l.head?s(l.head):void 0;if(p)return`Department ${l.name} cannot be headed by ${p.name}: ${i(p)}`;for(let u of l.members){let g=Ee(u,`Department ${l.name} lists`,e,n,r);if(g)return g;let m=s(u);if(m)return`Department ${l.name} cannot list ${m.name}: ${i(m)}`;let f=a.get(u);if(f)return`"${u}" is in both department ${f} and ${l.name}; a member is in one department`;a.set(u,l.name)}}let d=vs(t);for(let l of t)for(let c of l.alsoMembers??[]){let p=Ee(c,`Department ${l.name} also lists`,e,n,r);if(p)return p;let u=s(c);if(u)return`Department ${l.name} cannot also list ${u.name}: ${i(u)}`;let g=d.get(c);if(g===l.id)return`"${c}" is a member of department ${l.name} already; alsoMembers is for members whose home is another department`;if(c===l.head)return`"${c}" heads department ${l.name} already; alsoMembers is for members whose home is another department`;if(!g)return`"${c}" is in alsoMembers of department ${l.name} but has no home; list them in the members of one department first`}}function vs(t){let e=new Map;for(let n of t)for(let r of n.members)e.has(r)||e.set(r,n.id);for(let n of t)n.head&&!e.has(n.head)&&e.set(n.head,n.id);return e}function Bm(t,e){let n=new Set,r=vs(t),o=new Map(t.map(i=>[i.id,i.name]));return{boxes:t.map(i=>{i.head&&n.add(i.head);for(let d of i.members)n.add(d);let a=(i.alsoMembers??[]).flatMap(d=>{let l=r.get(d);return l&&l!==i.id&&d!==i.head?[{key:d,home:o.get(l)}]:[]});return{id:i.id,name:i.name,...i.head?{head:i.head}:{},members:i.members.filter(d=>d!==i.head),...a.length?{also:a}:{}}}),rest:[...new Set(e)].filter(i=>!n.has(i))}}et();var Ss=80,be={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},Ke=["mon","tue","wed","thu","fri","sat","sun"],Zt={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function Mc(t){let e=(a,d,l)=>{let c=String(a??"").trim();if(!c)return l;if(!/^([01]\d|2[0-3]):[0-5]\d$/.test(c))throw new Error(`The ${d} time "${c}" is not a time. Write it as HH:MM, for example 09:00.`);return c},n=e(t.start,"start",be.start),r=e(t.end,"end",be.end);if(r<=n)throw new Error(`The end time (${r}) must be after the start time (${n}).`);if(t.days!=null&&!Array.isArray(t.days))throw new Error("Pick the working days from Monday to Sunday.");let o=(t.days??[]).map(a=>String(a).trim().toLowerCase()),s=o.find(a=>!Ke.includes(a));if(s)throw new Error(`"${s}" is not a day. Use mon, tue, wed, thu, fri, sat or sun.`);let i=o.length?Ke.filter(a=>o.includes(a)):[...be.days];return{start:n,end:r,days:i}}function Fc(t){let e=Ke.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>Ke.indexOf(r)===e+o))return`${Zt[t[0]]} to ${Zt[t[t.length-1]]}`;let n=t.map(r=>Zt[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var en={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function tn(t){let e=Array.isArray(t?.people)?t.people:[],n=new Map;for(let r of e)r?.id&&n.set(String(r.id),String(r.name||r.id));return n}function As(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function Uc(t){let e=t?.business?.roles??{};return{agents:[...As(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...tn(t)].map(([n,r])=>({ref:`person:${n}`,name:r})),roles:Object.entries(e).map(([n,r])=>({key:n,title:String(r?.title||n)})),types:Ze}}function Wc(t){let e=t?.business??{},n=e.roles??{},r=As(t),o=tn(t),s=le(e),i=(c,p,u,g)=>({ref:`${c}:${p}`,kind:c,id:p,name:(c==="agent"?r.get(p):o.get(p))??p,...u?{role:u,title:String(n[u]?.title||u)}:{},...g&&typeof g=="object"?{schedule:{start:String(g.start??""),end:String(g.end??""),days:Array.isArray(g.days)?g.days.map(String):[...be.days]}}:{}}),a=[...Object.entries(e.orgChart??{}).map(([c,p])=>i("agent",c,p?.role,p?.schedule)),...Object.entries(e.orgPeople??{}).map(([c,p])=>i("person",c,p?.role))],d=new Set(a.map(c=>c.ref)),l=[...s.flatMap(c=>[c.from,c.to]),...Qt(e).flatMap(c=>[...c.head?[c.head]:[],...c.members])];for(let c of l){let p=C(c);p.kind==="person"&&!d.has(c)&&(d.add(c),a.push(i("person",p.id,void 0)))}return{members:a,relations:s}}function Es(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(tn(t).keys()),o=_n(t),s=Array.isArray(t?.people)?t.people:[],i=new Map(s.flatMap(a=>a?.id&&(a.role==="client"||a.role==="guest")?[[String(a.id),{name:String(a.name||a.id),role:a.role}]]:[]));return En(le(e),n,r,o)??ks(Qt(e),n,r,o,i)}function jc(t,e){let n=[];for(let[r,o]of Object.entries(t.departments??{})){let s=!1;if(o?.head&&E(o.head)===e&&(delete o.head,s=!0),Array.isArray(o?.members)){let i=o.members.filter(a=>E(a)!==e);i.length!==o.members.length&&(o.members=i,s=!0)}if(Array.isArray(o?.alsoMembers)){let i=o.alsoMembers.filter(a=>E(a)!==e);i.length!==o.alsoMembers.length&&(o.alsoMembers=i,s=!0)}s&&n.push(String(o?.name||r))}return n}function _s(t,e){let n=t.business.roles=t.business.roles||{};if(n[e])return e;let r=e.toLowerCase(),o=Object.entries(n).find(([,a])=>String(a?.title||"").toLowerCase()===r);if(o)return o[0];let s=r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"role",i=s;for(let a=2;n[i];a++)i=`${s}-${a}`;return n[i]={title:e},i}function $s(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>Ss)throw new Error(`Keep the role under ${Ss} characters.`);return e}function Bc(t,e,n){let r=new Set;for(let o=e;o&&!r.has(o);o=t.find(s=>s.type==="reports-to"&&s.from===o)?.to){if(o===n)return!0;r.add(o)}return!1}function Ts(t,e){let n=0;for(let[o,s]of Object.entries(t.orgChart??{}))s?.reportsTo&&e({from:`agent:${o}`,to:E(s.reportsTo),type:"reports-to"})&&(delete s.reportsTo,n++);let r=(t.relations??[]).length;return t.relations=(t.relations??[]).filter(o=>!e({from:E(o.from),to:E(o.to),type:o.type})),n+=r-t.relations.length,t.relations.length===0&&delete t.relations,n}function Xm(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=Es(n),s=Wc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=Uc(n),d=new Map([...a.agents,...a.people].map(u=>[u.ref,u.name])),l=u=>i.get(u)?.name??d.get(u)??C(u).id,c;switch(e?.op){case"add-member":{let u=/^(agent|person):[^\s:]+$/.test(String(e.member??"").trim())?E(String(e.member).trim()):"";if(!u)throw new Error("Pick an agent or a person to add.");let{kind:g,id:m}=C(u),f=d.get(u);if(!f)throw new Error(g==="agent"?`There is no agent "${m}" on this computer.`:`There is no person "${m}" in your people list. Add them on the People page first.`);if(i.has(u))throw new Error(`${f} is already in the org chart.`);let w=$s(e.role);if(g==="agent"&&!w)throw new Error(`Give ${f} a role.`);let x=w?_s(n,w):void 0;g==="agent"?(r.orgChart=r.orgChart||{},r.orgChart[m]={role:x,schedule:{...be},utilizationTarget:.8}):(r.orgPeople=r.orgPeople||{},r.orgPeople[m]=x?{role:x}:{}),c=`${f} added to the org chart`;break}case"set-role":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=$s(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let m=g?_s(n,g):void 0;u.kind==="agent"?r.orgChart[u.id].role=m:(r.orgPeople=r.orgPeople||{},r.orgPeople[u.id]=m?{role:m}:{}),c=m?`${u.name} is now ${r.roles[m]?.title||g}`:`${u.name} has no role now`;break}case"remove-member":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=u.kind==="agent"?(r.projects??[]).find(w=>w?.pm===u.id):void 0;if(g)throw new Error(`${u.name} is the project manager of "${g.id}". Give that project another manager first.`);let m=Ts(r,w=>w.from===u.ref||w.to===u.ref),f=jc(r,u.ref);u.kind==="agent"?delete r.orgChart[u.id]:r.orgPeople&&(delete r.orgPeople[u.id],Object.keys(r.orgPeople).length===0&&delete r.orgPeople),c=`${u.name} removed from the org chart`+(m?`, with ${m} ${m===1?"line":"lines"}`:"")+(f.length?` and out of ${f.join(", ")}`:"");break}case"add-relation":{let u=String(e.type??"").trim(),g=[String(e.from??"").trim(),String(e.to??"").trim()];if(!g[0]||!g[1]||!u)throw new Error("Pick a member, a kind of relation and a target.");if(!Ze.includes(u))throw new Error(`"${u}" is not a kind of relation. Pick reports to, dotted line or acts for.`);let[m,f]=g.map(E);for(let x of[m,f])if(!i.has(x))throw new Error(`${l(x)} is not in the org chart. Add them first.`);if(m===f)throw new Error(`${l(m)} cannot be linked to themself.`);let w={from:m,to:f,type:u};if(s.relations.some(x=>x.from===m&&x.to===f&&x.type===u))throw new Error(`${l(m)} already ${en[u]} ${l(f)}.`);if(u==="acts-for"&&i.get(m).kind!=="agent")throw new Error(`Only an agent can act for someone: ${l(m)} is a person.`);if(u==="acts-for"&&i.get(f).kind!=="person")throw new Error(`An agent acts for a person: ${l(f)} is an agent.`);if(u==="reports-to"){let x=s.relations.find(b=>b.type==="reports-to"&&b.from===m);if(x)throw new Error(`${l(m)} already reports to ${l(x.to)}. Remove that line first: each member has one boss.`);if(Bc(s.relations,f,m))throw new Error(`${l(m)} cannot report to ${l(f)}: ${l(f)} already reports up to ${l(m)}.`)}if(u==="reports-to"&&i.get(m).kind==="agent"){let x=C(f);r.orgChart[C(m).id].reportsTo=x.kind==="agent"?x.id:f}else r.relations=[...r.relations??[],w];c=`${l(m)} ${en[u]} ${l(f)}`;break}case"remove-relation":{let u={from:E(String(e.from??"")),to:E(String(e.to??"")),type:String(e.type??"")};if(!Ts(r,g=>g.from===u.from&&g.to===u.to&&g.type===u.type))throw new Error("That line is not in the org chart any more. Reload the page.");c=`${l(u.from)} no longer ${en[u.type]??u.type} ${l(u.to)}`;break}case"set-schedule":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);if(u.kind!=="agent")throw new Error(`Working hours are for agents: ${u.name} is a person.`);let g=Mc(e),m=r.orgChart[u.id];m.schedule={...m.schedule??{},...g},c=`${u.name} works ${Fc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=Es(n);if(p&&p!==o)throw new Error(p);for(let u of Object.keys(t))delete t[u];return Object.assign(t,n),c}var Hc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},Rs=class{constructor(e=Hc,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(o=>r-o<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},qc="That code didn't work. Check it, or run agentx app pair for a new one.",Vc=400;async function Gm(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),o=t.socket.remoteAddress||"unknown",s=e.limiter.retryAfter(o);if(s>0)return r(`[app] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let i=null;try{i=(await $r(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await Xc(n,e.minMs??Vc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:qc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function Xc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as cd}from"child_process";import{mkdtempSync as nd,rmSync as rd,writeFileSync as od}from"fs";import{tmpdir as sd}from"os";import{join as Os}from"path";import{randomBytes as zc}from"crypto";function R(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var B={top:8,side:32,bottom:60},nn={height:56,keep:52},Is=`
|
|
552
|
+
`;Ze();function Jt(t){let e=n=>[...new Set((n??[]).filter(Boolean).map($))];return Object.entries(t?.departments??{}).map(([n,r])=>{let o=e(r?.alsoMembers);return{id:n,name:r?.name?.trim()||n,...r?.head?{head:$(r.head)}:{},members:e(r?.members),...o.length?{alsoMembers:o}:{}}}).sort((n,r)=>n.name.localeCompare(r.name)||n.id.localeCompare(r.id))}function ms(t,e,n,r=new Set,o=new Map){let s=l=>{let c=C(l);return c.kind==="person"?o.get(c.id):void 0},i=l=>`${l.name} is a ${l.role}, and only owners and members of the organisation can be in a department`,a=new Map;for(let l of t){let c=l.head&&$e(l.head,`Department ${l.name} is headed by`,e,n,r);if(c)return c;let p=l.head?s(l.head):void 0;if(p)return`Department ${l.name} cannot be headed by ${p.name}: ${i(p)}`;for(let u of l.members){let g=$e(u,`Department ${l.name} lists`,e,n,r);if(g)return g;let f=s(u);if(f)return`Department ${l.name} cannot list ${f.name}: ${i(f)}`;let m=a.get(u);if(m)return`"${u}" is in both department ${m} and ${l.name}; a member is in one department`;a.set(u,l.name)}}let d=hs(t);for(let l of t)for(let c of l.alsoMembers??[]){let p=$e(c,`Department ${l.name} also lists`,e,n,r);if(p)return p;let u=s(c);if(u)return`Department ${l.name} cannot also list ${u.name}: ${i(u)}`;let g=d.get(c);if(g===l.id)return`"${c}" is a member of department ${l.name} already; alsoMembers is for members whose home is another department`;if(c===l.head)return`"${c}" heads department ${l.name} already; alsoMembers is for members whose home is another department`;if(!g)return`"${c}" is in alsoMembers of department ${l.name} but has no home; list them in the members of one department first`}}function hs(t){let e=new Map;for(let n of t)for(let r of n.members)e.has(r)||e.set(r,n.id);for(let n of t)n.head&&!e.has(n.head)&&e.set(n.head,n.id);return e}function Df(t,e){let n=new Set,r=hs(t),o=new Map(t.map(i=>[i.id,i.name]));return{boxes:t.map(i=>{i.head&&n.add(i.head);for(let d of i.members)n.add(d);let a=(i.alsoMembers??[]).flatMap(d=>{let l=r.get(d);return l&&l!==i.id&&d!==i.head?[{key:d,home:o.get(l)}]:[]});return{id:i.id,name:i.name,...i.head?{head:i.head}:{},members:i.members.filter(d=>d!==i.head),...a.length?{also:a}:{}}}),rest:[...new Set(e)].filter(i=>!n.has(i))}}Ze();var bs=80,be={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},Xe=["mon","tue","wed","thu","fri","sat","sun"],Yt={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function Ic(t){let e=(a,d,l)=>{let c=String(a??"").trim();if(!c)return l;if(!/^([01]\d|2[0-3]):[0-5]\d$/.test(c))throw new Error(`The ${d} time "${c}" is not a time. Write it as HH:MM, for example 09:00.`);return c},n=e(t.start,"start",be.start),r=e(t.end,"end",be.end);if(r<=n)throw new Error(`The end time (${r}) must be after the start time (${n}).`);if(t.days!=null&&!Array.isArray(t.days))throw new Error("Pick the working days from Monday to Sunday.");let o=(t.days??[]).map(a=>String(a).trim().toLowerCase()),s=o.find(a=>!Xe.includes(a));if(s)throw new Error(`"${s}" is not a day. Use mon, tue, wed, thu, fri, sat or sun.`);let i=o.length?Xe.filter(a=>o.includes(a)):[...be.days];return{start:n,end:r,days:i}}function Dc(t){let e=Xe.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>Xe.indexOf(r)===e+o))return`${Yt[t[0]]} to ${Yt[t[t.length-1]]}`;let n=t.map(r=>Yt[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var Qt={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function Zt(t){let e=Array.isArray(t?.people)?t.people:[],n=new Map;for(let r of e)r?.id&&n.set(String(r.id),String(r.name||r.id));return n}function vs(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function Cc(t){let e=t?.business?.roles??{};return{agents:[...vs(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...Zt(t)].map(([n,r])=>({ref:`person:${n}`,name:r})),roles:Object.entries(e).map(([n,r])=>({key:n,title:String(r?.title||n)})),types:Qe}}function Oc(t){let e=t?.business??{},n=e.roles??{},r=vs(t),o=Zt(t),s=le(e),i=(c,p,u,g)=>({ref:`${c}:${p}`,kind:c,id:p,name:(c==="agent"?r.get(p):o.get(p))??p,...u?{role:u,title:String(n[u]?.title||u)}:{},...g&&typeof g=="object"?{schedule:{start:String(g.start??""),end:String(g.end??""),days:Array.isArray(g.days)?g.days.map(String):[...be.days]}}:{}}),a=[...Object.entries(e.orgChart??{}).map(([c,p])=>i("agent",c,p?.role,p?.schedule)),...Object.entries(e.orgPeople??{}).map(([c,p])=>i("person",c,p?.role))],d=new Set(a.map(c=>c.ref)),l=[...s.flatMap(c=>[c.from,c.to]),...Jt(e).flatMap(c=>[...c.head?[c.head]:[],...c.members])];for(let c of l){let p=C(c);p.kind==="person"&&!d.has(c)&&(d.add(c),a.push(i("person",p.id,void 0)))}return{members:a,relations:s}}function ys(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(Zt(t).keys()),o=Sn(t),s=Array.isArray(t?.people)?t.people:[],i=new Map(s.flatMap(a=>a?.id&&(a.role==="client"||a.role==="guest")?[[String(a.id),{name:String(a.name||a.id),role:a.role}]]:[]));return vn(le(e),n,r,o)??ms(Jt(e),n,r,o,i)}function Nc(t,e){let n=[];for(let[r,o]of Object.entries(t.departments??{})){let s=!1;if(o?.head&&$(o.head)===e&&(delete o.head,s=!0),Array.isArray(o?.members)){let i=o.members.filter(a=>$(a)!==e);i.length!==o.members.length&&(o.members=i,s=!0)}if(Array.isArray(o?.alsoMembers)){let i=o.alsoMembers.filter(a=>$(a)!==e);i.length!==o.alsoMembers.length&&(o.alsoMembers=i,s=!0)}s&&n.push(String(o?.name||r))}return n}function ws(t,e){let n=t.business.roles=t.business.roles||{};if(n[e])return e;let r=e.toLowerCase(),o=Object.entries(n).find(([,a])=>String(a?.title||"").toLowerCase()===r);if(o)return o[0];let s=r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"role",i=s;for(let a=2;n[i];a++)i=`${s}-${a}`;return n[i]={title:e},i}function xs(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>bs)throw new Error(`Keep the role under ${bs} characters.`);return e}function Lc(t,e,n){let r=new Set;for(let o=e;o&&!r.has(o);o=t.find(s=>s.type==="reports-to"&&s.from===o)?.to){if(o===n)return!0;r.add(o)}return!1}function ks(t,e){let n=0;for(let[o,s]of Object.entries(t.orgChart??{}))s?.reportsTo&&e({from:`agent:${o}`,to:$(s.reportsTo),type:"reports-to"})&&(delete s.reportsTo,n++);let r=(t.relations??[]).length;return t.relations=(t.relations??[]).filter(o=>!e({from:$(o.from),to:$(o.to),type:o.type})),n+=r-t.relations.length,t.relations.length===0&&delete t.relations,n}function Lf(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=ys(n),s=Oc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=Cc(n),d=new Map([...a.agents,...a.people].map(u=>[u.ref,u.name])),l=u=>i.get(u)?.name??d.get(u)??C(u).id,c;switch(e?.op){case"add-member":{let u=/^(agent|person):[^\s:]+$/.test(String(e.member??"").trim())?$(String(e.member).trim()):"";if(!u)throw new Error("Pick an agent or a person to add.");let{kind:g,id:f}=C(u),m=d.get(u);if(!m)throw new Error(g==="agent"?`There is no agent "${f}" on this computer.`:`There is no person "${f}" in your people list. Add them on the People page first.`);if(i.has(u))throw new Error(`${m} is already in the org chart.`);let w=xs(e.role);if(g==="agent"&&!w)throw new Error(`Give ${m} a role.`);let x=w?ws(n,w):void 0;g==="agent"?(r.orgChart=r.orgChart||{},r.orgChart[f]={role:x,schedule:{...be},utilizationTarget:.8}):(r.orgPeople=r.orgPeople||{},r.orgPeople[f]=x?{role:x}:{}),c=`${m} added to the org chart`;break}case"set-role":{let u=i.get($(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=xs(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let f=g?ws(n,g):void 0;u.kind==="agent"?r.orgChart[u.id].role=f:(r.orgPeople=r.orgPeople||{},r.orgPeople[u.id]=f?{role:f}:{}),c=f?`${u.name} is now ${r.roles[f]?.title||g}`:`${u.name} has no role now`;break}case"remove-member":{let u=i.get($(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=u.kind==="agent"?(r.projects??[]).find(w=>w?.pm===u.id):void 0;if(g)throw new Error(`${u.name} is the project manager of "${g.id}". Give that project another manager first.`);let f=ks(r,w=>w.from===u.ref||w.to===u.ref),m=Nc(r,u.ref);u.kind==="agent"?delete r.orgChart[u.id]:r.orgPeople&&(delete r.orgPeople[u.id],Object.keys(r.orgPeople).length===0&&delete r.orgPeople),c=`${u.name} removed from the org chart`+(f?`, with ${f} ${f===1?"line":"lines"}`:"")+(m.length?` and out of ${m.join(", ")}`:"");break}case"add-relation":{let u=String(e.type??"").trim(),g=[String(e.from??"").trim(),String(e.to??"").trim()];if(!g[0]||!g[1]||!u)throw new Error("Pick a member, a kind of relation and a target.");if(!Qe.includes(u))throw new Error(`"${u}" is not a kind of relation. Pick reports to, dotted line or acts for.`);let[f,m]=g.map($);for(let x of[f,m])if(!i.has(x))throw new Error(`${l(x)} is not in the org chart. Add them first.`);if(f===m)throw new Error(`${l(f)} cannot be linked to themself.`);let w={from:f,to:m,type:u};if(s.relations.some(x=>x.from===f&&x.to===m&&x.type===u))throw new Error(`${l(f)} already ${Qt[u]} ${l(m)}.`);if(u==="acts-for"&&i.get(f).kind!=="agent")throw new Error(`Only an agent can act for someone: ${l(f)} is a person.`);if(u==="acts-for"&&i.get(m).kind!=="person")throw new Error(`An agent acts for a person: ${l(m)} is an agent.`);if(u==="reports-to"){let x=s.relations.find(b=>b.type==="reports-to"&&b.from===f);if(x)throw new Error(`${l(f)} already reports to ${l(x.to)}. Remove that line first: each member has one boss.`);if(Lc(s.relations,m,f))throw new Error(`${l(f)} cannot report to ${l(m)}: ${l(m)} already reports up to ${l(f)}.`)}if(u==="reports-to"&&i.get(f).kind==="agent"){let x=C(m);r.orgChart[C(f).id].reportsTo=x.kind==="agent"?x.id:m}else r.relations=[...r.relations??[],w];c=`${l(f)} ${Qt[u]} ${l(m)}`;break}case"remove-relation":{let u={from:$(String(e.from??"")),to:$(String(e.to??"")),type:String(e.type??"")};if(!ks(r,g=>g.from===u.from&&g.to===u.to&&g.type===u.type))throw new Error("That line is not in the org chart any more. Reload the page.");c=`${l(u.from)} no longer ${Qt[u.type]??u.type} ${l(u.to)}`;break}case"set-schedule":{let u=i.get($(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);if(u.kind!=="agent")throw new Error(`Working hours are for agents: ${u.name} is a person.`);let g=Ic(e),f=r.orgChart[u.id];f.schedule={...f.schedule??{},...g},c=`${u.name} works ${Dc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=ys(n);if(p&&p!==o)throw new Error(p);for(let u of Object.keys(t))delete t[u];return Object.assign(t,n),c}var Pc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},Ss=class{constructor(e=Pc,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(o=>r-o<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},Mc="That code didn't work. Check it, or run agentx app pair for a new one.",Fc=400;async function Ff(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),o=t.socket.remoteAddress||"unknown",s=e.limiter.retryAfter(o);if(s>0)return r(`[app] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let i=null;try{i=(await vr(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await Wc(n,e.minMs??Fc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Mc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function Wc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as nd}from"child_process";import{mkdtempSync as Gc,rmSync as Jc,writeFileSync as Yc}from"fs";import{tmpdir as Qc}from"os";import{join as Rs}from"path";import{randomBytes as Uc}from"crypto";function T(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var B={top:8,side:32,bottom:60},en={height:56,keep:52},$s=`
|
|
613
553
|
:root {
|
|
614
554
|
--ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
|
|
615
555
|
--ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
|
|
@@ -738,33 +678,33 @@ button.primary:hover:not(:disabled) { transform: translateY(-1px); background: v
|
|
|
738
678
|
button.primary:disabled { opacity: .55; cursor: not-allowed; }
|
|
739
679
|
kbd { font: 11px var(--ac-mono); color: var(--ac-subtle); }
|
|
740
680
|
button.primary kbd { color: inherit; opacity: .7; }
|
|
741
|
-
`;var
|
|
681
|
+
`;var Es=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),As=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function jc(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Es(n):As(n)}`}function Bc(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[As(n)],Es(n)].join(" ")}function Hc(t){let e=t.trim().split(/[\s_-]+/).filter(Boolean);return(e.length>1?e[0][0]+e[1][0]:t.trim().slice(0,1)).toUpperCase()}function Vc(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var tn=t=>`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${t}</svg>`,qc=tn('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),zc=tn('<path d="m6 15 6-6 6 6"/>'),Xc=tn('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function _s(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=Uc(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",d=Wn(t),l=s.map((u,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${T(u)}</span>${g===d.index?'<i class="dot"></i>':""}</button>`).join(""),c=t.recommend?`<span class="rec"><i class="dot"></i>${T(r)} recommends</span>`:"",p={choices:s,draft:t.draft??"",placeholder:Mn,chime:e.sound==="chime",volume:Math.min(1,Math.max(0,e.volume??.4)),theme:e.theme??"system",pick:e.pick&&e.pick<=s.length?e.pick-1:d.index};return`<!doctype html>
|
|
742
682
|
<html lang="en"><head><meta charset="utf-8">
|
|
743
683
|
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${o}'">
|
|
744
684
|
<title>AgentX</title>
|
|
745
|
-
<style>${
|
|
685
|
+
<style>${$s}</style></head>
|
|
746
686
|
<body><div class="wrap"><main class="card${e.still?" still":""}">
|
|
747
|
-
<div class="head" title="Drag to move"><span class="avatar">${
|
|
748
|
-
<div class="who"><b>${
|
|
687
|
+
<div class="head" title="Drag to move"><span class="avatar">${T(Hc(r))}</span>
|
|
688
|
+
<div class="who"><b>${T(r)}</b><span>${T(jc(t.created_at,n))}</span></div>
|
|
749
689
|
<span class="kind${i?"":" decision"}">${i?"Reminder":a?"Request":"Decision"}</span>
|
|
750
|
-
<button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${
|
|
751
|
-
<div class="body"><h1 dir="auto">${
|
|
752
|
-
${t.context?`<p class="context" dir="auto">${
|
|
753
|
-
<p class="ask" dir="auto">${
|
|
690
|
+
<button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${zc}</button></div>
|
|
691
|
+
<div class="body"><h1 dir="auto">${T(t.title)}</h1>
|
|
692
|
+
${t.context?`<p class="context" dir="auto">${T(t.context)}</p>`:""}
|
|
693
|
+
<p class="ask" dir="auto">${T(t.ask)}</p>
|
|
754
694
|
${l||c?`<div class="label-row">${l?'<span class="label">Pick one</span>':""}${c}</div>`:""}
|
|
755
695
|
${l?`<div class="options" role="radiogroup">${l}</div>`:""}
|
|
756
|
-
${d.why?`<p class="why" dir="auto">${
|
|
696
|
+
${d.why?`<p class="why" dir="auto">${T(d.why)}</p>`:""}
|
|
757
697
|
${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><span class="edited"><i class="dot"></i>Edited</span><button class="reset" id="reset">Reset</button></div>
|
|
758
698
|
<textarea id="text" dir="auto" rows="2" spellcheck="true"></textarea>`:""}
|
|
759
|
-
<div class="notes"><div>${
|
|
760
|
-
<div>${
|
|
699
|
+
<div class="notes"><div>${qc}<span>${a?`It stays on the ${_e} until you close it.`:`If you don't answer by ${T(Bc(t.expires,n))}: ${T(t.if_silent)}.`}</span></div>
|
|
700
|
+
<div>${Xc}<span>Nothing goes out until you click.</span></div></div>
|
|
761
701
|
</div><div class="foot"><button class="btn later" id="later">Not now<kbd>esc</kbd></button>
|
|
762
702
|
<button class="btn" id="no">${a?"Drop":"No"}</button>
|
|
763
|
-
<button class="btn primary" id="yes">${
|
|
703
|
+
<button class="btn primary" id="yes">${Vc(t)}<kbd>\u2318\u21A9</kbd></button></div>
|
|
764
704
|
</main></div>
|
|
765
705
|
<script type="application/json" id="data">${JSON.stringify(p).replace(/</g,"\\u003c")}</script>
|
|
766
|
-
<script nonce="${o}">${
|
|
767
|
-
</body></html>`}var
|
|
706
|
+
<script nonce="${o}">${Kc}</script>
|
|
707
|
+
</body></html>`}var Kc=`
|
|
768
708
|
(function () {
|
|
769
709
|
var d = JSON.parse(document.getElementById("data").textContent);
|
|
770
710
|
var root = document.documentElement;
|
|
@@ -853,10 +793,10 @@ ${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><sp
|
|
|
853
793
|
});
|
|
854
794
|
} catch (e) {}
|
|
855
795
|
})();
|
|
856
|
-
`;var
|
|
796
|
+
`;var Zc=440,ed=`
|
|
857
797
|
ObjC.import("Cocoa"); ObjC.import("WebKit")
|
|
858
798
|
function run(argv) {
|
|
859
|
-
var path = argv[0], side = ${B.side}, gripTop = ${B.top}, gripEnd = ${B.top+
|
|
799
|
+
var path = argv[0], side = ${B.side}, gripTop = ${B.top}, gripEnd = ${B.top+en.height}, keep = ${en.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
|
|
860
800
|
var app = $.NSApplication.sharedApplication
|
|
861
801
|
app.setActivationPolicy($.NSApplicationActivationPolicyAccessory)
|
|
862
802
|
ObjC.registerSubclass({ name: "AgentXCardView", superclass: "WKWebView", methods: {
|
|
@@ -928,29 +868,29 @@ function run(argv) {
|
|
|
928
868
|
}
|
|
929
869
|
function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
|
|
930
870
|
function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
|
|
931
|
-
`;function
|
|
932
|
-
`).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&
|
|
933
|
-
`).trim():"",!i||i.length>
|
|
934
|
-
`),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function
|
|
935
|
-
`);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function
|
|
871
|
+
`;function td(t,e){let n=t.trim().split(`
|
|
872
|
+
`).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&Is.includes(r.why))return{action:"dismiss",why:r.why};if(r?.action!=="yes")return{action:"dismiss"};let o=e.choices??[],s;if(o.length){if(typeof r.choice!="string"||!o.includes(r.choice))return{action:"dismiss"};s=r.choice}let i;return e.draft&&(i=typeof r.text=="string"?r.text.replace(/\r\n?/g,`
|
|
873
|
+
`).trim():"",!i||i.length>Pn.text)?{action:"dismiss"}:{action:"yes",...s?{choice:s}:{},...i?{text:i}:{}}}async function Ts(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=Gc(Rs(Qc(),"agentx-card-"));try{let s=Rs(o,"card.html");Yc(s,_s(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",ed,s,String(Zc),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?td(a.stdout,t):null}finally{Jc(o,{recursive:!0,force:!0})}}var Is=["not now","timed out","closed"],rd=(t,e,n)=>new Promise(r=>{try{nd(t,e,{timeout:n},(o,s)=>r({ok:!o,stdout:String(s??"")}))}catch{r({ok:!1,stdout:""})}}),Ds=160,nn=15e3;function Cs(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Ds?e.slice(0,Ds):e}async function od(t,e,n,r,o){let s=e.sound==="chime"?r?"":"Glass":e.sound,i=s?kr(s):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],nn),!!e.speak)if(o){let a;await Promise.race([o(Cs(t)),new Promise(d=>{a=setTimeout(d,nn)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Cs(t)],nn)}}function Ls(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function sd(t,e,n){return Ls(["on run argv","set opts to items 3 thru -1 of argv",'set pick to choose from list opts with title (item 1 of argv) with prompt (item 2 of argv) OK button name "Next" cancel button name "Not now"','if pick is false then return ""',"return item 1 of pick","end run"],[t,e,...n])}function Os(t,e,n,r,o){return Ls(["on run argv","set AppleScript's text item delimiters to linefeed","set btns to text items of (item 3 of argv)","set secs to (item 5 of argv) as integer","if (count of argv) > 5 then","set r to display dialog (item 2 of argv) with title (item 1 of argv) default answer (item 6 of argv) buttons btns default button (item 4 of argv) giving up after secs","else","set r to display dialog (item 2 of argv) with title (item 1 of argv) buttons btns default button (item 4 of argv) giving up after secs","end if",'if gave up of r then return ""',"if (count of argv) > 5 then return (button returned of r) & linefeed & (text returned of r)","return button returned of r","end run"],[t,e,n.join(`
|
|
874
|
+
`),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function Ns(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
|
|
875
|
+
`);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function rn(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
|
|
936
876
|
|
|
937
|
-
`)}async function
|
|
877
|
+
`)}async function Ps(t,e,n={}){let r=n.run??rd,o=(e.style??"card")==="card",s=od(t,e,r,o,n.speak).catch(()=>{});if(o){let i=await Ts(t,{timeoutSeconds:e.timeoutSeconds,sound:e.sound,volume:e.volume,theme:e.theme,from:n.from,capture:n.capture,pick:n.pick},r).catch(()=>null);if(i)return i}return await s,id(t,e,r)}async function id(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=(r+5)*1e3,s=`${t.raised_by}: ${t.title}`,i;if(t.choices?.length){let l=await n("/usr/bin/osascript",sd(s,rn(t),t.choices),o);if(i=l.stdout.replace(/\n$/,""),!l.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let l=i?`${i}
|
|
938
878
|
|
|
939
|
-
Message (edit it if you like):`:`${
|
|
879
|
+
Message (edit it if you like):`:`${rn(t)}
|
|
940
880
|
|
|
941
|
-
Message (edit it if you like):`,p=await n("/usr/bin/osascript",
|
|
942
|
-
Answer it on the Desk.`}}import{closeSync as ye,createReadStream as
|
|
943
|
-
`)[0]}); Siri voices will not switch`),null}}var
|
|
944
|
-
`).pop()?.slice(0,160)??""}`))})})}An();
|
|
945
|
-
`)[0].slice(0,200);d.push(`${l}: ${p}`),i.log(`[voice] phone transcription with ${l} failed: ${p}`)}return[502,{error:"Speech to text failed on this computer.",detail:d.join("; ")}]}function
|
|
946
|
-
`)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function
|
|
881
|
+
Message (edit it if you like):`,p=await n("/usr/bin/osascript",Os(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,Fn(t.draft,i)),o),u=p.ok?Ns(p.stdout):null;if(u?.button==="Send"){let g=u.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return u?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",Os(s,rn(t),["Not now","No","Yes"],r),o),d=a.ok?Ns(a.stdout):null;return d?.button==="Yes"?{action:"yes"}:d?.button==="No"?{action:"no"}:{action:"dismiss"}}var an=24*36e5,on=!1,ad=10*6e4,Ms=-1/0;function Fs(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o,passAt:s,wanted:i=[]}=O(t.root),a=s?Date.parse(s):NaN,d=Z(t.root,"pending").filter(c=>Date.parse(c.expires)>n),l=d.find(c=>i.includes(`card:${c.id}`));if(l)return l;for(let c of d){let p=`card:${c.id}`;if(r[p]||!e(c)||_r(t.root,c.id,n))continue;let u=o[p];if(u&&Date.parse(u)>n)continue;let g=Date.parse(c.created_at);if(!(n-g>an&&!(g<=a)))return c}return null}function sn(t){try{return G(t)?.listByState("needs_attention")??[]}catch{return[]}}var Ws=new Map;function ld(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=O(t.root);return e({})?sn(t).find(s=>{let i=`request:${s.id}`,a=o[i];return Ws.get(s.id)===K(s,rt.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=an})??null:null}function cd(t,e){return{id:t.id,title:K(t,rt.title).headline,context:t.attentionReason??"It is not finished and nothing is retrying it.",ask:`Hand it back to ${t.agentId}, or drop it?`,say:"A request you made is not finished.",recommend:"",if_silent:"keep",expires:new Date(e+an).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function hm(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(on)return"busy";let o=Fs(e,t.reaches)?null:ld(e,t.reaches),s=o?cd(o,e.now??Date.now()):Fs(e,t.reaches);if(!s)return"none";let i=(t.focus??ls)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,d=(O(e.root).wanted??[]).includes(a)?null:Un(s);if(d){if(o)Ws.set(o.id,s.title);else{let l=[...Z(e.root,"pending").map(c=>`card:${c.id}`),...sn(e).map(c=>`request:${c.id}`)];ht(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${d}`),t.returnToAuthor?.(s,jn(s,d)),"returned"}on=!0;try{let l=[...Z(e.root,"pending").map(w=>`card:${w.id}`),...sn(e).map(w=>`request:${w.id}`)];ht(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let c=e.now??Date.now(),p=!!o&&c-Ms<ad;o&&n.speak&&(Ms=c);let u=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??Ps)(s,p?{...n,speak:!1}:n,{from:u,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${Zn(i)} when shown)`),"shown";if(!(o?G(e)?.get(o.id)?.state==="needs_attention":ce(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let m=await go(e,a,g.action,{by:"operator (popup)",popup:!0,...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(m.ok?`[approvals] popup: ${m.message}`:`[approvals] popup: ${a} not recorded: ${m.error}`),"shown"}catch(l){return r(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{on=!1}}function bm(t,e,n){if(!n)return{ok:!1,error:"the Mac popup is off; turn it on with `agentx approvals settings --popup on`"};let r=e.startsWith("card:")?ce(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Fr(t.root,e),{ok:!0,message:`${e} will show on the Mac within a minute`}):{ok:!1,error:`no card "${e}"; the popup shows decision cards only`}}import{existsSync as dd,mkdirSync as ud,readFileSync as pd,renameSync as gd,writeFileSync as fd}from"fs";import{dirname as md,resolve as hd}from"path";var bd=["all","urgent","off"],yd=24*36e5,Us=24*36e5,wd=30*24*36e5,js=t=>bd.includes(t);function km(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:js(e)?e:"off",computer:js(n)?n:t.popupEnabled?"all":"off"}}function Hs(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=yd}function Bs(t,e,n){return t==="all"||t==="urgent"&&Hs(e,n)}function Vs(t){return hd(t,".agentx","desk-routed.json")}function xd(t){let e=Vs(t);if(!dd(e))return null;try{let n=JSON.parse(pd(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function ln(t,e){let n=Vs(t);ud(md(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;fd(r,JSON.stringify(e,null,2)),gd(r,n)}async function vm(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),d=xd(e);if(!d){let p={};for(let u of r.items)p[u.key]={at:a,seen:a};return ln(e,{items:p}),i.primed=!0,i}let l=[],c=[];for(let p of r.items){let u=d.items[p.key];if(u){u.seen=a,u.computerHeld&&n-Date.parse(u.at)>Us&&delete u.computerHeld,u.computerHeld&&c.push(p);continue}d.items[p.key]={at:a,seen:a};let g=p.askedAt?Date.parse(p.askedAt):n;n-g<=Us&&l.push(p)}for(let[p,u]of Object.entries(d.items))n-Date.parse(u.seen)>wd&&delete d.items[p];ln(e,d);for(let p of l)if(Bs(o.phone,p,n))try{await t.phone(p,Hs(p,n)),i.phone.push(p.key)}catch(u){s(`[desk] ${p.key}: not sent to the phone: ${u?.message??u}`)}if(t.computer){let p=!1;for(let u of[...c,...l]){let g=d.items[u.key];if(!Bs(o.computer,u,n)){g.computerHeld&&(delete g.computerHeld,p=!0);continue}try{let f=await t.computer(u);f&&i.computer.push(u.key),f&&g.computerHeld&&(delete g.computerHeld,p=!0),!f&&!g.computerHeld&&(g.computerHeld=!0,p=!0)}catch(f){s(`[desk] ${u.key}: not shown on this computer: ${f?.message??f}`),g.computerHeld&&(delete g.computerHeld,p=!0)}}p&&ln(e,d)}return(i.phone.length||i.computer.length)&&s(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function Sm(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
|
|
882
|
+
Answer it on the Desk.`}}import{closeSync as ye,createReadStream as kd,fstatSync as vd,openSync as Sd,realpathSync as qs}from"fs";import{isAbsolute as $d,resolve as zs,sep as Xs}from"path";var Tm="/app-files",Ed=/^[A-Za-z0-9_.:-]{1,64}$/;function Ad(t,e,n=process.cwd()){if(!e||e.length>U.pathChars||e.includes("\0"))return{ok:!1,status:400,error:"bad file path"};if(e.split(/[\\/]/).includes(".."))return{ok:!1,status:403,error:`the path leaves the workspace: copy the file into ${ct}/ first`};if(!ue(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=qs(zs(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=qs($d(e)?e:zs(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+Xs))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${ct}/ first`};let s=ue(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function _d(t,e){let n=t.replace(/[^\x20-\x7e]/g,"_").replace(/["\\;]/g,"_").slice(0,120)||"file";return`${e==="file"?"attachment":"inline"}; filename="${n}"; filename*=UTF-8''${encodeURIComponent(t.slice(0,120))}`}function Rd(t,e,n){return{"Content-Type":t,"Content-Disposition":_d(e,n),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; img-src 'self'; media-src 'self'; sandbox","Cache-Control":"private, max-age=3600","Accept-Ranges":"bytes"}}function Td(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,o;return n[1]?(r=Number(n[1]),o=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),o=e-1),r>o||r>=e?"unsatisfiable":{start:r,end:o}}function Im(t,e,n,r){let o=(x,b)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(b))};if(t.method!=="GET"&&t.method!=="HEAD")return o(405,{error:"GET only"});let s=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!Ed.test(s))return o(400,{error:"bad agent id"});let a=r.workspaceOf(s);if(!a)return o(404,{error:`no agent "${s}" on this computer`});let d=Ad(a,i,r.cwd);if(!d.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${s}: ${d.error}`),o(d.status,{error:d.error});let l;try{l=Sd(d.path,"r")}catch{return o(404,{error:"file not found"})}let c;try{let x=vd(l);if(!x.isFile())return ye(l),o(404,{error:"not a file"});c=x.size}catch{return ye(l),o(404,{error:"file not found"})}if(c>U.bytes)return ye(l),o(413,{error:`the file is larger than ${U.bytes/1024/1024} MB`});let p=d.path.split(Xs).pop()||"file",u=Rd(d.mime,p,d.kind),g=Td(t.headers.range,c);if(g==="unsatisfiable"){ye(l),e.writeHead(416,{...u,"Content-Range":`bytes */${c}`}),e.end();return}let{start:f,end:m}=g??{start:0,end:c-1};if(e.writeHead(g?206:200,{...u,"Content-Length":String(c?m-f+1:0),...g?{"Content-Range":`bytes ${f}-${m}/${c}`}:{}}),t.method==="HEAD"||c===0){ye(l),e.end();return}let w=kd("",{fd:l,start:f,end:m,autoClose:!0});w.on("error",()=>e.destroy()),e.on("close",()=>w.destroy()),w.pipe(e)}import{spawn as we}from"child_process";import{readFileSync as Id,writeFileSync as Dd}from"fs";import{tmpdir as Cd}from"os";import{join as Od}from"path";$n();var Ks=t=>t&&t!==1?Math.round(175*t):null,Ke=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function Nd(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let t of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let e=Id(t,"utf8").trim();if(e)return e}catch{}return null}function Wm(t=Nd()){let e=0;return async(n,r)=>{if(n.voice.provider==="system")return null;if(!t){if(n.voice.fallback)return null;throw new Error("ElevenLabs is the voice provider but no key is set")}try{let o=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n.voice.elevenlabs}/stream?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n.text,model_id:"eleven_flash_v2_5",...Ke(n.voice.rate)?{voice_settings:{speed:Ke(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=Od(Cd(),`agentx-say-${process.pid}-${++e}.mp3`);return Dd(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return J(`elevenlabs:${String(o?.message??o).slice(0,40)}`,`[voice] ElevenLabs failed (${String(o?.message??o).slice(0,160)}); speaking with the system voice`),null}}}function Gs(t,e){let n=t.languages&&Ee(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Ld=(t,e="")=>{let n=Gs(t,e),r=Ks(t.rate);return[...n&&!Eo(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Pd(t,e,n){if(!n)return["say",Ld(t,e)];let r=Gs(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function Um(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function jm(t=cn()){if(t)try{we("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Bm(t=cn()){if(t)try{we("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function cn(t={},e){if(!At(t))return null;try{return Ro(e)}catch(n){return J("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
|
|
883
|
+
`)[0]}); Siri voices will not switch`),null}}var Hm=(t,e)=>{if(!t){let[n,r]=Pd(e.voice,e.text,cn()),o=Ks(e.voice.rate),s=o?{...process.env,AGENTX_SAY_RATE:String(o)}:process.env,i=we(n,r,{stdio:["pipe","ignore","ignore"],env:s});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?we("afplay",[t],{stdio:"ignore"}):we("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as Js}from"child_process";import{accessSync as Md,constants as Fd,readFileSync as Ys}from"fs";import{homedir as Wd}from"os";import{basename as se,delimiter as Qs,dirname as Ud,extname as jd,join as dn}from"path";var X={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function Zs(t){let e=Array.isArray(t)?t[0]:t;return!e||!/^\d{1,9}$/.test(e.trim())?{status:400,error:"Say how long the recording is (X-Audio-Duration-Ms)."}:Number(e)>X.ms+2e3?{status:413,error:pn()}:null}var pn=()=>`The recording is longer than ${X.ms/6e4} minutes.`,Bd={"audio/webm":"webm","video/webm":"webm","audio/ogg":"ogg","audio/mp4":"m4a","video/mp4":"m4a","audio/x-m4a":"m4a","audio/aac":"aac","audio/mpeg":"mp3","audio/wav":"wav","audio/x-wav":"wav","audio/wave":"wav"};function ei(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Bd[e]??null}function ti(t,e){let n=[];return t!=="local"&&e.key&&n.push("elevenlabs"),e.ffmpeg&&(e.mlx?n.push("mlx-whisper"):e.whisper&&n.push("whisper")),n}function gn(t,e){return t==="local"&&e.key&&!e.ffmpeg?"Speech to text is set to local, and this computer has no ffmpeg.":(e.mlx||e.whisper)&&!e.ffmpeg?"This computer has Whisper but no ffmpeg to read the recording.":"Add an ElevenLabs key on this computer, or install mlx-whisper and ffmpeg."}function un(t,e,n=process.env.PATH??""){let r=Wd(),o=[dn(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(Qs).filter(Boolean)];for(let s of[e,...o.map(i=>dn(i,t))])if(s)try{return Md(s,Fd.X_OK),s}catch{}return null}function Gm(t){return{key:t,mlx:un("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:un("whisper",process.env.AGENTX_WHISPER),ffmpeg:Hd()}}var Hd=()=>un("ffmpeg",process.env.AGENTX_FFMPEG);async function ni(t,e){return e?Vd(t,e):null}async function Vd(t,e){let n=String(X.ms/1e3+5);try{let o=[...(await qd(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],s=o[o.length-1];return s?Number(s[1])*3600+Number(s[2])*60+Number(s[3]):null}catch{return null}}async function ri(t,e,n,r){let o=new FormData;o.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),o.set("file",new Blob([Ys(t)],{type:e}),se(t));let s=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:o,signal:r??AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);let i=await s.json();if(typeof i.text!="string")throw new Error("ElevenLabs returned no text");return i.text.trim()}async function oi(t,e,n,r,o){let s=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",o,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",o,"--fp16","False"],i={...process.env,PATH:`${Ud(r)}${Qs}${process.env.PATH??""}`};await zd(e,s,12e4,i);try{return Ys(dn(o,se(n,jd(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function qd(t,e,n){return new Promise((r,o)=>{let s=Js(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{s.kill("SIGKILL"),o(new Error(`${se(t)} took too long`))},n);s.stderr.on("data",d=>{i=(i+d).slice(-8192)}),s.on("error",d=>{clearTimeout(a),o(d)}),s.on("exit",d=>{clearTimeout(a),d===0?r(i):o(new Error(`${se(t)} exited ${d}`))})})}function zd(t,e,n,r=process.env){return new Promise((o,s)=>{let i=Js(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",d="",l=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`${se(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",c=>{a.length<4096&&(a+=c)}),i.stderr.on("data",c=>{d.length<4096&&(d+=c)}),i.on("error",c=>{clearTimeout(l),s(c)}),i.on("exit",c=>{clearTimeout(l),c===0?o(a):s(new Error(`${se(t)} exited ${c}: ${d.trim().split(`
|
|
884
|
+
`).pop()?.slice(0,160)??""}`))})})}An();bi();import{mkdtemp as Xd,rm as Kd,writeFile as Gd}from"fs/promises";import{tmpdir as Jd}from"os";import{join as si}from"path";var Yd=64*1024,Qd=2,fn=0;function ih(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function ah(t,e,n,r){return t.method!=="POST"?A(e,405,{error:"POST"}):n==="/voice/transcribe"?Zd(t,e,r):nu(t,e,r)}async function Zd(t,e,n){let r=String(t.headers["content-type"]||""),o=ei(r);if(!o)return A(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=Zs(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),A(e,s.status,{error:s.error});let i=await ii(t,X.bytes);if(!i)return A(e,413,{error:su()});if(!i.length)return A(e,400,{error:"The recording is empty."});if(fn>=Qd)return A(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),d=n.host(),l=ti(a,d);if(!d.ffmpeg&&!n.allowUnmeasured?.()){let p=n.nodeName?`on ${n.nodeName}`:"on this computer",u=l.length?"":" "+gn(a,d);return A(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${p} for voice input from the phone.${u}`,setup:!1})}if(!l.length)return A(e,503,{error:"Voice input isn't set up on this computer.",hint:gn(a,d),setup:!1});fn++;let c;try{let p=await Xd(si(Jd(),"agentx-phone-voice-"));try{c=await eu(p,`speech.${o}`,i,r,d,l,n)}finally{await Kd(p,{recursive:!0,force:!0}).catch(()=>{})}}finally{fn--}A(e,c[0],c[1])}async function eu(t,e,n,r,o,s,i){let a=si(t,e);if(await Gd(a,n,{mode:384}),o.ffmpeg){let l=await(i.measure??ni)(a,o.ffmpeg);if(l==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(l*1e3>X.ms+2e3)return[413,{error:pn()}]}let d=[];for(let l of s)try{let c=await tu(l,a,r,o,t,i);return i.log(`[voice] phone recording transcribed with ${l} (${Math.round(n.length/1024)} KB)`),c?[200,{text:c,engine:l}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:l}]}catch(c){let p=String(c?.message??c).split(`
|
|
885
|
+
`)[0].slice(0,200);d.push(`${l}: ${p}`),i.log(`[voice] phone transcription with ${l} failed: ${p}`)}return[502,{error:"Speech to text failed on this computer.",detail:d.join("; ")}]}function tu(t,e,n,r,o,s){let i=s.engines?.[t];if(i)return i(e,n,r,o);if(t==="elevenlabs")return ri(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return oi(t,a,e,r.ffmpeg,o)}async function nu(t,e,n){let r=await ii(t,Yd);if(!r)return A(e,413,{error:"request too large"});let o;try{o=JSON.parse(r.toString("utf8")||"{}")}catch{return A(e,400,{error:"expected JSON"})}let s=typeof o?.agent=="string"?o.agent:"",i=typeof o?.peer=="string"&&o.peer?o.peer:void 0;if(!s)return A(e,400,{error:"agent is required"});let a=ru(typeof o?.text=="string"?o.text:"",n.spokenMaxChars?.());if(!a)return A(e,422,{error:"Nothing in this answer can be said aloud."});let d=n.pronounce?n.pronounce(a):a,l=n.voiceOf(s,i);if(!l)return A(e,404,{error:`Unknown agent: ${s}`});let c=(u,g=200)=>A(e,g,{fallback:"browser",reason:u,text:d});if(l.provider!=="elevenlabs")return c("This agent speaks with a system voice, which only plays on the computer.");let p=n.elevenLabsKey();if(!p)return c("No ElevenLabs key is set on this computer.");try{let u=await(n.synth??ou)(p,l,d);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":u.length,"Cache-Control":"no-store","X-Spoken-Chars":String(d.length)}),e.end(u)}catch(u){return n.log(`[voice] phone answer synthesis failed: ${String(u?.message??u).split(`
|
|
886
|
+
`)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function ru(t,e){let n=Ae(Te(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return En(n,e)}async function ou(t,e,n){let r=Ke(e.rate),o=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(e.elevenlabs)}?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n,model_id:"eleven_flash_v2_5",...r?{voice_settings:{speed:r}}:{}}),signal:AbortSignal.timeout(6e4)});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text().catch(()=>"")).slice(0,160)}`);return Buffer.from(await o.arrayBuffer())}var su=()=>`The recording is larger than ${X.bytes/1024/1024} MB, more than ${X.ms/6e4} minutes of speech.`;function lh(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let o=n.agents??{};return o[t]?Pt(Ot(t,o,n.voice)):null}function ii(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,r)=>{let o=[],s=0;t.on("data",i=>{if(!(s>e)){if(s+=i.length,s>e){o.length=0,n(null);return}o.push(i)}}),t.on("end",()=>{s<=e&&n(Buffer.concat(o))}),t.on("error",r)})}function A(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}An();var iu="[Live voice call on the owner's watch or headset. Your answer is read aloud to them and they can't see a screen. Answer what they just said, in a few short spoken sentences.]",au="operator",lu=50,ai=4,li=500;function cu(t){let e={channel:"app",chatId:t.chatId,sender:au,...t.spoken?{via:"voice"}:{}},n=t.call==="watch"?`${iu}
|
|
947
887
|
|
|
948
|
-
${t.message}`:t.message;return t.node==="local"?{path:"/task",body:{agent:t.agent,message:n,stream:!0,context:e}}:{path:"/mesh/task",body:{peer:t.node,agent:t.agent,message:n,stream:!0,context:e}}}async function
|
|
888
|
+
${t.message}`:t.message;return t.node==="local"?{path:"/task",body:{agent:t.agent,message:n,stream:!0,context:e}}:{path:"/mesh/task",body:{peer:t.node,agent:t.agent,message:n,stream:!0,context:e}}}async function gh(t,e,n,r){let{path:o,body:s}=cu(e),i="",a=!1,d=[],l=new Map,c=(p,u,g)=>{let f=p!=="done",m=a?{text:Gn(u,f),artifacts:[]}:Te(u,U.perMessage,f),{cleanText:w,ui:x}=p==="done"?Ae(m.text):{cleanText:m.text,ui:void 0},b=a?void 0:uu(x);return{status:p,text:w,tools:d,files:m.artifacts,...b?{ui:b}:{},...g?{error:g}:{}}};try{let p=await fetch(t.url.replace(/\/+$/,"")+o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t.token?{Authorization:`Bearer ${t.token}`}:{},...t.operatorKey?{"X-AgentX-Operator":t.operatorKey}:{}},body:JSON.stringify(s),signal:n});if(!p.ok||!p.body){let u=await p.json().then(g=>g?.error).catch(()=>"");return c("error",i,u||`AgentX answered HTTP ${p.status}.`)}for await(let u of pu(p.body)){r(u.event,u.data);let g=u.data??{};if(u.event==="start")a=g.rich===!1;else if(u.event==="text"&&typeof g.text=="string")i+=g.text;else if(u.event==="tool"&&g.status==="start"&&d.length<lu){let f={name:String(g.name||"tool").slice(0,80),...g.arg?{arg:String(g.arg).slice(0,80)}:{}};d.push(f),g.id&&l.set(String(g.id),f)}else if(u.event==="tool"&&g.status==="result"&&g.error===!0&&l.has(String(g.id)))l.get(String(g.id)).error=!0;else{if(u.event==="done")return c("done",typeof g.content=="string"&&g.content?g.content:i);if(u.event==="error")return c("error",i,du(g.error))}}return n.aborted?c("stopped",i):c("error",i,"The connection to the agent closed before it answered.")}catch(p){return n.aborted?c("stopped",i):c("error",i,`Could not reach AgentX: ${p?.message||p}`)}}function du(t){let e=String(t||"The agent could not answer.");return Vn(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function uu(t){if(!t)return;let e=i=>/^https?:\/\//i.test(i)&&i.length<=2048,n={},r=(t.buttons??[]).filter(i=>e(i.url)).slice(0,8).map(i=>({label:i.label.slice(0,80),url:i.url}));r.length&&(n.buttons=r),t.poll&&(n.poll={question:t.poll.question.slice(0,300),options:t.poll.options.slice(0,10).map(i=>i.slice(0,100)),multiple:t.poll.multiple===!0}),t.media&&e(t.media.url)&&(n.media={type:t.media.type,url:t.media.url,...t.media.caption?{caption:t.media.caption.slice(0,300)}:{}});let o=(t.quickReplies??[]).slice(0,ai).map(i=>i.slice(0,li));o.length&&(n.quickReplies=o);let s=(t.replies??[]).slice(0,ai).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,li)}));return s.length&&(n.replies=s),Object.keys(n).length?n:void 0}async function*pu(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o)break;r+=n.decode(s,{stream:!0}).replace(/\r\n/g,`
|
|
949
889
|
`);let i;for(;(i=r.indexOf(`
|
|
950
890
|
|
|
951
891
|
`))!==-1;){let a=r.slice(0,i);r=r.slice(i+2);let d="message",l=[];for(let c of a.split(`
|
|
952
892
|
`))c.startsWith("event:")?d=c.slice(6).trim():c.startsWith("data:")&&l.push(c.slice(5).replace(/^ /,""));if(l.length)try{yield{event:d,data:JSON.parse(l.join(`
|
|
953
|
-
`))}}catch{}}}}finally{e.releaseLock()}}var
|
|
893
|
+
`))}}catch{}}}}finally{e.releaseLock()}}var ci=["custom","announce"];function mh(t,e){let n=t.nodeName,r=t.recent().filter(s=>ci.includes(s.kind)).slice(-500),o=(e?.list()??[]).slice(-500).map(s=>({...s,node:n}));return{node:n,events:r,wakes:o}}function hh(t,e={}){let n=e.now??Date.now(),r=Math.max(1,Math.min(200,Math.floor(e.limit||50))),o=new Map;for(let b of t)for(let y of b.events)ci.includes(y.kind)&&!o.has(y.id)&&o.set(y.id,y);let s=[...o.values()].sort((b,y)=>Date.parse(b.at)-Date.parse(y.at)||b.id.localeCompare(y.id)),i=new Map,a=new Map,d=new Set;for(let b of t)for(let y of b.wakes){let k=y.node||b.node,D=`${k}#${y.agentId}#${y.eventId}`;if(d.has(D))continue;d.add(D);let ae=i.get(y.eventId)??[];if(ae.push(fu(y,k,n)),i.set(y.eventId,ae),y.status!=="skipped"){let ve=`${y.agentId}#${y.rootId}`,h=a.get(ve)??[];h.push({eventId:y.eventId,at:y.decidedAt}),a.set(ve,h)}}for(let b of i.values())b.sort((y,k)=>y.decidedAt-k.decidedAt||y.agentId.localeCompare(k.agentId));let l=new Map,c=[];for(let b of s){let y=gu(b,o,a,c);y&&y!==b.id&&l.set(b.id,y),c.push(b)}let p=b=>{let y=b;for(let k=0;k<50;k++){let D=l.get(y);if(!D)return y;y=D}return y},u=new Map,g=b=>({event:b,wakes:i.get(b.id)??[]});for(let b of s){let y=p(b.id);y===b.id?u.set(b.id,{...g(b),replies:[]}):u.get(y)?.replies.push(g(b))}let f=b=>Math.max(Date.parse(b.event.at),...b.replies.map(y=>Date.parse(y.event.at))),m=[...u.values()].sort((b,y)=>f(y)-f(b)),w=[...i.values()].flat(),x=b=>w.filter(y=>b.includes(y.status)).length;return{threads:m.slice(0,r),total:m.length,counts:{events:s.length,wakes:w.length,ran:x(["ran"]),waiting:x(["waiting","held","running"]),timedOut:x(["timed-out","dropped"]),failed:x(["failed"]),skipped:x(["skipped"])}}}function gu(t,e,n,r){if(t.parentId&&e.has(t.parentId))return t.parentId;let o=Date.parse(t.at);if(t.agentId){let s=(n.get(`${t.agentId}#${t.rootId}`)??[]).filter(i=>i.eventId!==t.id&&e.has(i.eventId)&&Date.parse(e.get(i.eventId).at)<=o).sort((i,a)=>a.at-i.at)[0];if(s)return s.eventId}if(t.rootId!==t.id)for(let s=r.length-1;s>=0;s--){let i=r[s];if(i.rootId===t.rootId&&(i.agentId??i.node)!==(t.agentId??t.node))return i.id}}function fu(t,e,n){let r={agentId:t.agentId,node:e,status:t.status,decidedAt:t.decidedAt,attempts:t.attempts};if(t.reason&&(r.reason=t.reason),t.startedAt&&(r.startedAt=t.startedAt),t.endedAt&&(r.endedAt=t.endedAt),t.taskId&&(r.taskId=t.taskId),t.error&&(r.error=t.error),t.status!=="skipped"){let o=t.startedAt??t.endedAt??n;r.waitedMs=Math.max(0,o-t.decidedAt)}return r}import{existsSync as M,readFileSync as yn,writeFileSync as wn,mkdirSync as Ge,readdirSync as bn,rmSync as mu,statSync as W}from"fs";import{resolve as di,relative as hu,dirname as xn,join as Q,extname as xe,basename as kn}from"path";var I=200*1024,ui=new Set([".md",".markdown",".txt"]),ie=new Set([".md",".markdown",".txt",".json",".jsonc",".yaml",".yml",".toml",".sh",".bash",".zsh",".py",".js",".mjs",".ts",".tsx",".jsx",".css",".html",".lock",".cfg",".ini",".env",".gitignore"]),bu=6,yu=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function H(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=di(t);if(M(n)||Ge(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=di(n,e);if(hu(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function pi(t){let e=xe(t).toLowerCase();if(!ui.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function mn(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function xh(t){let e=H(t,"."),n=[],r=new Set,o=[];try{o=bn(e)}catch{}for(let a of yu){let d=Q(e,a);if(M(d)&&W(d).isFile()){let l=W(d).size,c=l>0&&l<I?hn(d):"";n.push({path:a,title:mn(c,a),size:l,exists:!0}),r.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),r.add(a)}for(let a of o){if(r.has(a))continue;let d=Q(e,a);try{let l=W(d);if(!l.isFile()||!ui.has(xe(a).toLowerCase()))continue;let c=l.size>0&&l.size<I?hn(d):"";n.push({path:a,title:mn(c,a),size:l.size,exists:!0})}catch{}}let s=[],i=Q(e,".claude","skills");if(M(i))try{for(let a of bn(i)){let d=Q(i,a),l;try{l=W(d)}catch{continue}if(!l.isDirectory())continue;let c=Q(d,"SKILL.md");if(!M(c))continue;let p=W(c),u=p.size<I?hn(c):"";s.push({slug:a,title:mn(u,a),size:p.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return s.sort((a,d)=>a.slug.localeCompare(d.slug)),{identity:n,skills:s,workspace:e}}function hn(t){try{return yn(t,"utf-8")}catch{return""}}function kh(t,e){let n=H(t,e);if(pi(n),!M(n))return{path:e,content:""};if(W(n).size>I)throw new Error(`File is too large to edit in the admin panel (> ${I/1024} KB).`);return{path:e,content:yn(n,"utf-8")}}function vh(t,e,n){let r=H(t,e);pi(r);let o=Buffer.from(n,"utf-8");if(o.length>I)throw new Error(`File too large (${o.length} > ${I} bytes).`);return Ge(xn(r),{recursive:!0}),wn(r,o),{path:e,bytes:o.length}}function Sh(t,e,n={}){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error("Skill slug must be lowercase (letters, digits, -, _) and start with a letter or digit.");let r=`.claude/skills/${e}/SKILL.md`,o=H(t,r);if(M(o))throw new Error(`Skill "${e}" already exists.`);Ge(xn(o),{recursive:!0});let s=n.content?.trim()?n.content:wu(e,n.title);return wn(o,s),{slug:e,path:r}}function $h(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=H(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);if(!W(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return mu(n,{recursive:!0,force:!0}),{slug:e}}function Eh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=H(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);let r=[];return o(n,"",0,r),r.sort((s,i)=>s.kind!==i.kind?s.kind==="dir"?-1:1:s.path.localeCompare(i.path)),r;function o(s,i,a,d){if(a>bu)return;let l=[];try{l=bn(s)}catch{return}for(let c of l){if(c==="node_modules"||c===".git")continue;let p=Q(s,c),u=i?`${i}/${c}`:c,g;try{g=W(p)}catch{continue}if(g.isDirectory())d.push({path:`${u}/`,kind:"dir",size:0,editable:!1}),o(p,u,a+1,d);else if(g.isFile()){let f=xe(c).toLowerCase(),m=ie.has(f)||ie.has(c.toLowerCase());d.push({path:u,kind:"file",size:g.size,editable:m&&g.size<I})}}}}function Ah(t,e,n){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let r=H(t,`.claude/skills/${e}/${n}`);if(!M(r)||!W(r).isFile())throw new Error(`File not found: ${n}`);let o=xe(r).toLowerCase(),s=kn(r).toLowerCase();if(!ie.has(o)&&!ie.has(s))throw new Error(`File type not editable: ${n}`);if(W(r).size>I)throw new Error(`File too large to edit (> ${I/1024} KB): ${n}`);return{path:n,content:yn(r,"utf-8")}}function _h(t,e,n,r){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let o=H(t,`.claude/skills/${e}/${n}`),s=xe(o).toLowerCase(),i=kn(o).toLowerCase();if(!ie.has(s)&&!ie.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>I)throw new Error(`File too large (${a.length} > ${I} bytes).`);return Ge(xn(o),{recursive:!0}),wn(o,a),{path:n,bytes:a.length}}function Rh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=H(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);let r=o=>M(Q(n,o));return r("pnpm-lock.yaml")?{manager:"pnpm",file:"pnpm-lock.yaml",command:"pnpm install"}:r("yarn.lock")?{manager:"yarn",file:"yarn.lock",command:"yarn install"}:r("package.json")?{manager:"npm",file:"package.json",command:"npm install"}:r("requirements.txt")?{manager:"pip",file:"requirements.txt",command:"pip install -r requirements.txt"}:r("Gemfile")?{manager:"bundle",file:"Gemfile",command:"bundle install"}:{manager:null,file:null,command:null}}function wu(t,e){return`# ${e?.trim()||t}
|
|
954
894
|
|
|
955
895
|
Describe what this skill does and when the agent should use it. Keep it under ~5 lines \u2014 the agent reads this to decide whether to invoke the skill.
|
|
956
896
|
|
|
@@ -963,7 +903,7 @@ Document the arguments, commands, or files the skill expects. Example:
|
|
|
963
903
|
|
|
964
904
|
\`\`\`bash
|
|
965
905
|
# Example invocation
|
|
966
|
-
claude-code ${
|
|
906
|
+
claude-code ${kn(t)} --arg value
|
|
967
907
|
\`\`\`
|
|
968
|
-
`}
|
|
969
|
-
//# sourceMappingURL=chunk-
|
|
908
|
+
`}Cn();var gi={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function fi(t){return{...gi,...t??{},regions:{...t?.regions??{}},buffer:{...gi.buffer,...t?.buffer??{}}}}function Dh(t){try{return fi(Dn(t).screen)}catch{return fi(void 0)}}var xu=/^[a-z][\w-]*$/,mi=["window","screen","menubar","notifications"];function ke(t,e,n,r){let o=Number(t);if(t===""||t===null||!Number.isFinite(o)||!n(o))throw new Error(`${e} must be ${r}`);return o}var Je=(t,e)=>ke(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function hi(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function Ch(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Je(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Je(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Je(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ke(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ke(e.changeThreshold,"changeThreshold",o=>o>=0&&o<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let o={...n.regions??{}};for(let[s,i]of Object.entries(e.regions)){if(!xu.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=hi(i)}n.regions=o}if(e.buffer&&typeof e.buffer=="object"){let o=e.buffer,s={...n.buffer??{}};"enabled"in o&&(s.enabled=!!o.enabled),"seconds"in o&&(s.seconds=ke(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=ke(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=Je(o.maxPixels,"buffer.maxPixels")),"region"in o&&(s.region=String(o.region).trim()),n.buffer=s}let r=n.buffer?.region;if(r!==void 0&&!mi.includes(r)&&!n.regions?.[r])try{hi(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...mi,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Rr as a,Su as b,Kt as c,Zl as d,ec as e,ef as f,tf as g,nf as h,sf as i,af as j,lf as k,rs as l,os as m,cf as n,uf as o,z as p,ss as q,R as r,_u as s,ls as t,bf as u,xf as v,ds as w,kf as x,us as y,vf as z,he as A,$c as B,Sf as C,$f as D,gs as E,Bu as F,Ji as G,Ku as H,Xr as I,O as J,Cu as K,Ou as L,Wr as M,Wu as N,G as O,_p as P,co as Q,go as R,Rc as S,Af as T,Tc as U,_f as V,Rf as W,Jt as X,ms as Y,Df as Z,Qt as _,Cc as $,Oc as aa,Lf as ba,Ia as ca,Da as da,Ip as ea,Dp as fa,Fa as ga,Lp as ha,Ss as ia,Ff as ja,Fp as ka,Wp as la,Zo as ma,Wt as na,zl as oa,T as pa,Ps as qa,hm as ra,bm as sa,bd as ta,km as ua,Bs as va,vm as wa,Sm as xa,Tm as ya,Ad as za,Rd as Aa,Im as Ba,jp as Ca,Bp as Da,Hp as Ea,Vp as Fa,qp as Ga,zp as Ha,Xp as Ia,Kp as Ja,Jp as Ka,Yp as La,eg as Ma,tg as Na,ng as Oa,sg as Pa,ig as Qa,ag as Ra,lg as Sa,cg as Ta,dg as Ua,ug as Va,xg as Wa,Tt as Xa,kg as Ya,vg as Za,fe as _a,me as $a,Nd as ab,Wm as bb,Um as cb,jm as db,Bm as eb,cn as fb,Hm as gb,Ct as hb,Ot as ib,Be as jb,fl as kb,hl as lb,_g as mb,Lt as nb,Pt as ob,bl as pb,yl as qb,Fo as rb,Bo as sb,Rg as tb,kl as ub,Tg as vb,Tl as wb,Cl as xb,Mt as yb,Nl as zb,Ho as Ab,X as Bb,Zs as Cb,ei as Db,ti as Eb,un as Fb,Gm as Gb,Hd as Hb,ri as Ib,oi as Jb,ih as Kb,ah as Lb,su as Mb,lh as Nb,ii as Ob,Xo as Pb,gh as Qb,uu as Rb,mh as Sb,hh as Tb,He as Ub,Vg as Vb,zt as Wb,Yg as Xb,xh as Yb,kh as Zb,vh as _b,Sh as $b,$h as ac,Eh as bc,Ah as cc,_h as dc,Rh as ec,gi as fc,fi as gc,Dh as hc,mi as ic,Ch as jc};
|
|
909
|
+
//# sourceMappingURL=chunk-2KNI7ZRN.js.map
|