#!/usr/bin/env node
import*as s from'fs';import*as a from'path';import*as v from'os';import*as l from'crypto';var g=a.join(v.homedir(),".paradigm","score"),q=a.join(v.homedir(),".paradigm","mail"),y=a.join(g,"agents"),h=a.join(g,"threads"),S=a.join(g,"file-requests"),M=a.join(g,"trust.yaml"),H=3600*1e3,F={users:{},defaults:{level:"restricted",autoApprove:[],neverApprove:[".env*","**/*.key","**/*.pem","**/credentials*","**/secrets/**"]}};function K(){if(s.existsSync(q)&&!s.existsSync(g))try{s.renameSync(q,g);}catch{}}function d(){K();for(let t of [y,h,S])s.existsSync(t)||s.mkdirSync(t,{recursive:true});}function p(t){return a.join(y,t)}function A(t){let n=p(t);return s.existsSync(n)||s.mkdirSync(n,{recursive:true}),n}function x(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 N(t,n){let e=a.dirname(t);s.existsSync(e)||s.mkdirSync(e,{recursive:true}),s.appendFileSync(t,JSON.stringify(n)+`
`,"utf-8");}function D(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"unknown"}function E(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 D(r[1].trim().replace(/["']/g,""))}}catch{}return D(a.basename(t))}function C(t,n){return `${E(t)}/${n||"core"}`}function X(t,n,e){d();let r=C(t,n),i=A(r),o=E(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 Y(t){let n=p(t);if(!s.existsSync(n))return  false;try{return s.rmSync(n,{recursive:!0,force:!0}),!0}catch{return  false}}function R(){if(d(),!s.existsSync(y))return [];let t=[],n=s.readdirSync(y,{withFileTypes:true}).filter(e=>e.isDirectory());for(let e of n){let r=a.join(y,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"),f=JSON.parse(u);t.push(f);}catch{}}}return t}function tt(){let t=R(),n=0;for(let e of t)T(e.pid)||(Y(e.id),n++);return n}function et(t){let n=C(t),e=a.join(p(n),"identity.json");if(!s.existsSync(e))return null;try{return JSON.parse(s.readFileSync(e,"utf-8"))}catch{return null}}function nt(t,n){let e=a.join(p(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 rt(t,n=6e4){if(!t.lastPoll)return  true;let e=new Date(t.lastPoll).getTime();return Date.now()-e>n}function st(){let n=R().filter(e=>T(e.pid));try{let e=a.join(v.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(f=>f.pid===u)&&T(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 P(t){return a.join(p(t),"inbox.jsonl")}function b(t){return a.join(p(t),"outbox.jsonl")}function J(t){return a.join(p(t),"ack.json")}function O(t,n){A(t),N(P(t),n);}function it(t,n){let e=x(P(t));if(!n){let i=$(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 Q(t,n){A(t),N(b(t),n);}function ot(t){return x(b(t))}function at(t,n){let e=J(t);A(t),s.writeFileSync(e,JSON.stringify({lastAck:n}),"utf-8");}function $(t){let n=J(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8")).lastAck||null}catch{return null}}function ct(t){let n=$(t);if(!n)return 0;let e=P(t),r=x(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 j(t){return a.join(h,`${t}.json`)}function ut(t,n){d();let e="thr-"+l.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(j(e),JSON.stringify(i,null,2),"utf-8"),i}function z(t){let n=j(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8"))}catch{return null}}function ft(t){if(d(),!s.existsSync(h))return [];let n=s.readdirSync(h).filter(r=>r.endsWith(".json")),e=[];for(let r of n)try{let i=s.readFileSync(a.join(h,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(j(t),JSON.stringify(r,null,2),"utf-8"),true}function lt(t,n){return _(t,{status:"resolved",resolvedAt:new Date().toISOString(),decision:n})}function dt(t){let n=R(),e=[];for(let r of n){let i=x(P(r.id)),o=x(b(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:l.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(),Q(t.sender.id,t);let n=0;if(t.recipients&&t.recipients.length>0)for(let e of t.recipients)O(e.id,t),n++;else {let e=R();for(let r of e)r.id!==t.sender.id&&(O(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 m(t){return a.join(S,`${t}.json`)}function V(){if(!s.existsSync(M))return F;try{let t=s.readFileSync(M,"utf-8");try{return JSON.parse(t)}catch{return F}}catch{return F}}function pt(t){d();let n="freq-"+l.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(m(n),JSON.stringify(e,null,2),"utf-8"),e}function U(t){let n=m(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(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.createdAt.localeCompare(r.createdAt))}function gt(t,n,e){let r=U(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 G=[/(?: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(I=>{for(let W of G)if(W.test(I))return "[REDACTED]";return I}).join(`
`);}let u=l.createHash("sha256").update(o).digest("hex"),f={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=f,s.writeFileSync(m(t),JSON.stringify(r,null,2),"utf-8");let k=B({sender:{id:"system",name:"File Transfer",type:"human"},recipients:[r.request.requester],intent:"fileDelivery",text:`File delivered: ${r.request.filePath} (${f.size} bytes, SHA-256: ${u.slice(0,12)}...)`,threadRoot:r.request.threadRoot,symbols:[]});return k.attachments=[{name:a.basename(r.request.filePath),type:"file",content:f.content,encoding:f.encoding}],L(k),{success:!0,delivery:f}}catch(o){return {success:false,error:`Failed to read file: ${o.message}`}}}function yt(t,n){let e=U(t);if(!e||e.status!=="pending")return  false;e.status="denied",e.resolvedAt=new Date().toISOString(),e.denyReason=n,s.writeFileSync(m(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 w(t,n){let e=n.replace(/\./g,"\\.").replace(/\*\*/g,"{{GLOBSTAR}}").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/\{\{GLOBSTAR\}\}/g,".*");return new RegExp(`^${e}$`).test(t)}function ht(t,n,e){let r=n||V();if(e&&r.users[e]){for(let i of r.users[e].neverApprove)if(w(t,i))return  true}for(let i of r.defaults.neverApprove)if(w(t,i))return  true;return  false}function St(){let t=Z("pending"),n=0;for(let e of t)Date.now()-new Date(e.createdAt).getTime()>H&&(e.status="expired",e.resolvedAt=new Date().toISOString(),s.writeFileSync(m(e.request.requestId),JSON.stringify(e,null,2),"utf-8"),n++);return n}function T(t){try{return process.kill(t,0),!0}catch{return  false}}export{ht as A,St as B,C as a,X as b,Y as c,R as d,tt as e,et as f,nt as g,rt as h,st as i,O as j,it as k,ot as l,at as m,ct as n,ut as o,z as p,ft as q,lt as r,dt as s,B as t,L as u,V as v,pt as w,Z as x,gt as y,yt as z};