#!/usr/bin/env node
import*as s from'fs';import*as a from'path';import*as P from'os';import*as p from'crypto';var g=a.join(P.homedir(),".paradigm","score"),D=a.join(P.homedir(),".paradigm","mail"),h=a.join(g,"agents"),S=a.join(g,"threads"),x=a.join(g,"file-requests"),O=a.join(g,"trust.yaml"),K=3600*1e3,T={users:{},defaults:{level:"restricted",autoApprove:[],neverApprove:[".env*","**/*.key","**/*.pem","**/credentials*","**/secrets/**"]}};function Y(){if(s.existsSync(D)&&!s.existsSync(g))try{s.renameSync(D,g);}catch{}}function d(){Y();for(let t of [h,S,x])s.existsSync(t)||s.mkdirSync(t,{recursive:true});}var tt=d;function f(t){return a.join(h,t)}function v(t){let n=f(t);return s.existsSync(n)||s.mkdirSync(n,{recursive:true}),n}function m(t){if(!s.existsSync(t))return [];let e=s.readFileSync(t,"utf-8").split(`
`).filter(i=>i.trim().length>0),r=[];for(let i of e)try{r.push(JSON.parse(i));}catch{}return r}function E(t,n){let e=a.dirname(t);s.existsSync(e)||s.mkdirSync(e,{recursive:true}),s.appendFileSync(t,JSON.stringify(n)+`
`,"utf-8");}function w(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"unknown"}function C(t){try{let n=a.join(t,".paradigm","config.yaml");if(s.existsSync(n)){let r=s.readFileSync(n,"utf-8").match(/^project:\s*(.+)$/m);if(r)return w(r[1].trim().replace(/["']/g,""))}}catch{}return w(a.basename(t))}function J(t,n){return `${C(t)}/${n||"core"}`}function et(t,n,e){d();let r=J(t,n),i=v(r),o=C(t),c={id:r,name:e||`${o} (${n||"core"})`,type:"agent",project:o,role:n||"core",pid:process.pid,startedAt:new Date().toISOString(),label:e};return s.writeFileSync(a.join(i,"identity.json"),JSON.stringify(c,null,2),"utf-8"),c}function Q(t){let n=f(t);if(!s.existsSync(n))return  false;try{return s.rmSync(n,{recursive:!0,force:!0}),!0}catch{return  false}}function F(){if(d(),!s.existsSync(h))return [];let t=[],n=s.readdirSync(h,{withFileTypes:true}).filter(e=>e.isDirectory());for(let e of n){let r=a.join(h,e.name),i=s.readdirSync(r,{withFileTypes:true}).filter(o=>o.isDirectory());for(let o of i){let c=a.join(r,o.name,"identity.json");if(s.existsSync(c))try{let u=s.readFileSync(c,"utf-8"),l=JSON.parse(u);t.push(l);}catch{}}}return t}function nt(){let t=F(),n=0;for(let e of t)b(e.pid)||(Q(e.id),n++);return n}function rt(t){let n=J(t),e=a.join(f(n),"identity.json");if(!s.existsSync(e))return null;try{return JSON.parse(s.readFileSync(e,"utf-8"))}catch{return null}}function st(t,n){let e=a.join(f(t),"identity.json");if(s.existsSync(e))try{let r=JSON.parse(s.readFileSync(e,"utf-8"));r.lastPoll=new Date().toISOString(),n!==void 0&&(r.statusBlurb=n||void 0),s.writeFileSync(e,JSON.stringify(r,null,2),"utf-8");}catch{}}function it(t,n){let e=a.join(f(t),"identity.json");if(s.existsSync(e))try{let r=JSON.parse(s.readFileSync(e,"utf-8"));r.statusBlurb=n||void 0,s.writeFileSync(e,JSON.stringify(r,null,2),"utf-8");}catch{}}function ot(t,n=6e4){if(!t.lastPoll)return  true;let e=new Date(t.lastPoll).getTime();return Date.now()-e>n}function at(){let n=F().filter(e=>b(e.pid));try{let e=a.join(P.homedir(),".conductor","sessions");if(s.existsSync(e)){let r=s.readdirSync(e).filter(i=>i.endsWith(".json"));for(let i of r)try{let o=s.readFileSync(a.join(e,i),"utf-8"),c=JSON.parse(o),u=parseInt(a.basename(i,".json"),10);!n.some(l=>l.pid===u)&&b(u)&&n.push({id:`conductor/${u}`,name:c.label||`Session ${u}`,type:"agent",project:c.projectDir?a.basename(c.projectDir):"unknown",role:"conductor",pid:u,startedAt:c.registeredAt||new Date().toISOString()});}catch{}}}catch{}return n}function y(t){return a.join(f(t),"inbox.jsonl")}function j(t){return a.join(f(t),"outbox.jsonl")}function $(t){return a.join(f(t),"ack.json")}function ct(t){let n=y(t);if(!s.existsSync(n))return {hasNew:false,inboxSize:0};let r=s.statSync(n).size;if(!k(t))return {hasNew:r>0,inboxSize:r};let o=a.join(f(t),"ack-size.json");if(s.existsSync(o))try{let c=JSON.parse(s.readFileSync(o,"utf-8"));return {hasNew:r>(c.size||0),inboxSize:r}}catch{}return {hasNew:r>0,inboxSize:r}}function ut(t){let n=y(t),e=a.join(f(t),"ack-size.json");try{let r=s.existsSync(n)?s.statSync(n).size:0;v(t),s.writeFileSync(e,JSON.stringify({size:r}),"utf-8");}catch{}}function N(t,n){v(t),E(y(t),n);}function ft(t,n){let e=m(y(t));if(!n){let i=k(t);if(i){let o=e.findIndex(c=>c.id===i);if(o>=0)return e.slice(o+1)}return e}let r=e.findIndex(i=>i.id===n);return r>=0?e.slice(r+1):e}function V(t,n){v(t),E(j(t),n);}function lt(t){return m(j(t))}function dt(t,n){let e=$(t);v(t),s.writeFileSync(e,JSON.stringify({lastAck:n}),"utf-8");}function k(t){let n=$(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8")).lastAck||null}catch{return null}}function pt(t){let n=k(t);if(!n)return 0;let e=y(t),r=m(e),i=r.findIndex(u=>u.id===n);if(i<0)return 0;let o=r.slice(i+1),c=r.length-o.length;return o.length===0?s.existsSync(e)&&s.writeFileSync(e,"","utf-8"):s.writeFileSync(e,o.map(u=>JSON.stringify(u)).join(`
`)+`
`,"utf-8"),c}function I(t){return a.join(S,`${t}.json`)}function gt(t,n){d();let e="thr-"+p.randomBytes(4).toString("hex"),r=new Date().toISOString(),i={id:e,topic:t,initiator:n,participants:[n],status:"active",createdAt:r,lastActivity:r,messageCount:0};return s.writeFileSync(I(e),JSON.stringify(i,null,2),"utf-8"),i}function z(t){let n=I(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8"))}catch{return null}}function yt(t){if(d(),!s.existsSync(S))return [];let n=s.readdirSync(S).filter(r=>r.endsWith(".json")),e=[];for(let r of n)try{let i=s.readFileSync(a.join(S,r),"utf-8"),o=JSON.parse(i);(!t||o.status===t)&&e.push(o);}catch{}return e.sort((r,i)=>i.lastActivity.localeCompare(r.lastActivity))}function _(t,n){let e=z(t);if(!e)return  false;let r={...e,...n};return s.writeFileSync(I(t),JSON.stringify(r,null,2),"utf-8"),true}function ht(t,n){return _(t,{status:"resolved",resolvedAt:new Date().toISOString(),decision:n})}function St(t){let n=F(),e=[];for(let r of n){let i=m(y(r.id)),o=m(j(r.id));for(let c of [...i,...o])(c.threadRoot===t||c.id===t)&&(e.some(u=>u.id===c.id)||e.push(c));}return e.sort((r,i)=>r.timestamp.localeCompare(i.timestamp))}function B(t){return {id:p.randomUUID(),parentId:t.parentId,threadRoot:t.threadRoot,timestamp:new Date().toISOString(),sender:t.sender,recipients:t.recipients,intent:t.intent,content:{text:t.text,diff:t.diff,decision:t.decision},symbols:t.symbols||[],attachments:t.attachments,metadata:t.metadata}}function L(t){d(),V(t.sender.id,t);let n=0;if(t.recipients&&t.recipients.length>0)for(let e of t.recipients)N(e.id,t),n++;else {let e=F();for(let r of e)r.id!==t.sender.id&&(N(r.id,t),n++);}if(t.threadRoot){let e=z(t.threadRoot);if(e){let i=e.participants.some(o=>o.id===t.sender.id)?e.participants:[...e.participants,t.sender];_(t.threadRoot,{participants:i,lastActivity:t.timestamp,messageCount:e.messageCount+1});}}return n}function A(t){return a.join(x,`${t}.json`)}function U(){if(!s.existsSync(O))return T;try{let t=s.readFileSync(O,"utf-8");try{return JSON.parse(t)}catch{return T}}catch{return T}}function xt(t){d();let n="freq-"+p.randomBytes(4).toString("hex"),e={request:{requestId:n,filePath:t.filePath,reason:t.reason,requester:t.requester,urgency:t.urgency||"normal",snippet:t.snippet,threadRoot:t.threadRoot},status:"pending",createdAt:new Date().toISOString()};return s.writeFileSync(A(n),JSON.stringify(e,null,2),"utf-8"),e}function G(t){let n=A(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8"))}catch{return null}}function Z(t){if(d(),!s.existsSync(x))return [];let n=s.readdirSync(x).filter(r=>r.endsWith(".json")),e=[];for(let r of n)try{let i=s.readFileSync(a.join(x,r),"utf-8"),o=JSON.parse(i);(!t||o.status===t)&&e.push(o);}catch{}return e.sort((r,i)=>i.createdAt.localeCompare(r.createdAt))}function mt(t,n,e){let r=G(t);if(!r)return {success:false,error:`File request not found: ${t}`};if(r.status!=="pending")return {success:false,error:`Request already ${r.status}`};let i=a.resolve(n,r.request.filePath);if(!i.startsWith(a.resolve(n)))return {success:false,error:"File path escapes project directory"};if(!s.existsSync(i))return {success:false,error:`File not found: ${r.request.filePath}`};try{let o=s.readFileSync(i,"utf-8"),c="utf8";if(e){let W=[/(?:api[_-]?key|secret|token|password|credential|auth)\s*[:=]/i,/(?:^|\s)(?:export\s+)?[A-Z_]+(?:KEY|SECRET|TOKEN|PASSWORD|CREDENTIAL)\s*=/,/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/];o=o.split(`
`).map(M=>{for(let H of W)if(H.test(M))return "[REDACTED]";return M}).join(`
`);}let u=p.createHash("sha256").update(o).digest("hex"),l={requestId:t,filePath:r.request.filePath,content:o,encoding:c,size:Buffer.byteLength(o),hash:u};r.status="approved",r.resolvedAt=new Date().toISOString(),r.delivery=l,s.writeFileSync(A(t),JSON.stringify(r,null,2),"utf-8");let q=B({sender:{id:"system",name:"File Transfer",type:"human"},recipients:[r.request.requester],intent:"fileDelivery",text:`File delivered: ${r.request.filePath} (${l.size} bytes, SHA-256: ${u.slice(0,12)}...)`,threadRoot:r.request.threadRoot,symbols:[]});return q.attachments=[{name:a.basename(r.request.filePath),type:"file",content:l.content,encoding:l.encoding}],L(q),{success:!0,delivery:l}}catch(o){return {success:false,error:`Failed to read file: ${o.message}`}}}function vt(t,n){let e=G(t);if(!e||e.status!=="pending")return  false;e.status="denied",e.resolvedAt=new Date().toISOString(),e.denyReason=n,s.writeFileSync(A(t),JSON.stringify(e,null,2),"utf-8");let r=B({sender:{id:"system",name:"File Transfer",type:"human"},recipients:[e.request.requester],intent:"fileDenied",text:`File request denied: ${e.request.filePath}${n?` \u2014 ${n}`:""}`,threadRoot:e.request.threadRoot,symbols:[]});return L(r),true}function R(t,n){let e=n.replace(/\./g,"\\.").replace(/\*\*/g,"{{GLOBSTAR}}").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/\{\{GLOBSTAR\}\}/g,".*");return new RegExp(`^${e}$`).test(t)}function X(t,n,e){let r=n||U();if(e&&r.users[e]){for(let i of r.users[e].neverApprove)if(R(t,i))return  true}for(let i of r.defaults.neverApprove)if(R(t,i))return  true;return  false}function At(t,n,e){let r=n||U();if(X(t,r,e))return  false;if(e&&r.users[e]){for(let i of r.users[e].autoApprove)if(R(t,i))return  true}for(let i of r.defaults.autoApprove)if(R(t,i))return  true;return  false}function Rt(){let t=Z("pending"),n=0;for(let e of t)Date.now()-new Date(e.createdAt).getTime()>K&&(e.status="expired",e.resolvedAt=new Date().toISOString(),s.writeFileSync(A(e.request.requestId),JSON.stringify(e,null,2),"utf-8"),n++);return n}function b(t){try{return process.kill(t,0),!0}catch{return  false}}export{z as A,yt as B,_ as C,ht as D,St as E,B as F,L as G,U as H,xt as I,G as J,Z as K,mt as L,vt as M,X as N,At as O,Rt as P,g as a,d as b,tt as c,f as d,m as e,E as f,J as g,et as h,Q as i,F as j,nt as k,rt as l,st as m,it as n,ot as o,at as p,ct as q,ut as r,N as s,ft as t,V as u,lt as v,dt as w,k as x,pt as y,gt as z};