#!/usr/bin/env node
import {a}from'./chunk-7SWEOPWF.js';import {a as a$1}from'./chunk-MBPLJKE5.js';import*as s from'fs';import*as o from'path';import*as x from'os';import*as l from'crypto';function Y(t){return t.contentType!==void 0&&a.includes(t.contentType)}function st(t,n,e){try{let r={id:l.randomUUID(),timestamp:new Date().toISOString(),agent:t,boundary:e,data_category:n.contentType,action:"blocked",destination_ring:"network-public",details:n.id},i=o.join(x.homedir(),".paradigm","events","audit-ring1.jsonl");F(i,r);}catch(r){a$1.component("#symphony-loader").warn(`Ring 1 audit write failed: ${r}`);}}var g=o.join(x.homedir(),".paradigm","score"),D=o.join(x.homedir(),".paradigm","mail"),y=o.join(g,"agents"),h=o.join(g,"threads"),S=o.join(g,"file-requests"),w=o.join(g,"trust.yaml"),Q=3600*1e3,P={users:{},defaults:{level:"restricted",autoApprove:[],neverApprove:[".env*","**/*.key","**/*.pem","**/credentials*","**/secrets/**"]}};function V(){if(s.existsSync(D)&&!s.existsSync(g))try{s.renameSync(D,g);}catch{}}function d(){V();for(let t of [y,h,S])s.existsSync(t)||s.mkdirSync(t,{recursive:true});}function p(t){return o.join(y,t)}function R(t){let n=p(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 F(t,n){let e=o.dirname(t);s.existsSync(e)||s.mkdirSync(e,{recursive:true}),s.appendFileSync(t,JSON.stringify(n)+`
`,"utf-8");}function N(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"unknown"}function J(t){try{let n=o.join(t,".paradigm","config.yaml");if(s.existsSync(n)){let r=s.readFileSync(n,"utf-8").match(/^project:\s*(.+)$/m);if(r)return N(r[1].trim().replace(/["']/g,""))}}catch{}return N(o.basename(t))}function $(t,n){return `${J(t)}/${n||"core"}`}function it(t,n,e){d();let r=$(t,n),i=R(r),a=J(t),c={id:r,name:e||`${a} (${n||"core"})`,type:"agent",project:a,role:n||"core",pid:process.pid,startedAt:new Date().toISOString(),label:e};return s.writeFileSync(o.join(i,"identity.json"),JSON.stringify(c,null,2),"utf-8"),c}function Z(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 A(){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=o.join(y,e.name),i=s.readdirSync(r,{withFileTypes:true}).filter(a=>a.isDirectory());for(let a of i){let c=o.join(r,a.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 ot(){let t=A(),n=0;for(let e of t)b(e.pid)||(Z(e.id),n++);return n}function at(t){let n=$(t),e=o.join(p(n),"identity.json");if(!s.existsSync(e))return null;try{return JSON.parse(s.readFileSync(e,"utf-8"))}catch{return null}}function ct(t,n){let e=o.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 ut(t,n=6e4){if(!t.lastPoll)return  true;let e=new Date(t.lastPoll).getTime();return Date.now()-e>n}function ft(){let n=A().filter(e=>b(e.pid));try{let e=o.join(x.homedir(),".conductor","sessions");if(s.existsSync(e)){let r=s.readdirSync(e).filter(i=>i.endsWith(".json"));for(let i of r)try{let a=s.readFileSync(o.join(e,i),"utf-8"),c=JSON.parse(a),u=parseInt(o.basename(i,".json"),10);!n.some(f=>f.pid===u)&&b(u)&&n.push({id:`conductor/${u}`,name:c.label||`Session ${u}`,type:"agent",project:c.projectDir?o.basename(c.projectDir):"unknown",role:"conductor",pid:u,startedAt:c.registeredAt||new Date().toISOString()});}catch{}}}catch{}return n}function T(t){return o.join(p(t),"inbox.jsonl")}function I(t){return o.join(p(t),"outbox.jsonl")}function _(t){return o.join(p(t),"ack.json")}function E(t,n){R(t),F(T(t),n);}function lt(t,n){let e=m(T(t));if(!n){let i=z(t);if(i){let a=e.findIndex(c=>c.id===i);if(a>=0)return e.slice(a+1)}return e}let r=e.findIndex(i=>i.id===n);return r>=0?e.slice(r+1):e}function X(t,n){R(t),F(I(t),n);}function dt(t){return m(I(t))}function pt(t,n){let e=_(t);R(t),s.writeFileSync(e,JSON.stringify({lastAck:n}),"utf-8");}function z(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 gt(t){let n=z(t);if(!n)return 0;let e=T(t),r=m(e),i=r.findIndex(u=>u.id===n);if(i<0)return 0;let a=r.slice(i+1),c=r.length-a.length;return a.length===0?s.existsSync(e)&&s.writeFileSync(e,"","utf-8"):s.writeFileSync(e,a.map(u=>JSON.stringify(u)).join(`
`)+`
`,"utf-8"),c}function j(t){return o.join(h,`${t}.json`)}function yt(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 B(t){let n=j(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8"))}catch{return null}}function ht(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(o.join(h,r),"utf-8"),a=JSON.parse(i);(!t||a.status===t)&&e.push(a);}catch{}return e.sort((r,i)=>i.lastActivity.localeCompare(r.lastActivity))}function L(t,n){let e=B(t);if(!e)return  false;let r={...e,...n};return s.writeFileSync(j(t),JSON.stringify(r,null,2),"utf-8"),true}function St(t,n){return L(t,{status:"resolved",resolvedAt:new Date().toISOString(),decision:n})}function mt(t){let n=A(),e=[];for(let r of n){let i=m(T(r.id)),a=m(I(r.id));for(let c of [...i,...a])(c.threadRoot===t||c.id===t)&&!e.some(u=>u.id===c.id)&&!Y(c)&&e.push(c);}return e.sort((r,i)=>r.timestamp.localeCompare(i.timestamp))}function U(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 G(t){d(),X(t.sender.id,t);let n=0;if(t.recipients&&t.recipients.length>0)for(let e of t.recipients)E(e.id,t),n++;else {let e=A();for(let r of e)r.id!==t.sender.id&&(E(r.id,t),n++);}if(t.threadRoot){let e=B(t.threadRoot);if(e){let i=e.participants.some(a=>a.id===t.sender.id)?e.participants:[...e.participants,t.sender];L(t.threadRoot,{participants:i,lastActivity:t.timestamp,messageCount:e.messageCount+1});}}return n}function v(t){return o.join(S,`${t}.json`)}function tt(){if(!s.existsSync(w))return P;try{let t=s.readFileSync(w,"utf-8");try{return JSON.parse(t)}catch{return P}}catch{return P}}function xt(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(v(n),JSON.stringify(e,null,2),"utf-8"),e}function W(t){let n=v(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8"))}catch{return null}}function et(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(o.join(S,r),"utf-8"),a=JSON.parse(i);(!t||a.status===t)&&e.push(a);}catch{}return e.sort((r,i)=>i.createdAt.localeCompare(r.createdAt))}function vt(t,n,e){let r=W(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=o.resolve(n,r.request.filePath);if(!i.startsWith(o.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 a=s.readFileSync(i,"utf-8"),c="utf8";if(e){let H=[/(?: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-----/];a=a.split(`
`).map(q=>{for(let K of H)if(K.test(q))return "[REDACTED]";return q}).join(`
`);}let u=l.createHash("sha256").update(a).digest("hex"),f={requestId:t,filePath:r.request.filePath,content:a,encoding:c,size:Buffer.byteLength(a),hash:u};r.status="approved",r.resolvedAt=new Date().toISOString(),r.delivery=f,s.writeFileSync(v(t),JSON.stringify(r,null,2),"utf-8");let k=U({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:o.basename(r.request.filePath),type:"file",content:f.content,encoding:f.encoding}],G(k),{success:!0,delivery:f}}catch(a){return {success:false,error:`Failed to read file: ${a.message}`}}}function Rt(t,n){let e=W(t);if(!e||e.status!=="pending")return  false;e.status="denied",e.resolvedAt=new Date().toISOString(),e.denyReason=n,s.writeFileSync(v(t),JSON.stringify(e,null,2),"utf-8");let r=U({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 G(r),true}function C(t,n){let e=n.replace(/\./g,"\\.").replace(/\*\*/g,"{{GLOBSTAR}}").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/\{\{GLOBSTAR\}\}/g,".*");return new RegExp(`^${e}$`).test(t)}function At(t,n,e){let r=n||tt();if(e&&r.users[e]){for(let i of r.users[e].neverApprove)if(C(t,i))return  true}for(let i of r.defaults.neverApprove)if(C(t,i))return  true;return  false}function Tt(){let t=et("pending"),n=0;for(let e of t)Date.now()-new Date(e.createdAt).getTime()>Q&&(e.status="expired",e.resolvedAt=new Date().toISOString(),s.writeFileSync(v(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{vt as A,Rt as B,At as C,Tt as D,Y as a,st as b,$ as c,it as d,Z as e,A as f,ot as g,at as h,ct as i,ut as j,ft as k,E as l,lt as m,dt as n,pt as o,gt as p,yt as q,B as r,ht as s,St as t,mt as u,U as v,G as w,tt as x,xt as y,et as z};