@directive-run/ai 0.1.1
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/LICENSE +21 -0
- package/README.md +146 -0
- package/dist/anthropic.cjs +3 -0
- package/dist/anthropic.cjs.map +1 -0
- package/dist/anthropic.d.cts +103 -0
- package/dist/anthropic.d.ts +103 -0
- package/dist/anthropic.js +3 -0
- package/dist/anthropic.js.map +1 -0
- package/dist/index.cjs +78 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +4663 -0
- package/dist/index.d.ts +4663 -0
- package/dist/index.js +78 -0
- package/dist/index.js.map +1 -0
- package/dist/ollama.cjs +3 -0
- package/dist/ollama.cjs.map +1 -0
- package/dist/ollama.d.cts +47 -0
- package/dist/ollama.d.ts +47 -0
- package/dist/ollama.js +3 -0
- package/dist/ollama.js.map +1 -0
- package/dist/openai.cjs +3 -0
- package/dist/openai.cjs.map +1 -0
- package/dist/openai.d.cts +127 -0
- package/dist/openai.d.ts +127 -0
- package/dist/openai.js +3 -0
- package/dist/openai.js.map +1 -0
- package/dist/testing.cjs +14 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +345 -0
- package/dist/testing.d.ts +345 -0
- package/dist/testing.js +14 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-BKCdgKC-.d.cts +300 -0
- package/dist/types-BKCdgKC-.d.ts +300 -0
- package/package.json +83 -0
package/dist/testing.cjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
'use strict';var adapterUtils=require('@directive-run/core/adapter-utils'),core=require('@directive-run/core');require('@directive-run/core/plugins');var N=class extends Error{code;guardrailName;guardrailType;userMessage;agentName;constructor(t){super(t.message,{cause:t.cause}),this.name="GuardrailError",this.code=t.code,this.guardrailName=t.guardrailName,this.guardrailType=t.guardrailType,this.userMessage=t.userMessage??t.message,this.agentName=t.agentName,Object.defineProperty(this,"input",{value:t.input,enumerable:false,writable:false,configurable:false}),Object.defineProperty(this,"data",{value:t.data,enumerable:false,writable:false,configurable:false});}toJSON(){return {name:this.name,code:this.code,message:this.message,guardrailName:this.guardrailName,guardrailType:this.guardrailType,userMessage:this.userMessage,agentName:this.agentName}}};var Z="__agent",Y="__approval",ee="__conversation",te="__toolCalls",ye={facts:{[Z]:core.t.any(),[Y]:core.t.any(),[ee]:core.t.any(),[te]:core.t.any()}};function L(r){return adapterUtils.getBridgeFact(r,Z)}function I(r,t){adapterUtils.setBridgeFact(r,Z,t);}function J(r){return adapterUtils.getBridgeFact(r,Y)}function H(r,t){adapterUtils.setBridgeFact(r,Y,t);}function se(r){return adapterUtils.getBridgeFact(r,ee)}function re(r,t){adapterUtils.setBridgeFact(r,ee,t);}function ie(r){return adapterUtils.getBridgeFact(r,te)}function ae(r,t){adapterUtils.setBridgeFact(r,te,t);}function W(r){return {agent:L(r),approval:J(r),conversation:se(r),toolCalls:ie(r)}}function xe(r){let t={};for(let[u,s]of Object.entries(r))t[u]={priority:s.priority??0,when:i=>{let a=W(i),n={...i,...a};return s.when(n)},require:i=>{let a=W(i),n={...i,...a};return typeof s.require=="function"?s.require(n):s.require}};return t}function Ge(r,t,u){let s={};for(let[i,a]of Object.entries(r))s[i]={requirement:a.requirement,key:a.key,resolve:async(n,R)=>{let l=W(R.facts),T={facts:{...R.facts,...l},runAgent:async(b,v,P)=>t(b,v,Ee(u()),P),signal:R.signal};await a.resolve(n,T);}};return s}function Ee(r){return W(r)}function V(r,t,u){return typeof r=="function"?{name:`${u}-guardrail-${t}`,fn:r,critical:true}:r}function Me(r,t){let{backoff:u="exponential",baseDelayMs:s=100,maxDelayMs:i=5e3}=t,a;switch(u){case "exponential":a=s*Math.pow(2,r-1);break;case "linear":a=s*r;break;default:a=s;}return Math.min(a,i)}async function K(r,t,u){let{retry:s}=r,i=s?.attempts??1,a;for(let n=1;n<=i;n++)try{return await r.fn(t,u)}catch(R){if(a=R instanceof Error?R:new Error(String(R)),n<i){let l=Me(n,s??{});await new Promise(d=>setTimeout(d,l));}}throw a}function De(r,t){let{backoff:u="exponential",baseDelayMs:s=1e3,maxDelayMs:i=3e4}=t,a;switch(u){case "exponential":a=s*Math.pow(2,r-1);break;case "linear":a=s*r;break;default:a=s;}return Math.min(a,i)}async function Re(r,t,u,s,i){let a=i?.attempts??1,n=i?.isRetryable??(()=>true),R=i?.onRetry,l;for(let d=1;d<=a;d++)try{return await r(t,u,s)}catch(T){if(l=T instanceof Error?T:new Error(String(T)),d<a&&n(l)){let b=De(d,i??{});R?.(d,l,b),await new Promise(v=>setTimeout(v,b));}else break}throw l}function he(r){let{runner:t,factsSchema:u={},init:s,constraints:i={},resolvers:a={},guardrails:n={},onApprovalRequest:R,autoApproveToolCalls:l=true,maxTokenBudget:d,plugins:T=[],debug:b=false,approvalTimeoutMs:v=3e5,agentRetry:P,hooks:F={},memory:D,circuitBreaker:ue}=r;if(!l&&!R)throw new Error(`[Directive] Invalid approval configuration: autoApproveToolCalls is false but no onApprovalRequest callback provided. Tool calls would wait for approval indefinitely. Either:
|
|
2
|
+
- Set autoApproveToolCalls: true to auto-approve all tool calls
|
|
3
|
+
- Provide an onApprovalRequest callback to handle approvals programmatically`);let Ae={facts:{...ye.facts,...u},derivations:{},events:{},requirements:{}},le,o,ce=xe(i);d&&(ce.__budgetLimit={priority:100,when:e=>L(e).tokenUsage>d,require:{type:"__PAUSE_BUDGET_EXCEEDED"}});let pe=Ge(a,(e,c,y,A)=>le(e,c,y,A),()=>o.facts);pe.__pause={requirement:adapterUtils.requirementGuard("__PAUSE_BUDGET_EXCEEDED"),resolve:async(e,c)=>{let y=L(c.facts);I(c.facts,{...y,status:"paused"});}};let ve=adapterUtils.createCallbackPlugin("openai-agents-callbacks",{}),Ce=core.createModule("openai-agents-orchestrator",{schema:Ae,init:e=>{if(I(e,{status:"idle",currentAgent:null,input:null,output:null,error:null,tokenUsage:0,turnCount:0,startedAt:null,completedAt:null}),H(e,{pending:[],approved:[],rejected:[]}),re(e,[]),ae(e,[]),s){let c=W(e),y={...e,...c};s(y);}},constraints:ce,resolvers:pe});o=core.createSystem({module:Ce,plugins:[...T,ve],debug:b?{timeTravel:true}:void 0}),o.start();async function de(e,c,y,A,k){return ue?ue.execute(()=>ge(e,c,y,A,k)):ge(e,c,y,A,k)}async function ge(e,c,y,A,k){let w=Date.now();if(D){let m=D.getContextMessages();if(m.length>0){let g=m.map(x=>`${x.role}: ${x.content}`).join(`
|
|
4
|
+
`);e={...e,instructions:(e.instructions??"")+`
|
|
5
|
+
|
|
6
|
+
Conversation context:
|
|
7
|
+
`+g};}}F.onAgentStart?.({agentName:e.name,input:c,timestamp:w});let E=k?.inputGuardrails!==void 0?k.inputGuardrails:n.input??[],$=k?.outputGuardrails!==void 0?k.outputGuardrails:n.output??[],_=E.map((m,g)=>V(m,g,"input"));for(let m of _){let{name:g}=m,x={agentName:e.name,input:c,facts:o.facts.$store.toObject()},M=Date.now(),h=await K(m,{input:c,agentName:e.name},x);if(F.onGuardrailCheck?.({guardrailName:g,guardrailType:"input",passed:h.passed,reason:h.reason,durationMs:Date.now()-M,timestamp:Date.now()}),!h.passed)throw new N({code:"INPUT_GUARDRAIL_FAILED",message:`Input guardrail "${g}" failed: ${h.reason}`,guardrailName:g,guardrailType:"input",userMessage:h.reason??"Input validation failed",agentName:e.name,input:c});h.transformed!==void 0&&(c=h.transformed);}o.batch(()=>{let m=L(o.facts);I(o.facts,{...m,status:"running",currentAgent:e.name,input:c,startedAt:Date.now()});});let O=await Re(t,e,c,{...A,signal:A?.signal,onMessage:m=>{let g=se(o.facts);re(o.facts,[...g,m]),A?.onMessage?.(m);},onToolCall:async m=>{let g=(n.toolCall??[]).map((M,h)=>V(M,h,"toolCall"));for(let M of g){let{name:h}=M,f={agentName:e.name,input:c,facts:o.facts.$store.toObject()},q=Date.now(),S=await K(M,{toolCall:m,agentName:e.name,input:c},f);if(F.onGuardrailCheck?.({guardrailName:h,guardrailType:"toolCall",passed:S.passed,reason:S.reason,durationMs:Date.now()-q,timestamp:Date.now()}),!S.passed)throw new N({code:"TOOL_CALL_GUARDRAIL_FAILED",message:`Tool call guardrail "${h}" failed: ${S.reason}`,guardrailName:h,guardrailType:"toolCall",userMessage:S.reason??"Tool call blocked",data:{toolCall:m},agentName:e.name,input:c})}if(!l){let M=`tool-${m.id}`,h={id:M,type:"tool_call",agentName:e.name,description:`Tool call: ${m.name}`,data:m,requestedAt:Date.now()};o.batch(()=>{let f=J(o.facts);H(o.facts,{...f,pending:[...f.pending,h]});}),R?.(h),await me(M);}let x=ie(o.facts);ae(o.facts,[...x,m]),A?.onToolCall?.(m);}},P?{...P,onRetry:(m,g,x)=>{P.onRetry?.(m,g,x),F.onAgentRetry?.({agentName:e.name,input:c,attempt:m,error:g,delayMs:x,timestamp:Date.now()});}}:void 0),U=$.map((m,g)=>V(m,g,"output"));for(let m of U){let{name:g}=m,x={agentName:e.name,input:c,facts:o.facts.$store.toObject()},M=Date.now(),h=await K(m,{output:O.output,agentName:e.name,input:c,messages:O.messages},x);if(F.onGuardrailCheck?.({guardrailName:g,guardrailType:"output",passed:h.passed,reason:h.reason,durationMs:Date.now()-M,timestamp:Date.now()}),!h.passed)throw new N({code:"OUTPUT_GUARDRAIL_FAILED",message:`Output guardrail "${g}" failed: ${h.reason}`,guardrailName:g,guardrailType:"output",userMessage:h.reason??"Output validation failed",agentName:e.name,input:c});h.transformed!==void 0&&(O.output=h.transformed);}return o.batch(()=>{let m=L(o.facts);I(o.facts,{...m,status:"completed",output:O.output,tokenUsage:m.tokenUsage+O.totalTokens,turnCount:m.turnCount+O.messages.length,completedAt:Date.now()});}),D&&O.messages.length>0&&D.addMessages(O.messages),F.onAgentComplete?.({agentName:e.name,input:c,output:O.output,tokenUsage:O.totalTokens,durationMs:Date.now()-w,timestamp:Date.now()}),O}le=de;function me(e){return new Promise((c,y)=>{let A=null,k=()=>{A&&(clearTimeout(A),A=null);},w=o.facts.$store.subscribe([Y],()=>{let E=J(o.facts);if(E.approved.includes(e))k(),w(),c();else {let $=E.rejected.find(_=>_.id===e);if($){k(),w();let _=$.reason?`Request ${e} rejected: ${$.reason}`:`Request ${e} rejected`;y(new Error(_));}}});A=setTimeout(()=>{w();let E=Math.round(v/1e3);y(new Error(`[Directive] Approval timeout: Request ${e} not resolved within ${E}s.
|
|
8
|
+
Solutions:
|
|
9
|
+
1. Handle via onApprovalRequest callback and call orchestrator.approve()/reject()
|
|
10
|
+
2. Set autoApproveToolCalls: true to auto-approve
|
|
11
|
+
3. Increase approvalTimeoutMs (current: ${v}ms)
|
|
12
|
+
See: https://directive.run/docs/ai/running-agents`));},v);})}function fe(){return {...W(o.facts)}}return {system:o,get facts(){return fe()},async run(e,c,y){return de(e,c,fe(),void 0,y)},runStream(e,c,y={}){let A=new AbortController,k=[],w=[],E=false,$=Date.now(),_=0,O="",U;y.signal&&(U=()=>A.abort(),y.signal.addEventListener("abort",U));let m=()=>{U&&y.signal&&y.signal.removeEventListener("abort",U);},g=f=>{if(E)return;let q=w.shift();q?q(f):k.push(f);},x=()=>{E=true,m();for(let f of w)f(null);w.length=0;},M=(async()=>{g({type:"progress",phase:"starting",message:"Running input guardrails"});try{let f=c,q=(n.input??[]).map((p,G)=>V(p,G,"input"));for(let p of q){let{name:G}=p,j={agentName:e.name,input:f,facts:o.facts.$store.toObject()},C=await K(p,{input:f,agentName:e.name},j);if(!C.passed)throw g({type:"guardrail_triggered",guardrailName:G,reason:C.reason??"Input validation failed",partialOutput:O,stopped:!0}),new N({code:"INPUT_GUARDRAIL_FAILED",message:`Input guardrail "${G}" failed: ${C.reason}`,guardrailName:G,guardrailType:"input",userMessage:C.reason??"Input validation failed",agentName:e.name,input:f});C.transformed!==void 0&&(f=C.transformed);}g({type:"progress",phase:"generating",message:"Starting agent"}),o.batch(()=>{let p=L(o.facts);I(o.facts,{...p,status:"running",currentAgent:e.name,input:f,startedAt:Date.now()});});let S=await Re(t,e,f,{signal:A.signal,onMessage:p=>{let G=se(o.facts);if(re(o.facts,[...G,p]),g({type:"message",message:p}),p.role==="assistant"&&p.content){let j=Math.ceil(p.content.length/4);_+=j,O+=p.content,g({type:"token",data:p.content,tokenCount:_});}},onToolCall:async p=>{g({type:"tool_start",tool:p.name,toolCallId:p.id,arguments:p.arguments});let G=(n.toolCall??[]).map((C,B)=>V(C,B,"toolCall"));for(let C of G){let{name:B}=C,X={agentName:e.name,input:f,facts:o.facts.$store.toObject()},z=await K(C,{toolCall:p,agentName:e.name,input:f},X);if(!z.passed)throw g({type:"guardrail_triggered",guardrailName:B,reason:z.reason??"Tool call blocked",partialOutput:O,stopped:!0}),new N({code:"TOOL_CALL_GUARDRAIL_FAILED",message:`Tool call guardrail "${B}" failed: ${z.reason}`,guardrailName:B,guardrailType:"toolCall",userMessage:z.reason??"Tool call blocked",data:{toolCall:p},agentName:e.name,input:f})}if(!l){let C=`tool-${p.id}`;g({type:"approval_required",requestId:C,toolName:p.name});let B={id:C,type:"tool_call",agentName:e.name,description:`Tool call: ${p.name}`,data:p,requestedAt:Date.now()};o.batch(()=>{let X=J(o.facts);H(o.facts,{...X,pending:[...X.pending,B]});}),R?.(B),await me(C),g({type:"approval_resolved",requestId:C,approved:!0});}let j=ie(o.facts);ae(o.facts,[...j,p]),p.result&&g({type:"tool_end",tool:p.name,toolCallId:p.id,result:p.result});}},P);g({type:"progress",phase:"finishing",message:"Running output guardrails"});let Te=(n.output??[]).map((p,G)=>V(p,G,"output"));for(let p of Te){let{name:G}=p,j={agentName:e.name,input:f,facts:o.facts.$store.toObject()},C=await K(p,{output:S.output,agentName:e.name,input:f,messages:S.messages},j);if(!C.passed)throw g({type:"guardrail_triggered",guardrailName:G,reason:C.reason??"Output validation failed",partialOutput:typeof S.output=="string"?S.output:"",stopped:!0}),new N({code:"OUTPUT_GUARDRAIL_FAILED",message:`Output guardrail "${G}" failed: ${C.reason}`,guardrailName:G,guardrailType:"output",userMessage:C.reason??"Output validation failed",agentName:e.name,input:f});C.transformed!==void 0&&(S.output=C.transformed);}o.batch(()=>{let p=L(o.facts);I(o.facts,{...p,status:"completed",output:S.output,tokenUsage:p.tokenUsage+S.totalTokens,turnCount:p.turnCount+S.messages.length,completedAt:Date.now()});});let ke=Date.now()-$;return g({type:"done",totalTokens:S.totalTokens,duration:ke,droppedTokens:0}),x(),S}catch(f){throw g({type:"error",error:f instanceof Error?f:new Error(String(f))}),x(),f}})();return {stream:{[Symbol.asyncIterator](){return {async next(){return k.length>0?{done:false,value:k.shift()}:E?{done:true,value:void 0}:new Promise(f=>{w.push(q=>{f(q===null?{done:true,value:void 0}:{done:false,value:q});});})}}}},result:M,abort:()=>{A.abort(),x();}}},approve(e){o.batch(()=>{let c=J(o.facts);if(!c.pending.some(k=>k.id===e)){b&&console.debug(`[Directive] approve() ignored: no pending request "${e}"`);return}let y=200,A=[...c.approved,e];H(o.facts,{...c,pending:c.pending.filter(k=>k.id!==e),approved:A.length>y?A.slice(-y):A});});},reject(e,c){o.batch(()=>{let y=J(o.facts);if(!y.pending.some(E=>E.id===e)){b&&console.debug(`[Directive] reject() ignored: no pending request "${e}"`);return}c&&b&&console.debug(`[Directive] Request ${e} rejected: ${c}`);let A={id:e,reason:c,rejectedAt:Date.now()},k=200,w=[...y.rejected,A];H(o.facts,{...y,pending:y.pending.filter(E=>E.id!==e),rejected:w.length>k?w.slice(-k):w});});},pause(){let e=L(o.facts);I(o.facts,{...e,status:"paused"});},resume(){let e=L(o.facts);e.status==="paused"&&I(o.facts,{...e,status:e.currentAgent?"running":"idle"});},reset(){o.batch(()=>{I(o.facts,{status:"idle",currentAgent:null,input:null,output:null,error:null,tokenUsage:0,turnCount:0,startedAt:null,completedAt:null}),H(o.facts,{pending:[],approved:[],rejected:[]}),re(o.facts,[]),ae(o.facts,[]);});},dispose(){o.destroy();}}}function Pe(r={}){let{defaultResponse:t={output:"mock response",totalTokens:10},responses:u={},recordCalls:s=true,onRun:i}=r,a=[],n=new Map(Object.entries(u)),R=t;return {run:async(d,T,b)=>{i?.(d,T),s&&a.push({agent:d,input:T,options:b,timestamp:Date.now()});let v=n.get(d.name)??R;if(v.generate){let D=v.generate(T,d);v={...v,...D};}if(v.error)throw v.error;v.delay&&v.delay>0&&await new Promise(D=>setTimeout(D,v.delay));let P=v.messages??[];for(let D of P)b?.onMessage?.(D);let F=v.toolCalls??[];for(let D of F)b?.onToolCall?.(D);return {output:v.output,messages:P,toolCalls:F,totalTokens:v.totalTokens??10}},getCalls:()=>[...a],getCallsFor:d=>a.filter(T=>T.agent.name===d),clearCalls:()=>a.length=0,setResponse:(d,T)=>n.set(d,T),setDefaultResponse:d=>R=d}}async function Fe(r,t,u){let s={agentName:"test-agent",input:"",...t},i={agentName:t.agentName??"test-agent",input:t.input??"",facts:u?.facts??{},...u},a=Date.now(),n=await r(s,i),R=Date.now()-a;return {...n,duration:R,testedData:s,assertPassed(){if(!n.passed)throw new Error(`Expected guardrail to pass, but it failed: ${n.reason}`)},assertFailed(l){if(n.passed)throw new Error("Expected guardrail to fail, but it passed");if(l!==void 0){if(typeof l=="string"&&!n.reason?.includes(l))throw new Error(`Expected failure reason to include "${l}", got: ${n.reason}`);if(l instanceof RegExp&&!l.test(n.reason??""))throw new Error(`Expected failure reason to match ${l}, got: ${n.reason}`)}},assertTransformed(l){if(n.transformed===void 0)throw new Error("Expected guardrail to transform input, but no transformation occurred");if(l!==void 0&&n.transformed!==l)throw new Error(`Expected transformation to be ${JSON.stringify(l)}, got: ${JSON.stringify(n.transformed)}`)}}}async function Ze(r,t){let u=[],s=[];for(let i=0;i<t.length;i++){let a=t[i],n=await Fe(r,a.input,a.context);u.push(n),(n.passed?n.transformed!==void 0?"transform":"pass":"fail")!==a.expect&&s.push({index:i,expected:a.expect,actual:n});}return {results:u,allPassed:()=>s.length===0,failures:()=>s}}function qe(r={}){let{autoApprove:t,autoReject:u,delay:s=0,recordRequests:i=true}=r,a=[],n=new Map,R=[];return {async handle(l){i&&a.push(l);for(let d of R)d.predicate(l)&&d.resolve(l);return s>0&&await new Promise(d=>setTimeout(d,s)),u&&u(l)?"rejected":t&&t(l)?"approved":new Promise(d=>{n.set(l.id,{request:l,resolve:d});})},getRequests:()=>[...a],clearRequests:()=>a.length=0,approve(l){let d=n.get(l);d&&(d.resolve("approved"),n.delete(l));},reject(l,d){let T=n.get(l);T&&(T.resolve("rejected"),n.delete(l));},waitForRequest(l,d=5e3){let T=a.find(l);return T?Promise.resolve(T):new Promise((b,v)=>{let P=setTimeout(()=>{v(new Error("Timeout waiting for approval request"));},d);R.push({predicate:l,resolve:F=>{clearTimeout(P),b(F);}});})}}}function et(r={}){let{mockResponses:t,defaultMockResponse:u,...s}=r,i=Pe({responses:t,defaultResponse:u}),a=qe(),n=he({...s,runner:i.run,onApprovalRequest:R=>{a.handle(R),s.onApprovalRequest?.(R);}});return {...n,mockRunner:i,approvalSimulator:a,getCalls:()=>i.getCalls(),getApprovalRequests:()=>a.getRequests(),resetAll(){n.reset(),i.clearCalls(),a.clearRequests();}}}function tt(){let r=[];return {plugin:{name:"constraint-recorder",onRequirementCreated(t){r.push({constraintId:t.constraintId,triggered:true,requirement:t.requirement,facts:t.facts,timestamp:Date.now()});}},getSnapshots:()=>[...r],clearSnapshots:()=>r.length=0}}function rt(r,t){let u=r.facts;if(t.agentStatus!==void 0&&u.agent.status!==t.agentStatus)throw new Error(`Expected agent status to be "${t.agentStatus}", got "${u.agent.status}"`);if(t.tokenUsage!==void 0){let{min:s,max:i,exact:a}=t.tokenUsage;if(a!==void 0&&u.agent.tokenUsage!==a)throw new Error(`Expected token usage to be exactly ${a}, got ${u.agent.tokenUsage}`);if(s!==void 0&&u.agent.tokenUsage<s)throw new Error(`Expected token usage to be at least ${s}, got ${u.agent.tokenUsage}`);if(i!==void 0&&u.agent.tokenUsage>i)throw new Error(`Expected token usage to be at most ${i}, got ${u.agent.tokenUsage}`)}if(t.pendingApprovals!==void 0&&u.approval.pending.length!==t.pendingApprovals)throw new Error(`Expected ${t.pendingApprovals} pending approvals, got ${u.approval.pending.length}`);if(t.conversationLength!==void 0){let{min:s,max:i,exact:a}=t.conversationLength,n=u.conversation.length;if(a!==void 0&&n!==a)throw new Error(`Expected conversation length to be exactly ${a}, got ${n}`);if(s!==void 0&&n<s)throw new Error(`Expected conversation length to be at least ${s}, got ${n}`);if(i!==void 0&&n>i)throw new Error(`Expected conversation length to be at most ${i}, got ${n}`)}}function at(r=Date.now()){let t=r,u=r;return {now:()=>t,advance:s=>{t+=s;},set:s=>{t=s;},reset:()=>{t=u;}}}
|
|
13
|
+
exports.assertOrchestratorState=rt;exports.createApprovalSimulator=qe;exports.createConstraintRecorder=tt;exports.createMockAgentRunner=Pe;exports.createTestOrchestrator=et;exports.createTimeController=at;exports.testGuardrail=Fe;exports.testGuardrailBatch=Ze;//# sourceMappingURL=testing.cjs.map
|
|
14
|
+
//# sourceMappingURL=testing.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/index.ts","../src/testing.ts"],"names":["GuardrailError","options","AGENT_KEY","APPROVAL_KEY","CONVERSATION_KEY","TOOL_CALLS_KEY","orchestratorBridgeSchema","t","getAgentState","facts","getBridgeFact","setAgentState","state","setBridgeFact","getApprovalState","setApprovalState","getConversation","setConversation","messages","getToolCalls","setToolCalls","toolCalls","getOrchestratorState","convertOrchestratorConstraints","constraints","result","id","constraint","combinedFacts","convertOrchestratorResolvers","resolvers","runAgentWithGuardrails","getSystemFacts","resolver","req","ctx","orchestratorCtx","agent","input","opts","getCombinedFactsFromSystem","normalizeGuardrail","guardrail","index","type","calculateRetryDelay","attempt","config","backoff","baseDelayMs","maxDelayMs","delay","executeGuardrailWithRetry","data","context","retry","maxAttempts","lastError","error","resolve","calculateAgentRetryDelay","executeAgentWithRetry","runner","retryConfig","isRetryable","onRetry","createAgentOrchestrator","factsSchema","init","guardrails","onApprovalRequest","autoApproveToolCalls","maxTokenBudget","plugins","debug","approvalTimeoutMs","agentRetry","hooks","memory","circuitBreaker","combinedSchema","runAgentWithGuardrailsFn","system","directiveConstraints","directiveResolvers","currentFacts","requirementGuard","_req","currentAgent","callbackPlugin","createCallbackPlugin","orchestratorModule","createModule","createSystem","_currentFacts","callOptions","runAgentWithGuardrailsInner","startTime","contextMessages","contextStr","m","effectiveInputGuardrails","effectiveOutputGuardrails","inputGuardrailsList","g","i","name","guardStartTime","message","currentConversation","toolCall","toolCallGuardrails","guardResult","approvalId","approvalRequest","currentApproval","waitForApproval","currentToolCalls","delayMs","outputGuardrailsList","requestId","reject","timeoutId","cleanup","unsubscribe","approval","rejectedRequest","r","errorMsg","timeoutSeconds","getCombinedFacts","abortController","chunks","waiters","closed","tokenCount","accumulatedOutput","abortHandler","pushChunk","chunk","waiter","closeStream","resultPromise","processedInput","inputGuardrails","newTokens","outputGuardrails","duration","MAX_APPROVAL_HISTORY","approved","reason","MAX_REJECTION_HISTORY","rejected","createMockAgentRunner","defaultResponse","responses","recordCalls","onRun","calls","responseMap","currentDefault","runOptions","generated","c","testGuardrail","testInput","fullContext","start","expectedReason","expected","testGuardrailBatch","testCases","results","failures","testCase","createApprovalSimulator","autoApprove","autoReject","recordRequests","requests","pendingRequests","requestWaiters","request","pending","_reason","predicate","timeoutMs","existing","timeout","createTestOrchestrator","mockResponses","defaultMockResponse","orchestratorOptions","mockRunner","approvalSimulator","orchestrator","createConstraintRecorder","snapshots","assertOrchestratorState","min","max","exact","len","createTimeController","currentTime","initial","ms","time"],"mappings":"sJA4VO,IAAMA,CAAAA,CAAN,cAA6B,KAAM,CAC/B,KACA,aAAA,CACA,aAAA,CACA,YAEA,SAAA,CAGT,WAAA,CAAYC,EAUT,CACD,KAAA,CAAMA,EAAQ,OAAA,CAAS,CAAE,MAAOA,CAAAA,CAAQ,KAAM,CAAC,CAAA,CAC/C,IAAA,CAAK,IAAA,CAAO,gBAAA,CACZ,IAAA,CAAK,IAAA,CAAOA,EAAQ,IAAA,CACpB,IAAA,CAAK,cAAgBA,CAAAA,CAAQ,aAAA,CAC7B,KAAK,aAAA,CAAgBA,CAAAA,CAAQ,cAC7B,IAAA,CAAK,WAAA,CAAcA,EA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,CAAE,CAAA,CAEnF,GAAIH,CAAAA,GAAQ,MAAA,EAAaG,CAAAA,CAAMH,CAAAA,CAC7B,MAAM,IAAI,KAAA,CAAM,CAAA,4CAAA,EAA+CA,CAAG,CAAA,MAAA,EAASG,CAAG,EAAE,CAAA,CAElF,GAAIF,CAAAA,GAAQ,MAAA,EAAaE,CAAAA,CAAMF,CAAAA,CAC7B,MAAM,IAAI,KAAA,CAAM,CAAA,2CAAA,EAA8CA,CAAG,CAAA,MAAA,EAASE,CAAG,CAAA,CAAE,CAEnF,CACF,CAuBO,SAASC,EAAAA,CAAqB1G,CAAAA,CAAY,IAAA,CAAK,GAAA,EAAI,CAKxD,CACA,IAAI2G,CAAAA,CAAc3G,CAAAA,CACZ4G,CAAAA,CAAU5G,CAAAA,CAEhB,OAAO,CACL,GAAA,CAAK,IAAM2G,EACX,OAAA,CAAUE,CAAAA,EAAO,CAAEF,CAAAA,EAAeE,EAAI,CAAA,CACtC,GAAA,CAAMC,CAAAA,EAAS,CAAEH,CAAAA,CAAcG,EAAM,CAAA,CACrC,KAAA,CAAO,IAAM,CAAEH,CAAAA,CAAcC,EAAS,CACxC,CACF","file":"testing.cjs","sourcesContent":["/**\n * Shared types for AI adapter — used by orchestrator, guardrails, helpers, and stack.\n */\n\nimport type { Requirement, ModuleSchema } from \"@directive-run/core\";\nimport { t } from \"@directive-run/core\";\n\n// ============================================================================\n// Agent Types (LLM-agnostic)\n// ============================================================================\n\n/** Simplified Agent interface */\nexport interface AgentLike {\n name: string;\n instructions?: string;\n model?: string;\n tools?: unknown[];\n}\n\n/** Agent run result */\nexport interface RunResult<T = unknown> {\n output: T;\n messages: Message[];\n toolCalls: ToolCall[];\n totalTokens: number;\n /** Breakdown of input vs output tokens, when available from the provider */\n tokenUsage?: TokenUsage;\n /** True when result was served from semantic cache */\n isCached?: boolean;\n}\n\n/** Breakdown of token usage by input/output */\nexport interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n}\n\n/** Message from agent run */\nexport interface Message {\n role: \"user\" | \"assistant\" | \"tool\" | \"system\";\n content: string;\n toolCallId?: string;\n}\n\n/** Tool call record */\nexport interface ToolCall {\n id: string;\n name: string;\n arguments: string;\n result?: string;\n}\n\n/** Run function type */\nexport type AgentRunner = <T = unknown>(\n agent: AgentLike,\n input: string,\n options?: RunOptions\n) => Promise<RunResult<T>>;\n\n/** Run options */\nexport interface RunOptions {\n maxTurns?: number;\n signal?: AbortSignal;\n onMessage?: (message: Message) => void;\n onToolCall?: (toolCall: ToolCall) => void;\n}\n\n// ============================================================================\n// Adapter Lifecycle Hooks\n// ============================================================================\n\n/**\n * Lifecycle hooks for adapter-level observability.\n *\n * Attach to any adapter (runner or streaming runner) to trace, log,\n * or measure individual LLM calls without modifying application code.\n *\n * @example\n * ```typescript\n * const runner = createOpenAIRunner({\n * apiKey: process.env.OPENAI_API_KEY!,\n * hooks: {\n * onBeforeCall: ({ agent, input }) => console.log(`→ ${agent.name}`, input.slice(0, 50)),\n * onAfterCall: ({ durationMs, tokenUsage }) => {\n * metrics.track('llm_call', { durationMs, ...tokenUsage });\n * },\n * onError: ({ error }) => Sentry.captureException(error),\n * },\n * });\n * ```\n */\nexport interface AdapterHooks {\n /** Fires before each LLM API call. */\n onBeforeCall?: (event: {\n agent: AgentLike;\n input: string;\n timestamp: number;\n }) => void;\n\n /** Fires after a successful LLM API call. */\n onAfterCall?: (event: {\n agent: AgentLike;\n input: string;\n output: string;\n totalTokens: number;\n tokenUsage: TokenUsage;\n durationMs: number;\n timestamp: number;\n }) => void;\n\n /** Fires when an LLM API call fails. */\n onError?: (event: {\n agent: AgentLike;\n input: string;\n error: Error;\n durationMs: number;\n timestamp: number;\n }) => void;\n}\n\n// ============================================================================\n// Guardrail Types\n// ============================================================================\n\n/** Guardrail function */\nexport type GuardrailFn<T = unknown> = (\n data: T,\n context: GuardrailContext\n) => GuardrailResult | Promise<GuardrailResult>;\n\n/** Guardrail context */\nexport interface GuardrailContext {\n agentName: string;\n input: string;\n facts: Record<string, unknown>;\n}\n\n/** Guardrail result */\nexport interface GuardrailResult {\n passed: boolean;\n reason?: string;\n transformed?: unknown;\n}\n\n/** Input guardrail data */\nexport interface InputGuardrailData {\n input: string;\n agentName: string;\n}\n\n/** Output guardrail data */\nexport interface OutputGuardrailData {\n output: unknown;\n agentName: string;\n input: string;\n messages: Message[];\n}\n\n/** Tool call guardrail data */\nexport interface ToolCallGuardrailData {\n toolCall: ToolCall;\n agentName: string;\n input: string;\n}\n\n/** Retry configuration for guardrails */\nexport interface GuardrailRetryConfig {\n /** @default 1 */\n attempts?: number;\n /** @default \"exponential\" */\n backoff?: \"exponential\" | \"linear\" | \"fixed\";\n /** @default 100 */\n baseDelayMs?: number;\n /** @default 5000 */\n maxDelayMs?: number;\n}\n\n/** Named guardrail for better debugging */\nexport interface NamedGuardrail<T = unknown> {\n name: string;\n fn: GuardrailFn<T>;\n /** @default true */\n critical?: boolean;\n retry?: GuardrailRetryConfig;\n}\n\n/** Guardrails configuration */\nexport interface GuardrailsConfig {\n input?: Array<GuardrailFn<InputGuardrailData> | NamedGuardrail<InputGuardrailData>>;\n output?: Array<GuardrailFn<OutputGuardrailData> | NamedGuardrail<OutputGuardrailData>>;\n toolCall?: Array<GuardrailFn<ToolCallGuardrailData> | NamedGuardrail<ToolCallGuardrailData>>;\n}\n\n// ============================================================================\n// Retry Configuration\n// ============================================================================\n\n/** Retry configuration for agent runs */\nexport interface AgentRetryConfig {\n /** @default 1 */\n attempts?: number;\n /** @default \"exponential\" */\n backoff?: \"exponential\" | \"linear\" | \"fixed\";\n /** @default 1000 */\n baseDelayMs?: number;\n /** @default 30000 */\n maxDelayMs?: number;\n isRetryable?: (error: Error) => boolean;\n onRetry?: (attempt: number, error: Error, delayMs: number) => void;\n}\n\n// ============================================================================\n// Orchestrator State Types\n// ============================================================================\n\n/** Agent state in facts */\nexport interface AgentState {\n status: \"idle\" | \"running\" | \"paused\" | \"completed\" | \"error\";\n currentAgent: string | null;\n input: string | null;\n output: unknown | null;\n error: string | null;\n tokenUsage: number;\n turnCount: number;\n startedAt: number | null;\n completedAt: number | null;\n}\n\n/** Approval state */\nexport interface ApprovalState {\n pending: ApprovalRequest[];\n approved: string[];\n rejected: RejectedRequest[];\n}\n\n/** Rejected request with tracking information */\nexport interface RejectedRequest {\n id: string;\n reason?: string;\n rejectedAt: number;\n}\n\n/** Approval request */\nexport interface ApprovalRequest {\n id: string;\n type: \"tool_call\" | \"output\" | \"handoff\";\n agentName: string;\n description: string;\n data: unknown;\n requestedAt: number;\n}\n\n/** Combined orchestrator state */\nexport interface OrchestratorState {\n agent: AgentState;\n approval: ApprovalState;\n conversation: Message[];\n toolCalls: ToolCall[];\n}\n\n// ============================================================================\n// Orchestrator Config Types\n// ============================================================================\n\n/** Constraint for orchestrator */\nexport interface OrchestratorConstraint<F extends Record<string, unknown>> {\n when: (facts: F & OrchestratorState) => boolean | Promise<boolean>;\n require: Requirement | ((facts: F & OrchestratorState) => Requirement);\n priority?: number;\n}\n\n/** Resolver context for orchestrator */\nexport interface OrchestratorResolverContext<F extends Record<string, unknown>> {\n facts: F & OrchestratorState;\n runAgent: <T>(agent: AgentLike, input: string, options?: RunOptions) => Promise<RunResult<T>>;\n signal: AbortSignal;\n}\n\n/** Resolver for orchestrator */\nexport interface OrchestratorResolver<\n F extends Record<string, unknown>,\n R extends Requirement = Requirement\n> {\n requirement: (req: Requirement) => req is R;\n key?: (req: R) => string;\n resolve: (req: R, ctx: OrchestratorResolverContext<F>) => void | Promise<void>;\n}\n\n/** Lifecycle hooks for observability */\nexport interface OrchestratorLifecycleHooks {\n onAgentStart?: (event: {\n agentName: string;\n input: string;\n timestamp: number;\n }) => void;\n onAgentComplete?: (event: {\n agentName: string;\n input: string;\n output: unknown;\n tokenUsage: number;\n durationMs: number;\n timestamp: number;\n }) => void;\n onAgentError?: (event: {\n agentName: string;\n input: string;\n error: Error;\n durationMs: number;\n timestamp: number;\n }) => void;\n onGuardrailCheck?: (event: {\n guardrailName: string;\n guardrailType: \"input\" | \"output\" | \"toolCall\";\n passed: boolean;\n reason?: string;\n durationMs: number;\n timestamp: number;\n }) => void;\n onAgentRetry?: (event: {\n agentName: string;\n input: string;\n attempt: number;\n error: Error;\n delayMs: number;\n timestamp: number;\n }) => void;\n}\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/** Error codes for guardrail errors */\nexport type GuardrailErrorCode =\n | \"INPUT_GUARDRAIL_FAILED\"\n | \"OUTPUT_GUARDRAIL_FAILED\"\n | \"TOOL_CALL_GUARDRAIL_FAILED\"\n | \"APPROVAL_REJECTED\"\n | \"BUDGET_EXCEEDED\"\n | \"RATE_LIMIT_EXCEEDED\"\n | \"AGENT_ERROR\";\n\n/**\n * Structured error for guardrail failures.\n *\n * **Security:** The `input` and `data` properties are non-enumerable to prevent\n * accidental leakage of sensitive data via JSON.stringify or console.log.\n */\nexport class GuardrailError extends Error {\n readonly code: GuardrailErrorCode;\n readonly guardrailName: string;\n readonly guardrailType: \"input\" | \"output\" | \"toolCall\";\n readonly userMessage: string;\n declare readonly data: unknown;\n readonly agentName: string;\n declare readonly input: string;\n\n constructor(options: {\n code: GuardrailErrorCode;\n message: string;\n guardrailName: string;\n guardrailType: \"input\" | \"output\" | \"toolCall\";\n userMessage?: string;\n data?: unknown;\n agentName: string;\n input: string;\n cause?: Error;\n }) {\n super(options.message, { cause: options.cause });\n this.name = \"GuardrailError\";\n this.code = options.code;\n this.guardrailName = options.guardrailName;\n this.guardrailType = options.guardrailType;\n this.userMessage = options.userMessage ?? options.message;\n this.agentName = options.agentName;\n\n Object.defineProperty(this, \"input\", {\n value: options.input,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n Object.defineProperty(this, \"data\", {\n value: options.data,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n guardrailName: this.guardrailName,\n guardrailType: this.guardrailType,\n userMessage: this.userMessage,\n agentName: this.agentName,\n };\n }\n}\n\n/** Check if an error is a GuardrailError. */\nexport function isGuardrailError(error: unknown): error is GuardrailError {\n return error instanceof GuardrailError;\n}\n\n// ============================================================================\n// Schema Validation Types (used by built-in guardrails)\n// ============================================================================\n\n/** Schema validation result */\nexport interface SchemaValidationResult {\n valid: boolean;\n errors?: string[];\n}\n\n/** Schema validator function type */\nexport type SchemaValidator<_T = unknown> = (\n value: unknown\n) => SchemaValidationResult | boolean;\n\n// ============================================================================\n// Bridge Schema Constants\n// ============================================================================\n\nexport const AGENT_KEY = \"__agent\" as const;\nexport const APPROVAL_KEY = \"__approval\" as const;\nexport const CONVERSATION_KEY = \"__conversation\" as const;\nexport const TOOL_CALLS_KEY = \"__toolCalls\" as const;\n\n/** Bridge schema for orchestrator */\nexport const orchestratorBridgeSchema = {\n facts: {\n [AGENT_KEY]: t.any<AgentState>(),\n [APPROVAL_KEY]: t.any<ApprovalState>(),\n [CONVERSATION_KEY]: t.any<Message[]>(),\n [TOOL_CALLS_KEY]: t.any<ToolCall[]>(),\n },\n derivations: {},\n events: {},\n requirements: {},\n} satisfies ModuleSchema;\n","/**\n * AI Adapter – Constraint-driven agent orchestration with guardrails\n *\n * Philosophy: \"Use Directive WITH any LLM agent framework\"\n * - Your framework handles LLM tool execution\n * - Directive adds safety guardrails, approval workflows, state persistence\n *\n * Also available:\n * - `@directive-run/ai/testing` – Mock runners, test orchestrators, assertion helpers\n * - `@directive-run/ai/anthropic` – Anthropic Claude adapter\n * - `@directive-run/ai/openai` – OpenAI / Azure / Together adapter\n * - `@directive-run/ai/ollama` – Local Ollama inference adapter\n *\n * @example\n * ```typescript\n * import { createAgentOrchestrator } from '@directive-run/ai'\n *\n * const orchestrator = createAgentOrchestrator({\n * runner: myAgentRunner,\n * constraints: {\n * needsExpertReview: {\n * when: (facts) => facts.decision.confidence < 0.7,\n * require: { type: 'EXPERT_AGENT', query: facts.userQuery }\n * },\n * budgetLimit: {\n * when: (facts) => facts.tokenUsage > 10000,\n * require: { type: 'PAUSE_AGENTS' }\n * }\n * },\n * guardrails: {\n * input: [(data) => validatePII(data.input)],\n * output: [(data) => checkToxicity(data.output)]\n * }\n * })\n * ```\n */\n\nimport type {\n Requirement,\n ModuleSchema,\n Plugin,\n SingleModuleSystem,\n System,\n} from \"@directive-run/core\";\nimport type { AgentMemory } from \"./memory.js\";\nimport type { CircuitBreaker } from \"@directive-run/core/plugins\";\nimport type { StreamChunk as StreamChunkBase } from \"./streaming.js\";\nimport {\n setBridgeFact,\n getBridgeFact,\n createCallbackPlugin,\n requirementGuard,\n} from \"@directive-run/core/adapter-utils\";\nimport { createModule } from \"@directive-run/core\";\nimport { createSystem } from \"@directive-run/core\";\n\n// ============================================================================\n// Re-export all types from dedicated module\n// ============================================================================\n\nexport type {\n AgentLike,\n RunResult,\n TokenUsage,\n Message,\n ToolCall,\n AgentRunner,\n RunOptions,\n AdapterHooks,\n GuardrailFn,\n GuardrailContext,\n GuardrailResult,\n InputGuardrailData,\n OutputGuardrailData,\n ToolCallGuardrailData,\n GuardrailRetryConfig,\n AgentRetryConfig,\n NamedGuardrail,\n GuardrailsConfig,\n AgentState,\n ApprovalState,\n RejectedRequest,\n ApprovalRequest,\n OrchestratorConstraint,\n OrchestratorResolverContext,\n OrchestratorResolver,\n OrchestratorState,\n OrchestratorLifecycleHooks,\n GuardrailErrorCode,\n SchemaValidationResult,\n SchemaValidator,\n} from \"./types.js\";\n\nexport { GuardrailError, isGuardrailError } from \"./types.js\";\n\nimport type {\n AgentLike,\n RunResult,\n Message,\n ToolCall,\n AgentRunner,\n RunOptions,\n GuardrailFn,\n GuardrailContext,\n GuardrailResult,\n InputGuardrailData,\n OutputGuardrailData,\n ToolCallGuardrailData,\n GuardrailRetryConfig,\n AgentRetryConfig,\n NamedGuardrail,\n GuardrailsConfig,\n AgentState,\n ApprovalState,\n RejectedRequest,\n ApprovalRequest,\n OrchestratorConstraint,\n OrchestratorResolverContext,\n OrchestratorResolver,\n OrchestratorState,\n OrchestratorLifecycleHooks,\n} from \"./types.js\";\n\nimport {\n GuardrailError,\n AGENT_KEY,\n APPROVAL_KEY,\n CONVERSATION_KEY,\n TOOL_CALLS_KEY,\n orchestratorBridgeSchema,\n} from \"./types.js\";\n\n// Re-export built-in guardrails\nexport {\n createPIIGuardrail,\n createModerationGuardrail,\n createRateLimitGuardrail,\n createToolGuardrail,\n createOutputSchemaGuardrail,\n createOutputTypeGuardrail,\n createLengthGuardrail,\n createContentFilterGuardrail,\n type RateLimitGuardrail,\n} from \"./builtin-guardrails.js\";\n\n// Re-export helpers\nexport {\n isAgentRunning,\n hasPendingApprovals,\n estimateCost,\n validateBaseURL,\n createRunner,\n type CreateRunnerOptions,\n type ParsedResponse,\n} from \"./helpers.js\";\n\n// Re-export constraint helpers\nexport {\n constraint,\n when,\n type ConstraintBuilder,\n type WhenWithRequire,\n} from \"./constraint-helpers.js\";\n\n// ============================================================================\n// Bridge Accessors\n// ============================================================================\n\n// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\nfunction getAgentState(facts: any): AgentState {\n return getBridgeFact<AgentState>(facts, AGENT_KEY);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\nfunction setAgentState(facts: any, state: AgentState): void {\n setBridgeFact(facts, AGENT_KEY, state);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\nfunction getApprovalState(facts: any): ApprovalState {\n return getBridgeFact<ApprovalState>(facts, APPROVAL_KEY);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\nfunction setApprovalState(facts: any, state: ApprovalState): void {\n setBridgeFact(facts, APPROVAL_KEY, state);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\nfunction getConversation(facts: any): Message[] {\n return getBridgeFact<Message[]>(facts, CONVERSATION_KEY);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\nfunction setConversation(facts: any, messages: Message[]): void {\n setBridgeFact(facts, CONVERSATION_KEY, messages);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\nfunction getToolCalls(facts: any): ToolCall[] {\n return getBridgeFact<ToolCall[]>(facts, TOOL_CALLS_KEY);\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\nfunction setToolCalls(facts: any, toolCalls: ToolCall[]): void {\n setBridgeFact(facts, TOOL_CALLS_KEY, toolCalls);\n}\n\n/** Get full orchestrator state from facts */\n// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\nfunction getOrchestratorState(facts: any): OrchestratorState {\n return {\n agent: getAgentState(facts),\n approval: getApprovalState(facts),\n conversation: getConversation(facts),\n toolCalls: getToolCalls(facts),\n };\n}\n\n// ============================================================================\n// Constraint/Resolver Converters\n// ============================================================================\n\n// biome-ignore lint/suspicious/noExplicitAny: Constraint types are complex\nfunction convertOrchestratorConstraints<F extends Record<string, unknown>>(\n constraints: Record<string, OrchestratorConstraint<F>>,\n): Record<string, any> {\n // biome-ignore lint/suspicious/noExplicitAny: Result type is complex\n const result: Record<string, any> = {};\n\n for (const [id, constraint] of Object.entries(constraints)) {\n result[id] = {\n priority: constraint.priority ?? 0,\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n when: (facts: any) => {\n const state = getOrchestratorState(facts);\n const combinedFacts = { ...facts, ...state } as unknown as F & OrchestratorState;\n return constraint.when(combinedFacts);\n },\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n require: (facts: any) => {\n const state = getOrchestratorState(facts);\n const combinedFacts = { ...facts, ...state } as unknown as F & OrchestratorState;\n return typeof constraint.require === \"function\"\n ? constraint.require(combinedFacts)\n : constraint.require;\n },\n };\n }\n\n return result;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: Resolver types are complex\nfunction convertOrchestratorResolvers<F extends Record<string, unknown>>(\n resolvers: Record<string, OrchestratorResolver<F, Requirement>>,\n runAgentWithGuardrails: <T>(\n agent: AgentLike,\n input: string,\n currentFacts: F & OrchestratorState,\n opts?: RunOptions\n ) => Promise<RunResult<T>>,\n // biome-ignore lint/suspicious/noExplicitAny: Facts getter type varies\n getSystemFacts: () => any,\n): Record<string, any> {\n // biome-ignore lint/suspicious/noExplicitAny: Result type is complex\n const result: Record<string, any> = {};\n\n for (const [id, resolver] of Object.entries(resolvers)) {\n result[id] = {\n requirement: resolver.requirement,\n key: resolver.key,\n // biome-ignore lint/suspicious/noExplicitAny: Context type varies\n resolve: async (req: Requirement, ctx: any) => {\n const state = getOrchestratorState(ctx.facts);\n const combinedFacts = { ...ctx.facts, ...state } as unknown as F & OrchestratorState;\n\n const orchestratorCtx: OrchestratorResolverContext<F> = {\n facts: combinedFacts,\n runAgent: async <T>(agent: AgentLike, input: string, opts?: RunOptions) => {\n return runAgentWithGuardrails<T>(\n agent,\n input,\n getCombinedFactsFromSystem(getSystemFacts()) as unknown as F & OrchestratorState,\n opts\n );\n },\n signal: ctx.signal,\n };\n await resolver.resolve(req, orchestratorCtx);\n },\n };\n }\n\n return result;\n}\n\n/** Helper to get combined facts from system facts */\n// biome-ignore lint/suspicious/noExplicitAny: Facts type varies\nfunction getCombinedFactsFromSystem(facts: any): OrchestratorState {\n return getOrchestratorState(facts);\n}\n\n/** Built-in pause requirement type */\ninterface PauseBudgetExceededReq extends Requirement {\n type: \"__PAUSE_BUDGET_EXCEEDED\";\n}\n\n/** Orchestrator options */\nexport interface OrchestratorOptions<F extends Record<string, unknown>> {\n /** Function to run an agent */\n runner: AgentRunner;\n /** Additional facts schema */\n factsSchema?: Record<string, { _type: unknown; _validators: [] }>;\n /** Initialize additional facts */\n init?: (facts: F & OrchestratorState) => void;\n /** Constraints for orchestration */\n constraints?: Record<string, OrchestratorConstraint<F>>;\n /** Resolvers for orchestration */\n resolvers?: Record<string, OrchestratorResolver<F, Requirement>>;\n /** Guardrails */\n guardrails?: GuardrailsConfig;\n /** Callback for approval requests */\n onApprovalRequest?: (request: ApprovalRequest) => void;\n /**\n * Auto-approve tool calls\n * @default true\n */\n autoApproveToolCalls?: boolean;\n /**\n * Maximum token budget across all agent runs.\n *\n * When exceeded, agents are automatically paused with status \"paused\".\n * Check `facts.agent.tokenUsage` to see current usage.\n *\n * For more sophisticated cost management (per-user budgets, tiered pricing,\n * cost alerts), see the Cost Management section in the documentation.\n *\n * @example\n * ```typescript\n * const orchestrator = createAgentOrchestrator({\n * maxTokenBudget: 10000, // Pause after 10K tokens\n * });\n *\n * // Check if paused due to budget\n * if (orchestrator.facts.agent.status === 'paused') {\n * console.log('Budget exceeded:', orchestrator.facts.agent.tokenUsage);\n * }\n * ```\n */\n maxTokenBudget?: number;\n /** Plugins */\n plugins?: Plugin[];\n /**\n * Enable debugging\n * @default false\n */\n debug?: boolean;\n /**\n * Approval timeout in milliseconds\n * @default 300000 (5 minutes)\n */\n approvalTimeoutMs?: number;\n /** Retry configuration for agent runs (no retries if not specified) */\n agentRetry?: AgentRetryConfig;\n /** Lifecycle hooks for observability */\n hooks?: OrchestratorLifecycleHooks;\n /**\n * Optional memory instance. When provided, context messages are auto-injected\n * into agent instructions before each run, and result messages are auto-stored.\n */\n memory?: AgentMemory;\n /**\n * Optional circuit breaker. Wraps every run() call.\n * When OPEN, throws CircuitBreakerOpenError instead of calling the agent.\n */\n circuitBreaker?: CircuitBreaker;\n}\n\n/** Streaming run result from orchestrator */\nexport interface OrchestratorStreamResult<T = unknown> {\n /** Async iterator for streaming chunks */\n stream: AsyncIterable<OrchestratorStreamChunk>;\n /** Promise that resolves to the final result */\n result: Promise<RunResult<T>>;\n /** Abort the stream */\n abort: () => void;\n}\n\n/** Stream chunk types for orchestrator — extends StreamChunk with approval events */\nexport type OrchestratorStreamChunk =\n | StreamChunkBase\n | { type: \"approval_required\"; requestId: string; toolName: string }\n | { type: \"approval_resolved\"; requestId: string; approved: boolean };\n\n/** Per-call options for run() */\nexport interface RunCallOptions {\n /** Override output guardrails for this call only. Set to [] to skip. */\n outputGuardrails?: Array<GuardrailFn<OutputGuardrailData> | NamedGuardrail<OutputGuardrailData>>;\n /** Override input guardrails for this call only. Set to [] to skip. */\n inputGuardrails?: Array<GuardrailFn<InputGuardrailData> | NamedGuardrail<InputGuardrailData>>;\n /** Signal for abort */\n signal?: AbortSignal;\n}\n\n/** Orchestrator instance */\nexport interface AgentOrchestrator<F extends Record<string, unknown>> {\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: System<any>;\n facts: F & OrchestratorState;\n /** Run an agent with guardrails. Pass options to override guardrails per-call. */\n run<T>(agent: AgentLike, input: string, options?: RunCallOptions): Promise<RunResult<T>>;\n /**\n * Run an agent with streaming support.\n * Returns an async iterator for chunks and a promise for the final result.\n *\n * @example\n * ```typescript\n * const { stream, result, abort } = orchestrator.runStream(agent, input);\n *\n * for await (const chunk of stream) {\n * if (chunk.type === 'token') process.stdout.write(chunk.data);\n * if (chunk.type === 'approval_required') showApprovalDialog(chunk);\n * if (chunk.type === 'guardrail_triggered') handleGuardrail(chunk);\n * }\n *\n * const finalResult = await result;\n * ```\n */\n runStream<T>(agent: AgentLike, input: string, options?: { signal?: AbortSignal }): OrchestratorStreamResult<T>;\n /** Approve a pending request */\n approve(requestId: string): void;\n /** Reject a pending request */\n reject(requestId: string, reason?: string): void;\n /** Pause all agents */\n pause(): void;\n /** Resume agents */\n resume(): void;\n /** Reset conversation state */\n reset(): void;\n /** Dispose of the orchestrator */\n dispose(): void;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n// ============================================================================\n// Helper: Normalize Guardrail (internal)\n// ============================================================================\n\n/** Normalize a guardrail to a named guardrail */\nfunction normalizeGuardrail<T>(\n guardrail: GuardrailFn<T> | NamedGuardrail<T>,\n index: number,\n type: string\n): NamedGuardrail<T> {\n if (typeof guardrail === \"function\") {\n return {\n name: `${type}-guardrail-${index}`,\n fn: guardrail,\n critical: true,\n };\n }\n return guardrail;\n}\n\n/** Calculate delay for retry with backoff */\nfunction calculateRetryDelay(\n attempt: number,\n config: GuardrailRetryConfig\n): number {\n const { backoff = \"exponential\", baseDelayMs = 100, maxDelayMs = 5000 } = config;\n let delay: number;\n switch (backoff) {\n case \"exponential\":\n delay = baseDelayMs * Math.pow(2, attempt - 1);\n break;\n case \"linear\":\n delay = baseDelayMs * attempt;\n break;\n case \"fixed\":\n default:\n delay = baseDelayMs;\n }\n return Math.min(delay, maxDelayMs);\n}\n\n/** Execute a guardrail with retry support */\nasync function executeGuardrailWithRetry<T>(\n guardrail: NamedGuardrail<T>,\n data: T,\n context: GuardrailContext\n): Promise<GuardrailResult> {\n const { retry } = guardrail;\n const maxAttempts = retry?.attempts ?? 1;\n\n let lastError: Error | undefined;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await guardrail.fn(data, context);\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n // Only retry if we have more attempts left\n if (attempt < maxAttempts) {\n const delay = calculateRetryDelay(attempt, retry ?? {});\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n // All retries exhausted, throw the last error\n throw lastError;\n}\n\n/** Calculate delay for agent retry with backoff */\nfunction calculateAgentRetryDelay(\n attempt: number,\n config: AgentRetryConfig\n): number {\n const { backoff = \"exponential\", baseDelayMs = 1000, maxDelayMs = 30000 } = config;\n let delay: number;\n switch (backoff) {\n case \"exponential\":\n delay = baseDelayMs * Math.pow(2, attempt - 1);\n break;\n case \"linear\":\n delay = baseDelayMs * attempt;\n break;\n case \"fixed\":\n default:\n delay = baseDelayMs;\n }\n return Math.min(delay, maxDelayMs);\n}\n\n/** Execute an agent run with retry support */\nasync function executeAgentWithRetry<T>(\n runner: AgentRunner,\n agent: AgentLike,\n input: string,\n options: RunOptions | undefined,\n retryConfig: AgentRetryConfig | undefined\n): Promise<RunResult<T>> {\n const maxAttempts = retryConfig?.attempts ?? 1;\n const isRetryable = retryConfig?.isRetryable ?? (() => true);\n const onRetry = retryConfig?.onRetry;\n\n let lastError: Error | undefined;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await runner<T>(agent, input, options);\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Check if error is retryable and we have more attempts\n if (attempt < maxAttempts && isRetryable(lastError)) {\n const delay = calculateAgentRetryDelay(attempt, retryConfig ?? {});\n onRetry?.(attempt, lastError, delay);\n await new Promise((resolve) => setTimeout(resolve, delay));\n } else {\n // Either not retryable or out of attempts\n break;\n }\n }\n }\n // All retries exhausted, throw the last error\n throw lastError;\n}\n\n/**\n * Create an orchestrator for OpenAI agents with Directive constraints.\n *\n * @example\n * ```typescript\n * import { run as runner } from '@openai/agents'\n *\n * const orchestrator = createAgentOrchestrator({\n * runner,\n * constraints: {\n * escalateToExpert: {\n * when: (facts) => facts.agent.output?.confidence < 0.7,\n * require: (facts) => ({\n * type: 'RUN_EXPERT_AGENT',\n * query: facts.agent.input,\n * }),\n * },\n * budgetExceeded: {\n * when: (facts) => facts.agent.tokenUsage > 10000,\n * require: { type: 'PAUSE_AGENTS' },\n * },\n * },\n * guardrails: {\n * input: [\n * async (data) => {\n * const hasPII = await detectPII(data.input);\n * return { passed: !hasPII, reason: hasPII ? 'Contains PII' : undefined };\n * },\n * ],\n * output: [\n * async (data) => {\n * const isToxic = await checkToxicity(data.output);\n * return { passed: !isToxic, reason: isToxic ? 'Toxic content' : undefined };\n * },\n * ],\n * },\n * });\n *\n * // Run with guardrails and constraint-driven orchestration\n * const result = await orchestrator.run(myAgent, 'Hello, can you help me?');\n * ```\n *\n * @throws {Error} If autoApproveToolCalls is false but no onApprovalRequest callback is provided\n */\nexport function createAgentOrchestrator<\n F extends Record<string, unknown> = Record<string, never>\n>(options: OrchestratorOptions<F>): AgentOrchestrator<F> {\n const {\n runner,\n factsSchema = {},\n init,\n constraints = {},\n resolvers = {},\n guardrails = {},\n onApprovalRequest,\n autoApproveToolCalls = true,\n maxTokenBudget,\n plugins = [],\n debug = false,\n approvalTimeoutMs = 300000,\n agentRetry,\n hooks = {},\n memory,\n circuitBreaker,\n } = options;\n\n // Enforce approval workflow configuration - require either auto-approve or callback\n if (!autoApproveToolCalls && !onApprovalRequest) {\n throw new Error(\n \"[Directive] Invalid approval configuration: autoApproveToolCalls is false but no onApprovalRequest callback provided. \" +\n \"Tool calls would wait for approval indefinitely. Either:\\n\" +\n \" - Set autoApproveToolCalls: true to auto-approve all tool calls\\n\" +\n \" - Provide an onApprovalRequest callback to handle approvals programmatically\"\n );\n }\n\n // Build schema by combining bridge schema with user-provided schema\n const combinedSchema = {\n facts: {\n ...orchestratorBridgeSchema.facts,\n ...factsSchema,\n },\n derivations: {},\n events: {},\n requirements: {},\n } satisfies ModuleSchema;\n\n // Forward declaration for runAgentWithGuardrails (used in resolver converter)\n let runAgentWithGuardrailsFn: <T>(\n agent: AgentLike,\n input: string,\n currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions\n ) => Promise<RunResult<T>>;\n\n // Forward declaration for system (used in resolver converter)\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n let system: SingleModuleSystem<any>;\n\n // Convert user constraints\n // biome-ignore lint/suspicious/noExplicitAny: Constraint types are complex\n const directiveConstraints: Record<string, any> =\n convertOrchestratorConstraints<F>(constraints);\n\n // Add built-in budget limit constraint\n if (maxTokenBudget) {\n directiveConstraints[\"__budgetLimit\"] = {\n priority: 100, // High priority\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n when: (facts: any) => getAgentState(facts).tokenUsage > maxTokenBudget,\n require: { type: \"__PAUSE_BUDGET_EXCEEDED\" } as PauseBudgetExceededReq,\n };\n }\n\n // Convert user resolvers\n // biome-ignore lint/suspicious/noExplicitAny: Resolver types are complex\n const directiveResolvers: Record<string, any> =\n convertOrchestratorResolvers<F>(\n resolvers,\n (agent, input, currentFacts, opts) => runAgentWithGuardrailsFn(agent, input, currentFacts, opts),\n () => system.facts,\n );\n\n // Add built-in pause resolver\n directiveResolvers[\"__pause\"] = {\n requirement: requirementGuard<PauseBudgetExceededReq>(\"__PAUSE_BUDGET_EXCEEDED\"),\n // biome-ignore lint/suspicious/noExplicitAny: Context type varies\n resolve: async (_req: Requirement, ctx: any) => {\n const currentAgent = getAgentState(ctx.facts);\n setAgentState(ctx.facts, {\n ...currentAgent,\n status: \"paused\",\n });\n },\n };\n\n // Create callback plugin for onApprovalRequest\n const callbackPlugin = createCallbackPlugin(\n \"openai-agents-callbacks\",\n {}, // No requirement callbacks needed, approval is handled separately\n );\n\n // Create module\n // biome-ignore lint/suspicious/noExplicitAny: Bridge module uses dynamic constraints/resolvers\n const orchestratorModule = createModule(\"openai-agents-orchestrator\", {\n schema: combinedSchema,\n init: (facts) => {\n setAgentState(facts, {\n status: \"idle\",\n currentAgent: null,\n input: null,\n output: null,\n error: null,\n tokenUsage: 0,\n turnCount: 0,\n startedAt: null,\n completedAt: null,\n });\n setApprovalState(facts, {\n pending: [],\n approved: [],\n rejected: [],\n });\n setConversation(facts, []);\n setToolCalls(facts, []);\n if (init) {\n const state = getOrchestratorState(facts);\n const combinedFacts = { ...facts, ...state } as unknown as F & OrchestratorState;\n init(combinedFacts);\n }\n },\n constraints: directiveConstraints,\n resolvers: directiveResolvers as any,\n });\n\n // Create system\n system = createSystem({\n module: orchestratorModule,\n plugins: [...plugins, callbackPlugin],\n debug: debug ? { timeTravel: true } : undefined,\n });\n\n system.start();\n\n // Helper to run agent with guardrails\n async function runAgentWithGuardrails<T>(\n agent: AgentLike,\n input: string,\n _currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions\n ): Promise<RunResult<T>> {\n // Wrap in circuit breaker if configured\n if (circuitBreaker) {\n return circuitBreaker.execute(() =>\n runAgentWithGuardrailsInner<T>(agent, input, _currentFacts, opts, callOptions)\n );\n }\n return runAgentWithGuardrailsInner<T>(agent, input, _currentFacts, opts, callOptions);\n }\n\n async function runAgentWithGuardrailsInner<T>(\n agent: AgentLike,\n input: string,\n _currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions\n ): Promise<RunResult<T>> {\n const startTime = Date.now();\n\n // Inject memory context into agent instructions if memory is configured\n if (memory) {\n const contextMessages = memory.getContextMessages();\n if (contextMessages.length > 0) {\n const contextStr = contextMessages\n .map((m) => `${m.role}: ${m.content}`)\n .join(\"\\n\");\n agent = {\n ...agent,\n instructions: (agent.instructions ?? \"\") + \"\\n\\nConversation context:\\n\" + contextStr,\n };\n }\n }\n\n // Call onAgentStart hook\n hooks.onAgentStart?.({\n agentName: agent.name,\n input,\n timestamp: startTime,\n });\n\n // Resolve which guardrails to use: per-call override > orchestrator defaults\n const effectiveInputGuardrails = callOptions?.inputGuardrails !== undefined\n ? callOptions.inputGuardrails\n : (guardrails.input ?? []);\n const effectiveOutputGuardrails = callOptions?.outputGuardrails !== undefined\n ? callOptions.outputGuardrails\n : (guardrails.output ?? []);\n\n // Run input guardrails with retry support\n const inputGuardrailsList = effectiveInputGuardrails.map((g, i) =>\n normalizeGuardrail(g, i, \"input\")\n );\n for (const guardrail of inputGuardrailsList) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const result = await executeGuardrailWithRetry(\n guardrail,\n { input, agentName: agent.name },\n context\n );\n // Call onGuardrailCheck hook\n hooks.onGuardrailCheck?.({\n guardrailName: name,\n guardrailType: \"input\",\n passed: result.passed,\n reason: result.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!result.passed) {\n throw new GuardrailError({\n code: \"INPUT_GUARDRAIL_FAILED\",\n message: `Input guardrail \"${name}\" failed: ${result.reason}`,\n guardrailName: name,\n guardrailType: \"input\",\n userMessage: result.reason ?? \"Input validation failed\",\n agentName: agent.name,\n input,\n });\n }\n if (result.transformed !== undefined) {\n input = result.transformed as string;\n }\n }\n\n // Update state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"running\",\n currentAgent: agent.name,\n input,\n startedAt: Date.now(),\n });\n });\n\n // Run the agent with retry support\n const result = await executeAgentWithRetry<T>(runner, agent, input, {\n ...opts,\n signal: opts?.signal,\n onMessage: (message) => {\n const currentConversation = getConversation(system.facts);\n setConversation(system.facts, [...currentConversation, message]);\n opts?.onMessage?.(message);\n },\n onToolCall: async (toolCall) => {\n // Run tool call guardrails with retry support\n const toolCallGuardrails = (guardrails.toolCall ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"toolCall\")\n );\n for (const guardrail of toolCallGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n { toolCall, agentName: agent.name, input },\n context\n );\n hooks.onGuardrailCheck?.({\n guardrailName: name,\n guardrailType: \"toolCall\",\n passed: guardResult.passed,\n reason: guardResult.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!guardResult.passed) {\n throw new GuardrailError({\n code: \"TOOL_CALL_GUARDRAIL_FAILED\",\n message: `Tool call guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"toolCall\",\n userMessage: guardResult.reason ?? \"Tool call blocked\",\n data: { toolCall },\n agentName: agent.name,\n input,\n });\n }\n }\n\n // Check if approval is needed\n if (!autoApproveToolCalls) {\n const approvalId = `tool-${toolCall.id}`;\n const approvalRequest: ApprovalRequest = {\n id: approvalId,\n type: \"tool_call\",\n agentName: agent.name,\n description: `Tool call: ${toolCall.name}`,\n data: toolCall,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const currentApproval = getApprovalState(system.facts);\n setApprovalState(system.facts, {\n ...currentApproval,\n pending: [...currentApproval.pending, approvalRequest],\n });\n });\n\n onApprovalRequest?.(approvalRequest);\n\n // Wait for approval\n await waitForApproval(approvalId);\n }\n\n const currentToolCalls = getToolCalls(system.facts);\n setToolCalls(system.facts, [...currentToolCalls, toolCall]);\n opts?.onToolCall?.(toolCall);\n },\n }, agentRetry ? {\n ...agentRetry,\n onRetry: (attempt, error, delayMs) => {\n agentRetry.onRetry?.(attempt, error, delayMs);\n hooks.onAgentRetry?.({\n agentName: agent.name,\n input,\n attempt,\n error,\n delayMs,\n timestamp: Date.now(),\n });\n },\n } : undefined);\n\n // Run output guardrails with retry support\n const outputGuardrailsList = effectiveOutputGuardrails.map((g, i) =>\n normalizeGuardrail(g, i, \"output\")\n );\n for (const guardrail of outputGuardrailsList) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n {\n output: result.output,\n agentName: agent.name,\n input,\n messages: result.messages,\n },\n context\n );\n hooks.onGuardrailCheck?.({\n guardrailName: name,\n guardrailType: \"output\",\n passed: guardResult.passed,\n reason: guardResult.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!guardResult.passed) {\n throw new GuardrailError({\n code: \"OUTPUT_GUARDRAIL_FAILED\",\n message: `Output guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"output\",\n userMessage: guardResult.reason ?? \"Output validation failed\",\n agentName: agent.name,\n input,\n });\n }\n if (guardResult.transformed !== undefined) {\n (result as { output: unknown }).output = guardResult.transformed;\n }\n }\n\n // Update state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"completed\",\n output: result.output,\n tokenUsage: currentAgent.tokenUsage + result.totalTokens,\n turnCount: currentAgent.turnCount + result.messages.length,\n completedAt: Date.now(),\n });\n });\n\n // Store messages in memory if configured\n if (memory && result.messages.length > 0) {\n memory.addMessages(result.messages);\n }\n\n // Call onAgentComplete hook\n hooks.onAgentComplete?.({\n agentName: agent.name,\n input,\n output: result.output,\n tokenUsage: result.totalTokens,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n });\n\n return result;\n }\n\n // Assign the function to the forward-declared variable\n runAgentWithGuardrailsFn = runAgentWithGuardrails;\n\n // Wait for approval with configurable timeout\n function waitForApproval(requestId: string): Promise<void> {\n return new Promise((resolve, reject) => {\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanup = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n const unsubscribe = system.facts.$store.subscribe([APPROVAL_KEY], () => {\n const approval = getApprovalState(system.facts);\n if (approval.approved.includes(requestId)) {\n cleanup();\n unsubscribe();\n resolve();\n } else {\n const rejectedRequest = approval.rejected.find((r) => r.id === requestId);\n if (rejectedRequest) {\n cleanup();\n unsubscribe();\n const errorMsg = rejectedRequest.reason\n ? `Request ${requestId} rejected: ${rejectedRequest.reason}`\n : `Request ${requestId} rejected`;\n reject(new Error(errorMsg));\n }\n }\n });\n\n // Set timeout to prevent indefinite hanging (uses configured approvalTimeoutMs)\n timeoutId = setTimeout(() => {\n unsubscribe();\n const timeoutSeconds = Math.round(approvalTimeoutMs / 1000);\n reject(new Error(\n `[Directive] Approval timeout: Request ${requestId} not resolved within ${timeoutSeconds}s.\\n` +\n `Solutions:\\n` +\n ` 1. Handle via onApprovalRequest callback and call orchestrator.approve()/reject()\\n` +\n ` 2. Set autoApproveToolCalls: true to auto-approve\\n` +\n ` 3. Increase approvalTimeoutMs (current: ${approvalTimeoutMs}ms)\\n` +\n `See: https://directive.run/docs/ai/running-agents`\n ));\n }, approvalTimeoutMs);\n });\n }\n\n /** Get facts as the combined type for external access */\n function getCombinedFacts(): F & OrchestratorState {\n const state = getOrchestratorState(system.facts);\n return { ...state } as unknown as F & OrchestratorState;\n }\n\n const orchestrator: AgentOrchestrator<F> = {\n system: system as unknown as System<any>,\n get facts() {\n return getCombinedFacts();\n },\n\n async run<T>(agent: AgentLike, input: string, options?: RunCallOptions): Promise<RunResult<T>> {\n return runAgentWithGuardrails<T>(agent, input, getCombinedFacts(), undefined, options);\n },\n\n runStream<T>(\n agent: AgentLike,\n input: string,\n options: { signal?: AbortSignal } = {}\n ): OrchestratorStreamResult<T> {\n const abortController = new AbortController();\n const chunks: OrchestratorStreamChunk[] = [];\n const waiters: Array<(chunk: OrchestratorStreamChunk | null) => void> = [];\n let closed = false;\n const startTime = Date.now();\n let tokenCount = 0;\n let accumulatedOutput = \"\";\n\n // Combine external abort signal\n let abortHandler: (() => void) | undefined;\n if (options.signal) {\n abortHandler = () => abortController.abort();\n options.signal.addEventListener(\"abort\", abortHandler);\n }\n\n const cleanup = () => {\n if (abortHandler && options.signal) {\n options.signal.removeEventListener(\"abort\", abortHandler);\n }\n };\n\n // Push a chunk to the stream\n const pushChunk = (chunk: OrchestratorStreamChunk) => {\n if (closed) return;\n const waiter = waiters.shift();\n if (waiter) {\n waiter(chunk);\n } else {\n chunks.push(chunk);\n }\n };\n\n // Close the stream\n const closeStream = () => {\n closed = true;\n cleanup();\n for (const waiter of waiters) {\n waiter(null);\n }\n waiters.length = 0;\n };\n\n // Run the agent with streaming callbacks\n const resultPromise = (async (): Promise<RunResult<T>> => {\n pushChunk({ type: \"progress\", phase: \"starting\", message: \"Running input guardrails\" });\n\n try {\n // Run input guardrails first with retry support\n let processedInput = input;\n const inputGuardrails = (guardrails.input ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"input\")\n );\n for (const guardrail of inputGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const result = await executeGuardrailWithRetry(\n guardrail,\n { input: processedInput, agentName: agent.name },\n context\n );\n if (!result.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: result.reason ?? \"Input validation failed\",\n partialOutput: accumulatedOutput,\n stopped: true,\n });\n throw new GuardrailError({\n code: \"INPUT_GUARDRAIL_FAILED\",\n message: `Input guardrail \"${name}\" failed: ${result.reason}`,\n guardrailName: name,\n guardrailType: \"input\",\n userMessage: result.reason ?? \"Input validation failed\",\n agentName: agent.name,\n input: processedInput,\n });\n }\n if (result.transformed !== undefined) {\n processedInput = result.transformed as string;\n }\n }\n\n pushChunk({ type: \"progress\", phase: \"generating\", message: \"Starting agent\" });\n\n // Update state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"running\",\n currentAgent: agent.name,\n input: processedInput,\n startedAt: Date.now(),\n });\n });\n\n // Run agent with streaming callbacks and retry support\n const result = await executeAgentWithRetry<T>(runner, agent, processedInput, {\n signal: abortController.signal,\n onMessage: (message) => {\n const currentConversation = getConversation(system.facts);\n setConversation(system.facts, [...currentConversation, message]);\n pushChunk({ type: \"message\", message });\n\n // Approximate token counting from content\n if (message.role === \"assistant\" && message.content) {\n const newTokens = Math.ceil(message.content.length / 4);\n tokenCount += newTokens;\n accumulatedOutput += message.content;\n pushChunk({ type: \"token\", data: message.content, tokenCount });\n }\n },\n onToolCall: async (toolCall) => {\n pushChunk({ type: \"tool_start\", tool: toolCall.name, toolCallId: toolCall.id, arguments: toolCall.arguments });\n\n // Run tool call guardrails with retry support\n const toolCallGuardrails = (guardrails.toolCall ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"toolCall\")\n );\n for (const guardrail of toolCallGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n { toolCall, agentName: agent.name, input: processedInput },\n context\n );\n if (!guardResult.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: guardResult.reason ?? \"Tool call blocked\",\n partialOutput: accumulatedOutput,\n stopped: true,\n });\n throw new GuardrailError({\n code: \"TOOL_CALL_GUARDRAIL_FAILED\",\n message: `Tool call guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"toolCall\",\n userMessage: guardResult.reason ?? \"Tool call blocked\",\n data: { toolCall },\n agentName: agent.name,\n input: processedInput,\n });\n }\n }\n\n // Check if approval is needed\n if (!autoApproveToolCalls) {\n const approvalId = `tool-${toolCall.id}`;\n pushChunk({ type: \"approval_required\", requestId: approvalId, toolName: toolCall.name });\n\n const approvalRequest: ApprovalRequest = {\n id: approvalId,\n type: \"tool_call\",\n agentName: agent.name,\n description: `Tool call: ${toolCall.name}`,\n data: toolCall,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const currentApproval = getApprovalState(system.facts);\n setApprovalState(system.facts, {\n ...currentApproval,\n pending: [...currentApproval.pending, approvalRequest],\n });\n });\n\n onApprovalRequest?.(approvalRequest);\n await waitForApproval(approvalId);\n pushChunk({ type: \"approval_resolved\", requestId: approvalId, approved: true });\n }\n\n const currentToolCalls = getToolCalls(system.facts);\n setToolCalls(system.facts, [...currentToolCalls, toolCall]);\n\n if (toolCall.result) {\n pushChunk({ type: \"tool_end\", tool: toolCall.name, toolCallId: toolCall.id, result: toolCall.result });\n }\n },\n }, agentRetry);\n\n // Run output guardrails\n pushChunk({ type: \"progress\", phase: \"finishing\", message: \"Running output guardrails\" });\n\n const outputGuardrails = (guardrails.output ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"output\")\n );\n for (const guardrail of outputGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n {\n output: result.output,\n agentName: agent.name,\n input: processedInput,\n messages: result.messages,\n },\n context\n );\n if (!guardResult.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: guardResult.reason ?? \"Output validation failed\",\n partialOutput: typeof result.output === \"string\" ? result.output : \"\",\n stopped: true,\n });\n throw new GuardrailError({\n code: \"OUTPUT_GUARDRAIL_FAILED\",\n message: `Output guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"output\",\n userMessage: guardResult.reason ?? \"Output validation failed\",\n agentName: agent.name,\n input: processedInput,\n });\n }\n if (guardResult.transformed !== undefined) {\n (result as { output: unknown }).output = guardResult.transformed;\n }\n }\n\n // Update final state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"completed\",\n output: result.output,\n tokenUsage: currentAgent.tokenUsage + result.totalTokens,\n turnCount: currentAgent.turnCount + result.messages.length,\n completedAt: Date.now(),\n });\n });\n\n const duration = Date.now() - startTime;\n pushChunk({ type: \"done\", totalTokens: result.totalTokens, duration, droppedTokens: 0 });\n closeStream();\n\n return result;\n } catch (error) {\n pushChunk({ type: \"error\", error: error instanceof Error ? error : new Error(String(error)) });\n closeStream();\n throw error;\n }\n })();\n\n // Create async iterator\n const stream: AsyncIterable<OrchestratorStreamChunk> = {\n [Symbol.asyncIterator](): AsyncIterator<OrchestratorStreamChunk> {\n return {\n async next(): Promise<IteratorResult<OrchestratorStreamChunk>> {\n if (chunks.length > 0) {\n return { done: false, value: chunks.shift()! };\n }\n if (closed) {\n return { done: true, value: undefined };\n }\n return new Promise<IteratorResult<OrchestratorStreamChunk>>((resolve) => {\n waiters.push((chunk) => {\n if (chunk === null) {\n resolve({ done: true, value: undefined });\n } else {\n resolve({ done: false, value: chunk });\n }\n });\n });\n },\n };\n },\n };\n\n return {\n stream,\n result: resultPromise,\n abort: () => {\n abortController.abort();\n closeStream();\n },\n };\n },\n\n approve(requestId: string): void {\n system.batch(() => {\n const approval = getApprovalState(system.facts);\n if (!approval.pending.some((r) => r.id === requestId)) {\n if (debug) console.debug(`[Directive] approve() ignored: no pending request \"${requestId}\"`);\n return;\n }\n const MAX_APPROVAL_HISTORY = 200;\n const approved = [...approval.approved, requestId];\n setApprovalState(system.facts, {\n ...approval,\n pending: approval.pending.filter((r) => r.id !== requestId),\n approved: approved.length > MAX_APPROVAL_HISTORY ? approved.slice(-MAX_APPROVAL_HISTORY) : approved,\n });\n });\n },\n\n reject(requestId: string, reason?: string): void {\n system.batch(() => {\n const approval = getApprovalState(system.facts);\n if (!approval.pending.some((r) => r.id === requestId)) {\n if (debug) console.debug(`[Directive] reject() ignored: no pending request \"${requestId}\"`);\n return;\n }\n if (reason && debug) {\n console.debug(`[Directive] Request ${requestId} rejected: ${reason}`);\n }\n const rejectedRequest: RejectedRequest = {\n id: requestId,\n reason,\n rejectedAt: Date.now(),\n };\n const MAX_REJECTION_HISTORY = 200;\n const rejected = [...approval.rejected, rejectedRequest];\n setApprovalState(system.facts, {\n ...approval,\n pending: approval.pending.filter((r) => r.id !== requestId),\n rejected: rejected.length > MAX_REJECTION_HISTORY ? rejected.slice(-MAX_REJECTION_HISTORY) : rejected,\n });\n });\n },\n\n pause(): void {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"paused\",\n });\n },\n\n resume(): void {\n const agent = getAgentState(system.facts);\n if (agent.status === \"paused\") {\n setAgentState(system.facts, {\n ...agent,\n status: agent.currentAgent ? \"running\" : \"idle\",\n });\n }\n },\n\n reset(): void {\n system.batch(() => {\n setAgentState(system.facts, {\n status: \"idle\",\n currentAgent: null,\n input: null,\n output: null,\n error: null,\n tokenUsage: 0,\n turnCount: 0,\n startedAt: null,\n completedAt: null,\n });\n setApprovalState(system.facts, {\n pending: [],\n approved: [],\n rejected: [],\n });\n setConversation(system.facts, []);\n setToolCalls(system.facts, []);\n });\n },\n\n dispose(): void {\n system.destroy();\n },\n };\n\n return orchestrator;\n}\n\n// (Built-in guardrails moved to openai-agents-builtin-guardrails.ts)\n\n// (Helper functions moved to openai-agents-helpers.ts)\n\n// (Cost helpers + errors moved to openai-agents-helpers.ts + openai-agents-types.ts)\n\n// ============================================================================\n// Builder Pattern\n// ============================================================================\n\n/** Builder for type-safe orchestrator configuration */\nexport interface OrchestratorBuilder<F extends Record<string, unknown>> {\n /** Add a constraint */\n withConstraint<K extends string>(\n id: K,\n constraint: OrchestratorConstraint<F>\n ): OrchestratorBuilder<F>;\n\n /** Add a resolver */\n withResolver<R extends Requirement>(\n id: string,\n resolver: OrchestratorResolver<F, R>\n ): OrchestratorBuilder<F>;\n\n /** Add an input guardrail */\n withInputGuardrail(\n nameOrGuardrail: string | NamedGuardrail<InputGuardrailData>,\n fn?: GuardrailFn<InputGuardrailData>\n ): OrchestratorBuilder<F>;\n\n /** Add an output guardrail */\n withOutputGuardrail(\n nameOrGuardrail: string | NamedGuardrail<OutputGuardrailData>,\n fn?: GuardrailFn<OutputGuardrailData>\n ): OrchestratorBuilder<F>;\n\n /** Add a tool call guardrail */\n withToolCallGuardrail(\n nameOrGuardrail: string | NamedGuardrail<ToolCallGuardrailData>,\n fn?: GuardrailFn<ToolCallGuardrailData>\n ): OrchestratorBuilder<F>;\n\n /** Add a plugin */\n withPlugin(plugin: Plugin): OrchestratorBuilder<F>;\n\n /** Set memory instance for auto context injection and message storage */\n withMemory(memory: AgentMemory): OrchestratorBuilder<F>;\n\n /** Set circuit breaker to wrap all run() calls */\n withCircuitBreaker(cb: CircuitBreaker): OrchestratorBuilder<F>;\n\n /** Set max token budget */\n withBudget(maxTokens: number): OrchestratorBuilder<F>;\n\n /** Enable debug mode */\n withDebug(enabled?: boolean): OrchestratorBuilder<F>;\n\n /** Build the orchestrator */\n build(options: {\n runner: AgentRunner;\n autoApproveToolCalls?: boolean;\n onApprovalRequest?: (request: ApprovalRequest) => void;\n }): AgentOrchestrator<F>;\n}\n\n/**\n * Create a type-safe orchestrator builder.\n *\n * @example\n * ```typescript\n * const orchestrator = createOrchestratorBuilder<MyFacts>()\n * .withConstraint('budget', {\n * when: (facts) => facts.cost > 100,\n * require: { type: 'PAUSE' },\n * })\n * .withInputGuardrail('pii', createPIIGuardrail())\n * .withOutputGuardrail('toxicity', createModerationGuardrail({ ... }))\n * .withBudget(10000)\n * .withDebug()\n * .build({ runner });\n * ```\n */\nexport function createOrchestratorBuilder<\n F extends Record<string, unknown> = Record<string, never>\n>(): OrchestratorBuilder<F> {\n const constraints: Record<string, OrchestratorConstraint<F>> = {};\n const resolvers: Record<string, OrchestratorResolver<F, Requirement>> = {};\n const inputGuardrails: NamedGuardrail<InputGuardrailData>[] = [];\n const outputGuardrails: NamedGuardrail<OutputGuardrailData>[] = [];\n const toolCallGuardrails: NamedGuardrail<ToolCallGuardrailData>[] = [];\n const plugins: Plugin[] = [];\n let maxTokenBudget: number | undefined;\n let debug = false;\n let memoryInstance: AgentMemory | undefined;\n let circuitBreakerInstance: CircuitBreaker | undefined;\n\n const builder: OrchestratorBuilder<F> = {\n withConstraint(id, constraint) {\n constraints[id] = constraint;\n return builder;\n },\n\n withResolver(id, resolver) {\n resolvers[id] = resolver as unknown as OrchestratorResolver<F, Requirement>;\n return builder;\n },\n\n withInputGuardrail(nameOrGuardrail, fn) {\n if (typeof nameOrGuardrail === \"string\" && fn) {\n inputGuardrails.push({ name: nameOrGuardrail, fn });\n } else if (typeof nameOrGuardrail === \"object\") {\n inputGuardrails.push(nameOrGuardrail);\n }\n return builder;\n },\n\n withOutputGuardrail(nameOrGuardrail, fn) {\n if (typeof nameOrGuardrail === \"string\" && fn) {\n outputGuardrails.push({ name: nameOrGuardrail, fn });\n } else if (typeof nameOrGuardrail === \"object\") {\n outputGuardrails.push(nameOrGuardrail);\n }\n return builder;\n },\n\n withToolCallGuardrail(nameOrGuardrail, fn) {\n if (typeof nameOrGuardrail === \"string\" && fn) {\n toolCallGuardrails.push({ name: nameOrGuardrail, fn });\n } else if (typeof nameOrGuardrail === \"object\") {\n toolCallGuardrails.push(nameOrGuardrail);\n }\n return builder;\n },\n\n withPlugin(plugin) {\n plugins.push(plugin);\n return builder;\n },\n\n withMemory(mem) {\n memoryInstance = mem;\n return builder;\n },\n\n withCircuitBreaker(cb) {\n circuitBreakerInstance = cb;\n return builder;\n },\n\n withBudget(maxTokens) {\n maxTokenBudget = maxTokens;\n return builder;\n },\n\n withDebug(enabled = true) {\n debug = enabled;\n return builder;\n },\n\n build(options) {\n return createAgentOrchestrator<F>({\n runner: options.runner,\n autoApproveToolCalls: options.autoApproveToolCalls,\n onApprovalRequest: options.onApprovalRequest,\n constraints,\n resolvers,\n guardrails: {\n input: inputGuardrails,\n output: outputGuardrails,\n toolCall: toolCallGuardrails,\n },\n plugins,\n maxTokenBudget,\n debug,\n memory: memoryInstance,\n circuitBreaker: circuitBreakerInstance,\n });\n },\n };\n\n return builder;\n}\n\n// (createRunner moved to openai-agents-helpers.ts)\n\n// ============================================================================\n// Re-exports from Sub-modules\n// ============================================================================\n\n// Memory system\nexport {\n createAgentMemory,\n createSlidingWindowStrategy,\n createTokenBasedStrategy,\n createHybridStrategy,\n createTruncationSummarizer,\n createKeyPointsSummarizer,\n createLLMSummarizer,\n type AgentMemory,\n type AgentMemoryConfig,\n type MemoryState,\n type MemoryManageResult,\n type MemoryStrategy,\n type MemoryStrategyConfig,\n type MemoryStrategyResult,\n type MessageSummarizer,\n} from \"./memory.js\";\n\n// Streaming utilities\nexport {\n createStreamingRunner,\n createLengthStreamingGuardrail,\n createPatternStreamingGuardrail,\n createToxicityStreamingGuardrail,\n combineStreamingGuardrails,\n adaptOutputGuardrail,\n collectTokens,\n tapStream,\n filterStream,\n mapStream,\n type TokenChunk,\n type ToolStartChunk,\n type ToolEndChunk,\n type MessageChunk,\n type GuardrailTriggeredChunk,\n type ProgressChunk,\n type DoneChunk,\n type ErrorChunk,\n type StreamChunk,\n type StreamRunOptions,\n type StreamRunner,\n type StreamingRunResult,\n type StreamingGuardrail,\n type StreamingGuardrailResult,\n type BackpressureStrategy,\n} from \"./streaming.js\";\n\n// Multi-agent orchestration\nexport {\n createMultiAgentOrchestrator,\n Semaphore,\n parallel,\n sequential,\n supervisor,\n selectAgent,\n runAgentRequirement,\n concatResults,\n pickBestResult,\n collectOutputs,\n aggregateTokens,\n type MultiAgentOrchestrator,\n type MultiAgentOrchestratorOptions,\n type MultiAgentState,\n type AgentRegistration,\n type AgentRegistry,\n type AgentRunState,\n type ExecutionPattern,\n type ParallelPattern,\n type SequentialPattern,\n type SupervisorPattern,\n type HandoffRequest,\n type HandoffResult,\n type AgentSelectionConstraint,\n type RunAgentRequirement,\n} from \"./multi.js\";\n\n// Agent communication\nexport {\n createMessageBus,\n createAgentNetwork,\n createResponder,\n createDelegator,\n createPubSub,\n type MessageBus,\n type MessageBusConfig,\n type AgentNetwork,\n type AgentNetworkConfig,\n type AgentInfo,\n type AgentMessage,\n type AgentMessageType,\n type TypedAgentMessage,\n type RequestMessage,\n type ResponseMessage,\n type DelegationMessage,\n type DelegationResultMessage,\n type QueryMessage,\n type InformMessage,\n type UpdateMessage,\n type MessageHandler,\n type Subscription,\n type MessageFilter,\n} from \"./communication.js\";\n\n// Observability\nexport {\n createObservability,\n createAgentMetrics,\n type ObservabilityInstance,\n type ObservabilityConfig,\n type MetricType,\n type MetricDataPoint,\n type AggregatedMetric,\n type TraceSpan,\n type AlertConfig,\n type AlertEvent,\n type DashboardData,\n} from \"@directive-run/core/plugins\";\n\n// OTLP Exporter\nexport {\n createOTLPExporter,\n type OTLPExporterConfig,\n type OTLPExporter,\n} from \"@directive-run/core/plugins\";\n\n// Circuit Breaker\nexport {\n createCircuitBreaker,\n CircuitBreakerOpenError,\n type CircuitBreaker,\n type CircuitBreakerConfig,\n type CircuitBreakerStats,\n type CircuitState,\n} from \"@directive-run/core/plugins\";\n\n// Audit Trail\nexport {\n createAuditTrail,\n createAgentAuditHandlers,\n type AuditPluginConfig,\n type AuditInstance,\n} from \"./plugins/audit.js\";\n\n// Prompt Injection Guardrails\nexport {\n createPromptInjectionGuardrail,\n createUntrustedContentGuardrail,\n detectPromptInjection,\n sanitizeInjection,\n markUntrustedContent,\n DEFAULT_INJECTION_PATTERNS,\n STRICT_INJECTION_PATTERNS,\n type PromptInjectionGuardrailOptions,\n} from \"./guardrails/prompt-injection.js\";\n\n// Compliance (GDPR/CCPA)\nexport {\n createCompliance,\n createInMemoryComplianceStorage,\n type ComplianceConfig,\n type ComplianceInstance,\n type ComplianceStorage,\n} from \"./plugins/compliance.js\";\n\n// Enhanced PII Guardrails\nexport {\n createEnhancedPIIGuardrail,\n createOutputPIIGuardrail,\n detectPII,\n redactPII,\n type EnhancedPIIGuardrailOptions,\n} from \"./guardrails/pii-enhanced.js\";\n\n// ANN Index\nexport {\n createBruteForceIndex,\n createVPTreeIndex,\n type ANNIndex,\n type ANNSearchResult,\n type VPTreeIndexConfig,\n} from \"./guardrails/ann-index.js\";\n\nexport {\n createSemanticCache,\n createSemanticCacheGuardrail,\n createBatchedEmbedder,\n createTestEmbedder,\n createInMemoryStorage,\n type Embedding,\n type SemanticCache,\n type SemanticCacheConfig,\n type CacheEntry,\n type CacheLookupResult,\n type CacheStats,\n type SemanticCacheStorage,\n type BatchedEmbedder,\n type EmbedderFn,\n} from \"./guardrails/semantic-cache.js\";\n\n// Stream Channels\nexport {\n createStreamChannel,\n createBidirectionalStream,\n pipeThrough,\n mergeStreams,\n type StreamChannel,\n type StreamChannelConfig,\n type StreamChannelState,\n type BidirectionalStream,\n} from \"./stream-channel.js\";\n\n// Agent Stack — Composition API\nexport {\n createAgentStack,\n type AgentStack,\n type AgentStackConfig,\n type AgentStackState,\n type StackRunOptions,\n type StackStreamOptions,\n type StructuredRunOptions,\n type TokenStream,\n type StreamingCallbackRunner,\n} from \"./stack.js\";\n\n// AI Bridge — Sync AgentStack state into Directive system\nexport { createAISyncer } from \"./bridge.js\";\n\n// RAG Enricher\nexport {\n createRAGEnricher,\n createJSONFileStore,\n type RAGChunk,\n type RAGStorage,\n type RAGEnricherConfig,\n type RAGEnrichOptions,\n type RAGEnricher,\n type JSONFileStoreOptions,\n} from \"./rag.js\";\n\n// SSE Transport\nexport {\n createSSETransport,\n type SSEEvent,\n type SSETransportConfig,\n type SSETransport,\n} from \"./sse-transport.js\";\n\n// P2: Intelligent Retry\nexport {\n withRetry,\n parseHttpStatus,\n parseRetryAfter,\n RetryExhaustedError,\n type RetryConfig,\n} from \"./retry.js\";\n\n// P0: Provider Fallback\nexport {\n withFallback,\n AllProvidersFailedError,\n type FallbackConfig,\n} from \"./fallback.js\";\n\n// P1: Cost Budget Guards\nexport {\n withBudget,\n BudgetExceededError,\n type BudgetConfig,\n type BudgetRunner,\n type BudgetWindow,\n type TokenPricing,\n type BudgetExceededDetails,\n} from \"./budget.js\";\n\n// P3: Smart Model Selection\nexport {\n withModelSelection,\n byInputLength,\n byAgentName,\n byPattern,\n type ModelRule,\n type ModelSelectionConfig,\n} from \"./model-selector.js\";\n\n// P6: Structured Outputs\nexport {\n withStructuredOutput,\n extractJsonFromOutput,\n StructuredOutputError,\n type StructuredOutputConfig,\n type SafeParseable,\n type SafeParseResult,\n} from \"./structured-output.js\";\n\n// P5: Batch Queue\nexport {\n createBatchQueue,\n type BatchQueue,\n type BatchQueueConfig,\n} from \"./batch.js\";\n\n// P4: Constraint-Driven Provider Routing\nexport {\n createConstraintRouter,\n type ConstraintRouterConfig,\n type ConstraintRouterRunner,\n type RoutingProvider,\n type RoutingFacts,\n type ProviderStats,\n type RoutingConstraint,\n} from \"./provider-routing.js\";\n\n// MCP (Model Context Protocol)\nexport {\n createMCPAdapter,\n convertToolsForLLM,\n mcpCallTool,\n mcpReadResource,\n mcpGetPrompt,\n mcpSyncResources,\n type MCPAdapter,\n} from \"./mcp.js\";\nexport type {\n MCPAdapterConfig,\n MCPTool,\n MCPToolResult,\n MCPToolConstraint,\n MCPServerConfig,\n MCPResource,\n MCPApprovalRequest,\n MCPCallToolRequirement,\n MCPReadResourceRequirement,\n MCPGetPromptRequirement,\n MCPSyncResourcesRequirement,\n MCPRequirement,\n} from \"./mcp-types.js\";\n","/**\n * OpenAI Agents Testing Utilities\n *\n * Provides testing helpers for:\n * - Mock agent runners with configurable responses\n * - Guardrail testing with assertions\n * - Approval workflow simulation\n * - Snapshot testing for constraint evaluation\n *\n * @example\n * ```typescript\n * import { createMockAgentRunner, testGuardrail, createApprovalSimulator } from '@directive-run/ai';\n *\n * describe('MyOrchestrator', () => {\n * it('should block PII in input', async () => {\n * const result = await testGuardrail(createPIIGuardrail(), {\n * input: 'My SSN is 123-45-6789',\n * });\n * expect(result.passed).toBe(false);\n * expect(result.reason).toContain('PII');\n * });\n * });\n * ```\n */\n\nimport type {\n AgentLike,\n RunResult,\n Message,\n ToolCall,\n RunOptions,\n AgentRunner,\n GuardrailFn,\n InputGuardrailData,\n OutputGuardrailData,\n ToolCallGuardrailData,\n GuardrailContext,\n GuardrailResult,\n ApprovalRequest,\n OrchestratorOptions,\n AgentOrchestrator,\n} from \"./index.js\";\nimport { createAgentOrchestrator } from \"./index.js\";\n\n// ============================================================================\n// Mock Agent Runner\n// ============================================================================\n\n/** Configuration for mock agent responses */\nexport interface MockAgentConfig<T = unknown> {\n /** Final output to return */\n output: T;\n /** Messages to emit during run */\n messages?: Message[];\n /** Tool calls to emit during run */\n toolCalls?: ToolCall[];\n /** Total tokens to report */\n totalTokens?: number;\n /** Delay before responding (ms) */\n delay?: number;\n /** Error to throw instead of returning */\n error?: Error;\n /** Function to generate dynamic responses */\n generate?: (input: string, agent: AgentLike) => Partial<MockAgentConfig<T>>;\n}\n\n/** Mock agent runner options */\nexport interface MockAgentRunnerOptions {\n /** Default response for unmatched agents */\n defaultResponse?: MockAgentConfig;\n /** Responses keyed by agent name */\n responses?: Record<string, MockAgentConfig>;\n /** Record all calls for assertions */\n recordCalls?: boolean;\n /** Callback for each run */\n onRun?: (agent: AgentLike, input: string) => void;\n}\n\n/** Recorded call for assertions */\nexport interface RecordedCall {\n agent: AgentLike;\n input: string;\n options?: RunOptions;\n timestamp: number;\n}\n\n/** Mock agent runner instance */\nexport interface MockAgentRunner {\n /** The run function to pass to orchestrator */\n run: AgentRunner;\n /** Get all recorded calls */\n getCalls(): RecordedCall[];\n /** Get calls for a specific agent */\n getCallsFor(agentName: string): RecordedCall[];\n /** Clear recorded calls */\n clearCalls(): void;\n /** Set response for an agent */\n setResponse<T>(agentName: string, config: MockAgentConfig<T>): void;\n /** Set default response */\n setDefaultResponse<T>(config: MockAgentConfig<T>): void;\n}\n\n/**\n * Create a mock agent runner for testing.\n *\n * @example\n * ```typescript\n * const mock = createMockAgentRunner({\n * responses: {\n * 'my-agent': {\n * output: 'Hello, world!',\n * totalTokens: 100,\n * },\n * },\n * });\n *\n * const orchestrator = createAgentOrchestrator({ runner: mock.run });\n * const result = await orchestrator.run(myAgent, 'Hi');\n *\n * expect(result.output).toBe('Hello, world!');\n * expect(mock.getCalls()).toHaveLength(1);\n * ```\n */\nexport function createMockAgentRunner(\n options: MockAgentRunnerOptions = {}\n): MockAgentRunner {\n const {\n defaultResponse = { output: \"mock response\", totalTokens: 10 },\n responses = {},\n recordCalls = true,\n onRun,\n } = options;\n\n const calls: RecordedCall[] = [];\n const responseMap = new Map<string, MockAgentConfig>(Object.entries(responses));\n let currentDefault = defaultResponse;\n\n const run: AgentRunner = async <T>(\n agent: AgentLike,\n input: string,\n runOptions?: RunOptions\n ): Promise<RunResult<T>> => {\n onRun?.(agent, input);\n\n if (recordCalls) {\n calls.push({\n agent,\n input,\n options: runOptions,\n timestamp: Date.now(),\n });\n }\n\n // Get config for this agent\n let config = responseMap.get(agent.name) ?? currentDefault;\n\n // Apply dynamic generation if present\n if (config.generate) {\n const generated = config.generate(input, agent);\n config = { ...config, ...generated };\n }\n\n // Handle error case\n if (config.error) {\n throw config.error;\n }\n\n // Apply delay\n if (config.delay && config.delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, config.delay));\n }\n\n // Emit messages\n const messages = config.messages ?? [];\n for (const message of messages) {\n runOptions?.onMessage?.(message);\n }\n\n // Emit tool calls\n const toolCalls = config.toolCalls ?? [];\n for (const toolCall of toolCalls) {\n runOptions?.onToolCall?.(toolCall);\n }\n\n return {\n output: config.output as T,\n messages,\n toolCalls,\n totalTokens: config.totalTokens ?? 10,\n };\n };\n\n return {\n run,\n getCalls: () => [...calls],\n getCallsFor: (name) => calls.filter((c) => c.agent.name === name),\n clearCalls: () => calls.length = 0,\n setResponse: (name, config) => responseMap.set(name, config),\n setDefaultResponse: (config) => currentDefault = config,\n };\n}\n\n// ============================================================================\n// Guardrail Testing\n// ============================================================================\n\n/** Test input for guardrail testing */\nexport type GuardrailTestInput<T> =\n T extends InputGuardrailData ? { input: string; agentName?: string } :\n T extends OutputGuardrailData ? { output: unknown; agentName?: string; input?: string; messages?: Message[] } :\n T extends ToolCallGuardrailData ? { toolCall: ToolCall; agentName?: string; input?: string } :\n Partial<T>;\n\n/** Extended guardrail result with test assertions */\nexport interface GuardrailTestResult extends GuardrailResult {\n /** Time taken to evaluate (ms) */\n duration: number;\n /** The data that was tested */\n testedData: unknown;\n /** Assert that the guardrail passed */\n assertPassed(): void;\n /** Assert that the guardrail failed */\n assertFailed(expectedReason?: string | RegExp): void;\n /** Assert that transformation occurred */\n assertTransformed(expected?: unknown): void;\n}\n\n/**\n * Test a guardrail with assertions.\n *\n * @example\n * ```typescript\n * // Test PII detection\n * const result = await testGuardrail(createPIIGuardrail(), {\n * input: 'My SSN is 123-45-6789',\n * });\n * result.assertFailed(/PII/);\n *\n * // Test input transformation\n * const redactResult = await testGuardrail(createPIIGuardrail({ redact: true }), {\n * input: 'My SSN is 123-45-6789',\n * });\n * redactResult.assertPassed();\n * redactResult.assertTransformed();\n * ```\n */\nexport async function testGuardrail<T>(\n guardrail: GuardrailFn<T>,\n testInput: GuardrailTestInput<T>,\n context?: Partial<GuardrailContext>\n): Promise<GuardrailTestResult> {\n // Build full data object\n const data = {\n agentName: \"test-agent\",\n input: \"\",\n ...testInput,\n } as unknown as T;\n\n // Build context\n const fullContext: GuardrailContext = {\n agentName: (testInput as { agentName?: string }).agentName ?? \"test-agent\",\n input: (testInput as { input?: string }).input ?? \"\",\n facts: context?.facts ?? {},\n ...context,\n };\n\n const start = Date.now();\n const result = await guardrail(data, fullContext);\n const duration = Date.now() - start;\n\n return {\n ...result,\n duration,\n testedData: data,\n assertPassed() {\n if (!result.passed) {\n throw new Error(`Expected guardrail to pass, but it failed: ${result.reason}`);\n }\n },\n assertFailed(expectedReason) {\n if (result.passed) {\n throw new Error(\"Expected guardrail to fail, but it passed\");\n }\n if (expectedReason !== undefined) {\n if (typeof expectedReason === \"string\" && !result.reason?.includes(expectedReason)) {\n throw new Error(\n `Expected failure reason to include \"${expectedReason}\", got: ${result.reason}`\n );\n }\n if (expectedReason instanceof RegExp && !expectedReason.test(result.reason ?? \"\")) {\n throw new Error(\n `Expected failure reason to match ${expectedReason}, got: ${result.reason}`\n );\n }\n }\n },\n assertTransformed(expected) {\n if (result.transformed === undefined) {\n throw new Error(\"Expected guardrail to transform input, but no transformation occurred\");\n }\n if (expected !== undefined && result.transformed !== expected) {\n throw new Error(\n `Expected transformation to be ${JSON.stringify(expected)}, got: ${JSON.stringify(result.transformed)}`\n );\n }\n },\n };\n}\n\n/**\n * Test multiple inputs against a guardrail.\n *\n * @example\n * ```typescript\n * const results = await testGuardrailBatch(createPIIGuardrail(), [\n * { input: 'Hello world', expect: 'pass' },\n * { input: 'My SSN is 123-45-6789', expect: 'fail' },\n * { input: 'Email: test@example.com', expect: 'fail' },\n * ]);\n *\n * expect(results.allPassed()).toBe(true);\n * ```\n */\nexport async function testGuardrailBatch<T>(\n guardrail: GuardrailFn<T>,\n testCases: Array<{\n input: GuardrailTestInput<T>;\n expect: \"pass\" | \"fail\" | \"transform\";\n context?: Partial<GuardrailContext>;\n }>\n): Promise<{\n results: GuardrailTestResult[];\n allPassed(): boolean;\n failures(): Array<{ index: number; expected: string; actual: GuardrailTestResult }>;\n}> {\n const results: GuardrailTestResult[] = [];\n const failures: Array<{ index: number; expected: string; actual: GuardrailTestResult }> = [];\n\n for (let i = 0; i < testCases.length; i++) {\n const testCase = testCases[i]!;\n const result = await testGuardrail(guardrail, testCase.input, testCase.context);\n results.push(result);\n\n const actualOutcome = !result.passed ? \"fail\" : result.transformed !== undefined ? \"transform\" : \"pass\";\n\n if (actualOutcome !== testCase.expect) {\n failures.push({ index: i, expected: testCase.expect, actual: result });\n }\n }\n\n return {\n results,\n allPassed: () => failures.length === 0,\n failures: () => failures,\n };\n}\n\n// ============================================================================\n// Approval Simulation\n// ============================================================================\n\n/** Approval simulator options */\nexport interface ApprovalSimulatorOptions {\n /** Auto-approve requests matching this predicate */\n autoApprove?: (request: ApprovalRequest) => boolean;\n /** Auto-reject requests matching this predicate */\n autoReject?: (request: ApprovalRequest) => boolean | string;\n /** Delay before auto-approval/rejection (ms) */\n delay?: number;\n /** Record all requests for assertions */\n recordRequests?: boolean;\n}\n\n/** Approval simulator instance */\nexport interface ApprovalSimulator {\n /** Handle an approval request */\n handle(request: ApprovalRequest): Promise<\"approved\" | \"rejected\">;\n /** Get all recorded requests */\n getRequests(): ApprovalRequest[];\n /** Clear recorded requests */\n clearRequests(): void;\n /** Manually approve a request */\n approve(requestId: string): void;\n /** Manually reject a request */\n reject(requestId: string, reason?: string): void;\n /** Wait for a specific request */\n waitForRequest(predicate: (req: ApprovalRequest) => boolean, timeoutMs?: number): Promise<ApprovalRequest>;\n}\n\n/**\n * Create an approval simulator for testing approval workflows.\n *\n * @example\n * ```typescript\n * const simulator = createApprovalSimulator({\n * autoApprove: (req) => req.type === 'tool_call' && req.data.name === 'search',\n * autoReject: (req) => req.type === 'tool_call' && req.data.name === 'delete',\n * });\n *\n * // Use in tests\n * orchestrator.onApprovalRequest = (req) => simulator.handle(req);\n * ```\n */\nexport function createApprovalSimulator(\n options: ApprovalSimulatorOptions = {}\n): ApprovalSimulator {\n const {\n autoApprove,\n autoReject,\n delay = 0,\n recordRequests = true,\n } = options;\n\n const requests: ApprovalRequest[] = [];\n const pendingRequests = new Map<string, { request: ApprovalRequest; resolve: (decision: \"approved\" | \"rejected\") => void }>();\n const requestWaiters: Array<{ predicate: (req: ApprovalRequest) => boolean; resolve: (req: ApprovalRequest) => void }> = [];\n\n return {\n async handle(request: ApprovalRequest): Promise<\"approved\" | \"rejected\"> {\n if (recordRequests) {\n requests.push(request);\n }\n\n // Notify waiters\n for (const waiter of requestWaiters) {\n if (waiter.predicate(request)) {\n waiter.resolve(request);\n }\n }\n\n // Apply delay\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n // Check auto-reject first (security-first)\n if (autoReject) {\n const rejectResult = autoReject(request);\n if (rejectResult) {\n return \"rejected\";\n }\n }\n\n // Check auto-approve\n if (autoApprove && autoApprove(request)) {\n return \"approved\";\n }\n\n // Wait for manual decision\n return new Promise((resolve) => {\n pendingRequests.set(request.id, { request, resolve });\n });\n },\n\n getRequests: () => [...requests],\n clearRequests: () => requests.length = 0,\n\n approve(requestId: string) {\n const pending = pendingRequests.get(requestId);\n if (pending) {\n pending.resolve(\"approved\");\n pendingRequests.delete(requestId);\n }\n },\n\n reject(requestId: string, _reason?: string) {\n const pending = pendingRequests.get(requestId);\n if (pending) {\n pending.resolve(\"rejected\");\n pendingRequests.delete(requestId);\n }\n },\n\n waitForRequest(predicate, timeoutMs = 5000): Promise<ApprovalRequest> {\n // Check existing requests first\n const existing = requests.find(predicate);\n if (existing) {\n return Promise.resolve(existing);\n }\n\n // Wait for future request\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new Error(\"Timeout waiting for approval request\"));\n }, timeoutMs);\n\n requestWaiters.push({\n predicate,\n resolve: (req) => {\n clearTimeout(timeout);\n resolve(req);\n },\n });\n });\n },\n };\n}\n\n// ============================================================================\n// Test Orchestrator Factory\n// ============================================================================\n\n/** Options for test orchestrator */\nexport interface TestOrchestratorOptions<F extends Record<string, unknown>> extends Omit<OrchestratorOptions<F>, \"runner\"> {\n /** Mock responses for agents */\n mockResponses?: Record<string, MockAgentConfig>;\n /** Default mock response */\n defaultMockResponse?: MockAgentConfig;\n}\n\n/** Test orchestrator with additional testing utilities */\nexport interface TestOrchestrator<F extends Record<string, unknown>> extends AgentOrchestrator<F> {\n /** The mock runner */\n mockRunner: MockAgentRunner;\n /** Approval simulator */\n approvalSimulator: ApprovalSimulator;\n /** Get recorded agent calls */\n getCalls(): RecordedCall[];\n /** Get approval requests */\n getApprovalRequests(): ApprovalRequest[];\n /** Reset all state */\n resetAll(): void;\n}\n\n/**\n * Create a test orchestrator with mocking and simulation built in.\n *\n * @example\n * ```typescript\n * const test = createTestOrchestrator({\n * mockResponses: {\n * 'my-agent': { output: 'test response' },\n * },\n * constraints: {\n * needsApproval: {\n * when: () => true,\n * require: { type: 'NEED_APPROVAL' },\n * },\n * },\n * });\n *\n * await test.run(myAgent, 'Hello');\n * expect(test.getCalls()).toHaveLength(1);\n * ```\n */\nexport function createTestOrchestrator<F extends Record<string, unknown> = Record<string, never>>(\n options: TestOrchestratorOptions<F> = {}\n): TestOrchestrator<F> {\n const {\n mockResponses,\n defaultMockResponse,\n ...orchestratorOptions\n } = options;\n\n const mockRunner = createMockAgentRunner({\n responses: mockResponses,\n defaultResponse: defaultMockResponse,\n });\n\n const approvalSimulator = createApprovalSimulator();\n\n const orchestrator = createAgentOrchestrator<F>({\n ...orchestratorOptions,\n runner: mockRunner.run,\n onApprovalRequest: (req) => {\n approvalSimulator.handle(req);\n orchestratorOptions.onApprovalRequest?.(req);\n },\n });\n\n return {\n ...orchestrator,\n mockRunner,\n approvalSimulator,\n getCalls: () => mockRunner.getCalls(),\n getApprovalRequests: () => approvalSimulator.getRequests(),\n resetAll() {\n orchestrator.reset();\n mockRunner.clearCalls();\n approvalSimulator.clearRequests();\n },\n };\n}\n\n// ============================================================================\n// Snapshot Testing\n// ============================================================================\n\n/** Constraint evaluation snapshot */\nexport interface ConstraintSnapshot {\n constraintId: string;\n triggered: boolean;\n requirement?: unknown;\n facts: Record<string, unknown>;\n timestamp: number;\n}\n\n/**\n * Create a constraint evaluation recorder for snapshot testing.\n *\n * @example\n * ```typescript\n * const recorder = createConstraintRecorder();\n * const orchestrator = createAgentOrchestrator({\n * plugins: [recorder.plugin],\n * });\n *\n * await orchestrator.run(agent, 'Hello');\n *\n * expect(recorder.getSnapshots()).toMatchSnapshot();\n * ```\n */\nexport function createConstraintRecorder(): {\n plugin: {\n name: string;\n onRequirementCreated: (data: { constraintId: string; requirement: unknown; facts: unknown }) => void;\n };\n getSnapshots(): ConstraintSnapshot[];\n clearSnapshots(): void;\n} {\n const snapshots: ConstraintSnapshot[] = [];\n\n return {\n plugin: {\n name: \"constraint-recorder\",\n onRequirementCreated(data) {\n snapshots.push({\n constraintId: data.constraintId,\n triggered: true,\n requirement: data.requirement,\n facts: data.facts as Record<string, unknown>,\n timestamp: Date.now(),\n });\n },\n },\n getSnapshots: () => [...snapshots],\n clearSnapshots: () => snapshots.length = 0,\n };\n}\n\n// ============================================================================\n// Assertion Helpers\n// ============================================================================\n\n/**\n * Assert that an orchestrator has specific state.\n *\n * @example\n * ```typescript\n * assertOrchestratorState(orchestrator, {\n * agentStatus: 'completed',\n * tokenUsage: { min: 0, max: 1000 },\n * pendingApprovals: 0,\n * });\n * ```\n */\nexport function assertOrchestratorState<F extends Record<string, unknown>>(\n orchestrator: AgentOrchestrator<F>,\n expected: {\n agentStatus?: \"idle\" | \"running\" | \"paused\" | \"completed\" | \"error\";\n tokenUsage?: { min?: number; max?: number; exact?: number };\n pendingApprovals?: number;\n conversationLength?: { min?: number; max?: number; exact?: number };\n }\n): void {\n const state = orchestrator.facts;\n\n if (expected.agentStatus !== undefined && state.agent.status !== expected.agentStatus) {\n throw new Error(\n `Expected agent status to be \"${expected.agentStatus}\", got \"${state.agent.status}\"`\n );\n }\n\n if (expected.tokenUsage !== undefined) {\n const { min, max, exact } = expected.tokenUsage;\n if (exact !== undefined && state.agent.tokenUsage !== exact) {\n throw new Error(\n `Expected token usage to be exactly ${exact}, got ${state.agent.tokenUsage}`\n );\n }\n if (min !== undefined && state.agent.tokenUsage < min) {\n throw new Error(\n `Expected token usage to be at least ${min}, got ${state.agent.tokenUsage}`\n );\n }\n if (max !== undefined && state.agent.tokenUsage > max) {\n throw new Error(\n `Expected token usage to be at most ${max}, got ${state.agent.tokenUsage}`\n );\n }\n }\n\n if (expected.pendingApprovals !== undefined && state.approval.pending.length !== expected.pendingApprovals) {\n throw new Error(\n `Expected ${expected.pendingApprovals} pending approvals, got ${state.approval.pending.length}`\n );\n }\n\n if (expected.conversationLength !== undefined) {\n const { min, max, exact } = expected.conversationLength;\n const len = state.conversation.length;\n if (exact !== undefined && len !== exact) {\n throw new Error(`Expected conversation length to be exactly ${exact}, got ${len}`);\n }\n if (min !== undefined && len < min) {\n throw new Error(`Expected conversation length to be at least ${min}, got ${len}`);\n }\n if (max !== undefined && len > max) {\n throw new Error(`Expected conversation length to be at most ${max}, got ${len}`);\n }\n }\n}\n\n// ============================================================================\n// Fake Timers Support\n// ============================================================================\n\n/**\n * Create a time controller for testing time-dependent behavior.\n *\n * @example\n * ```typescript\n * const time = createTimeController();\n *\n * // Override Date.now\n * const originalNow = Date.now;\n * Date.now = () => time.now();\n *\n * time.advance(1000); // Advance 1 second\n *\n * // Restore\n * Date.now = originalNow;\n * ```\n */\nexport function createTimeController(startTime = Date.now()): {\n now(): number;\n advance(ms: number): void;\n set(time: number): void;\n reset(): void;\n} {\n let currentTime = startTime;\n const initial = startTime;\n\n return {\n now: () => currentTime,\n advance: (ms) => { currentTime += ms; },\n set: (time) => { currentTime = time; },\n reset: () => { currentTime = initial; },\n };\n}\n"]}
|