#!/usr/bin/env node
import {a as a$1}from'./chunk-FYDRENK7.js';import {f,a}from'./chunk-HXGYVS2N.js';import {e}from'./chunk-AO7ZSRME.js';import {b,d,c}from'./chunk-EKZDFEJW.js';import*as h from'fs';import*as A from'path';import*as R from'js-yaml';import {glob}from'glob';import {EventEmitter}from'events';var H=/[#$^!~][a-zA-Z0-9_-]+/g;function V(r){let e=r.match(H)||[];return [...new Set(e)]}function G(r){let e=r.charAt(0);return {"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"}[e]||"unknown"}async function M(r,e,s,t){let o=A.join(s,".paradigm"),n=V(e),a=K(r,t),c=W(a.include||[],n),l=a.exclude||[],p=await J(s,c,l);return {systemPrompt:await Y(r,o,n),files:p,symbols:n}}function K(r,e){return e?.contextInclude||e?.contextExclude?{include:e.contextInclude,exclude:e.contextExclude}:{architect:{include:["specs/*.md",".purpose","**/.purpose","portal.yaml",".paradigm/config.yaml"],exclude:["src/**","tests/**","node_modules/**","dist/**"]},builder:{include:["src/**","tests/**","{feature}.purpose","specs/{feature}.md"],exclude:["specs/*.md","node_modules/**","dist/**"]},reviewer:{include:["src/**","specs/*.md","portal.yaml",".purpose"],exclude:["tests/**","node_modules/**","dist/**"]},tester:{include:["tests/**","health.yaml","{feature}.purpose"],exclude:["src/**","specs/**","node_modules/**","dist/**"]},security:{include:["portal.yaml","src/middleware/**","src/auth/**",".paradigm/wisdom/antipatterns.yaml"],exclude:["src/routes/**","tests/**","node_modules/**","dist/**"]}}[r.name]||{include:[".purpose","portal.yaml"],exclude:["node_modules/**","dist/**"]}}function W(r,e){let s=[];for(let t of r)if(t.includes("{feature}")||t.includes("{symbol}"))for(let o of e){let n=o.substring(1);s.push(t.replace(/\{feature\}/g,n).replace(/\{symbol\}/g,n));}else s.push(t);return s}async function J(r,e,s){let t=new Set;for(let o of e)try{let n=await glob(o,{cwd:r,ignore:s,nodir:!0,absolute:!1});for(let a of n)t.add(a);}catch{}return Array.from(t)}async function Y(r,e,s){let t=[],o=A.join(e,"config.yaml"),n=null;if(h.existsSync(o))try{n=R.load(h.readFileSync(o,"utf-8"));}catch{}if(t.push(`# ${r.name.charAt(0).toUpperCase()+r.name.slice(1)} Agent Context
`),n?.project&&(t.push(`> Project: ${n.project}`),n.discipline&&n.discipline!=="auto"&&t.push(`> Discipline: ${n.discipline}`),t.push("")),n?.["agent-guidelines"]?.overview&&(t.push(`## Project Overview
`),t.push(n["agent-guidelines"].overview),t.push("")),n?.["symbol-system"]){t.push(`## Symbol System
`),t.push("| Symbol | Meaning | Description |"),t.push("|--------|---------|-------------|");for(let[c,l]of Object.entries(n["symbol-system"]))t.push(`| \`${c}\` | ${l.name} | ${l.description} |`);t.push("");}if(n?.conventions){let c=Z(n.conventions,r.name);if(c.length>0){t.push(`## Conventions
`);for(let l of c)t.push(`- ${l}`);t.push("");}}if(s.length>0){t.push(`## Symbols in Scope
`);for(let c of s){let l=G(c);t.push(`- \`${c}\` (${l})`);}t.push("");}let a=q(r.name);if(a.length>0){t.push(`## Tips for This Role
`);for(let c of a)t.push(`- ${c}`);t.push("");}return t.join(`
`)}function Z(r,e){let t={architect:["design","spec","document","flow","symbol","reference"],builder:["code","implement","component","logger","test"],reviewer:["review","portal","gate","check","validate"],tester:["test","verify","health","validate"],security:["portal","gate","auth","security","vulnerability"]}[e]||[];return r.filter(o=>t.some(n=>o.toLowerCase().includes(n)))}function q(r){return {architect:["Focus on design decisions, not implementation details","Use paradigm symbols to reference features and components","Document flows that span 3+ components","Hand off to builder when spec is ready"],builder:["Follow the spec from architect exactly","If spec is unclear, ask for clarification or hand back","Use the Paradigm logger, not raw console.log","Hand off to reviewer when implementation is ready"],reviewer:["Check that all ^gate requirements are met","Verify adherence to specs","Do NOT implement fixes - hand back to builder","Approve or request changes with clear feedback"],tester:["Run tests and verify health status","Check portal validations","Update health.yaml when verified","Report issues with reproduction steps"],security:["Focus on ^gate implementations","Check for OWASP top 10 vulnerabilities","Flag issues but do NOT implement fixes","Review auth flows and session handling"]}[r]||[]}var w=class extends EventEmitter{config;usage;records=[];configPath;constructor(e){super(),this.configPath=A.join(e,".paradigm","config.yaml"),this.config=this.loadConfig(),this.usage=this.initializeUsage();}checkBudget(e,s){let t=this.estimateCost(s,"sonnet");if(this.config.maxTokens){let a=this.usage.tokens.total+s;if(a>this.config.maxTokens)return {allowed:false,reason:`Global token limit exceeded: ${d(a)} > ${d(this.config.maxTokens)}`,usage:this.usage,warningLevel:"exceeded"}}if(this.config.maxCostUsd){let a=this.usage.cost+t;if(a>this.config.maxCostUsd)return {allowed:false,reason:`Cost ceiling exceeded: ${c(a)} > ${c(this.config.maxCostUsd)}`,usage:this.usage,warningLevel:"exceeded"}}let o=this.config.agentLimits?.[e];if(o){let a=this.usage.byAgent[e]||{tokens:{total:0},cost:0};if(o.maxTokens){let c=a.tokens.total+s;if(c>o.maxTokens)return {allowed:false,reason:`Agent '${e}' token limit exceeded: ${d(c)} > ${d(o.maxTokens)}`,usage:this.usage,warningLevel:"exceeded"}}if(o.maxCostUsd){let c$1=a.cost+t;if(c$1>o.maxCostUsd)return {allowed:false,reason:`Agent '${e}' cost limit exceeded: ${c(c$1)} > ${c(o.maxCostUsd)}`,usage:this.usage,warningLevel:"exceeded"}}}let n="none";return this.config.warnAtPercent&&this.config.maxTokens&&(this.usage.tokens.total+s)/this.config.maxTokens*100>=this.config.warnAtPercent&&(n="approaching"),{allowed:true,usage:this.usage,warningLevel:n}}recordUsage(e,s,t,o){let n=b(s,t);this.usage.tokens.input+=s.input,this.usage.tokens.output+=s.output,this.usage.tokens.total+=s.total,this.usage.cost+=n,this.config.maxTokens&&(this.usage.percentage=this.usage.tokens.total/this.config.maxTokens*100),this.usage.byAgent[e]||(this.usage.byAgent[e]={tokens:{input:0,output:0,total:0},cost:0}),this.usage.byAgent[e].tokens.input+=s.input,this.usage.byAgent[e].tokens.output+=s.output,this.usage.byAgent[e].tokens.total+=s.total,this.usage.byAgent[e].cost+=n;let a={timestamp:new Date().toISOString(),agent:e,model:t,tokens:s,cost:n,orchestrationId:o};this.records.push(a),this.emit("usage",{agent:e,tokens:s,cost:n,total:this.usage}),this.config.warnAtPercent&&this.usage.percentage>=this.config.warnAtPercent&&this.emit("warning",{type:"budget_approaching",percentage:this.usage.percentage,usage:this.usage});}getUsage(){return {...this.usage}}getRecords(){return [...this.records]}getRemaining(){return {tokens:this.config.maxTokens?this.config.maxTokens-this.usage.tokens.total:null,cost:this.config.maxCostUsd?this.config.maxCostUsd-this.usage.cost:null}}reset(){this.usage=this.initializeUsage(),this.records=[];}estimateCost(e,s){let t={input:Math.floor(e/2),output:Math.ceil(e/2),total:e};return b(t,s)}estimateTime(e,s){return Math.ceil(e/{opus:50,sonnet:100,haiku:200}[s])*1e3}getSummary(){let e=[];if(e.push("Budget Summary:"),e.push(`  Tokens: ${d(this.usage.tokens.total)}`),e.push(`  Cost: ${c(this.usage.cost)}`),this.config.maxTokens&&e.push(`  Token limit: ${d(this.config.maxTokens)} (${this.usage.percentage.toFixed(1)}% used)`),this.config.maxCostUsd){let s=this.usage.cost/this.config.maxCostUsd*100;e.push(`  Cost limit: ${c(this.config.maxCostUsd)} (${s.toFixed(1)}% used)`);}if(Object.keys(this.usage.byAgent).length>0){e.push("  By agent:");for(let[s,t]of Object.entries(this.usage.byAgent))e.push(`    ${s}: ${d(t.tokens.total)} (${c(t.cost)})`);}return e.join(`
`)}loadConfig(){let e={maxTokens:5e5,maxCostUsd:5,warnAtPercent:80};if(!h.existsSync(this.configPath))return e;try{let s=h.readFileSync(this.configPath,"utf-8"),o=R.load(s).orchestration;if(o?.budget){let n=o.budget;return {maxTokens:n.max_tokens,maxCostUsd:n.max_cost_usd,warnAtPercent:n.warn_at_percent,agentLimits:o.agent_limits}}return e}catch{return e}}initializeUsage(){return {tokens:{input:0,output:0,total:0},cost:0,percentage:0,byAgent:{}}}};var F=class{provider=null;budgetTracker=null;auditLogger=null;rootDir;constructor(e){this.rootDir=e;}async initialize(){await f(),this.provider=a(),this.budgetTracker=new w(this.rootDir),this.auditLogger=new a$1(this.rootDir);}isReady(){return this.provider!==null}getProvider(){return this.provider}async spawn(e$1,s,t={}){if(!this.provider)return {success:false,error:"Spawner not initialized",sessionId:""};let o=e(this.rootDir);if(!o)return {success:false,error:"Team not configured. Run `paradigm team init` first.",sessionId:""};let n=o.agents[e$1];if(!n)return {success:false,error:`Unknown agent: ${e$1}. Available: ${Object.keys(o.agents).join(", ")}`,sessionId:""};let a$1=t.provider||this.provider.name,c=a(a$1);if(!c)return {success:false,error:`Provider '${a$1}' not available`,sessionId:""};if(!await c.isAvailable())return {success:false,error:`Provider '${a$1}' not configured (missing API key?)`,sessionId:""};let p=this.generateSessionId(e$1),k=this.loadFacetConfig(e$1),P=await M(n,s,this.rootDir,k),y=t.model||k?.defaultModel||"sonnet",O={model:y,task:s,context:P,budget:t.budget,mcpServerPath:t.mcpServerPath,workingDirectory:t.workingDirectory||this.rootDir,checkpoints:t.checkpoints,timeout:t.timeout},S=Date.now(),B=new Date().toISOString(),i={agent:e$1,task:s,status:"success",completionVerified:false,outputs:{artifacts:[],symbols:P.symbols,decisions:[]},metrics:{tokens_used:{input:0,output:0,total:0},duration_ms:0,files_read:0,files_written:0}};try{for await(let u of c.spawn(n,O)){if(u.usage&&(i.metrics.tokens_used=u.usage),u.type==="tool_use"){if(u.toolName==="read_file")i.metrics.files_read++;else if(u.toolName==="write_file"){i.metrics.files_written++;let f=u.toolInput?.path;f&&i.outputs.artifacts.push({path:f,action:"modified"});}}if(t.checkpoints&&u.type==="tool_use"&&this.shouldPauseForCheckpoint(u,t.checkpoints)&&t.onCheckpoint&&!await t.onCheckpoint(`Agent wants to ${u.toolName}: ${JSON.stringify(u.toolInput)}`)){i.status="blocked";break}if(t.onMessage&&t.onMessage(u),u.type==="error"&&(i.status="failed"),this.budgetTracker&&u.usage&&!this.budgetTracker.checkBudget(e$1,u.usage.total).allowed){i.status="failed";break}}if(i.metrics.duration_ms=Date.now()-S,this.budgetTracker&&this.budgetTracker.recordUsage(e$1,i.metrics.tokens_used,y),i.status==="success"){let u=i.outputs.artifacts.length>0,f=i.outputs.decisions.length>0,C=!!i.handoff,T=i.metrics.files_written>0,z=e$1==="architect";(e$1==="builder"&&!T&&!C||!u&&!f&&!C&&!T)&&(i.status="partial"),i.completionVerified=!0,i.status==="partial"&&!z&&t.onMessage&&t.onMessage({type:"text",content:`[completion-check] Agent "${e$1}" downgraded from success \u2192 partial: no meaningful output detected.`,timestamp:new Date().toISOString()});}if(this.auditLogger){let u={name:e$1,model:y,started:B,completed:new Date().toISOString(),duration_ms:i.metrics.duration_ms,tokens:i.metrics.tokens_used,cost_usd:b(i.metrics.tokens_used,y),status:i.status,artifacts:i.outputs.artifacts,symbols:i.outputs.symbols};this.auditLogger.logAgentCompletion(p,u);}return {success:i.status==="success"||i.status==="partial",relay:i,sessionId:p}}catch(u){return {success:false,error:u instanceof Error?u.message:String(u),sessionId:p,relay:{...i,status:"failed",metrics:{...i.metrics,duration_ms:Date.now()-S}}}}}async spawnParallel(e){let s=e.map(({name:t,task:o,options:n})=>this.spawn(t,o,n));return Promise.all(s)}generateSessionId(e){let s=Date.now(),t=Math.random().toString(36).substring(2,8);return `${e}-${s}-${t}`}loadFacetConfig(e){let s=A.join(this.rootDir,".paradigm","facets.yaml");if(!h.existsSync(s))return {architect:{defaultModel:"opus"},security:{defaultModel:"opus"},reviewer:{defaultModel:"sonnet"},builder:{defaultModel:"haiku"},tester:{defaultModel:"haiku"}}[e];try{let t=h.readFileSync(s,"utf-8");return R.load(t)[e]}catch{return}}shouldPauseForCheckpoint(e,s){if(!s.beforeActions||e.type!=="tool_use")return  false;let t={write:["write_file","edit_file"],delete:["delete_file","rm"],execute:["run_command","bash"],external_api:["mcp_call","http_request"]};for(let o of s.beforeActions){let n=t[o]||[];if(e.toolName&&n.includes(e.toolName))return  true}return  false}};export{V as a,F as b};