@directive-run/ai 1.17.1 → 1.18.0
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/dist/{chunk-7DPTXZZI.cjs → chunk-7EJN6TYX.cjs} +4 -4
- package/dist/chunk-7EJN6TYX.cjs.map +1 -0
- package/dist/chunk-D72LIBH2.js +16 -0
- package/dist/chunk-D72LIBH2.js.map +1 -0
- package/dist/{chunk-FN4GUZAI.js → chunk-G7CRWJT7.js} +4 -4
- package/dist/chunk-G7CRWJT7.js.map +1 -0
- package/dist/{chunk-56LYSE63.js → chunk-RHJAMXLS.js} +3 -3
- package/dist/{chunk-56LYSE63.js.map → chunk-RHJAMXLS.js.map} +1 -1
- package/dist/chunk-UZKM276C.cjs +16 -0
- package/dist/chunk-UZKM276C.cjs.map +1 -0
- package/dist/{chunk-PB276BX2.cjs → chunk-XGHNOSXT.cjs} +4 -4
- package/dist/{chunk-PB276BX2.cjs.map → chunk-XGHNOSXT.cjs.map} +1 -1
- package/dist/index.cjs +15 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +85 -2
- package/dist/index.d.ts +85 -2
- package/dist/index.js +15 -15
- package/dist/index.js.map +1 -1
- package/dist/multi-agent-orchestrator-OX2TKD5Y.cjs +2 -0
- package/dist/{multi-agent-orchestrator-KFYIDKTF.cjs.map → multi-agent-orchestrator-OX2TKD5Y.cjs.map} +1 -1
- package/dist/{multi-agent-orchestrator-ZHSMWIKP.js → multi-agent-orchestrator-RMTLPKB4.js} +2 -2
- package/dist/{multi-agent-orchestrator-ZHSMWIKP.js.map → multi-agent-orchestrator-RMTLPKB4.js.map} +1 -1
- package/dist/multi-agent.cjs +1 -1
- package/dist/multi-agent.d.cts +2 -2
- package/dist/multi-agent.d.ts +2 -2
- package/dist/multi-agent.js +1 -1
- package/dist/{orchestrator-types-ZK9lv5Sm.d.ts → orchestrator-types-D5cFRt3s.d.ts} +115 -0
- package/dist/{orchestrator-types-CbNE7Rjp.d.cts → orchestrator-types-Dlfcvdxw.d.cts} +115 -0
- package/dist/testing.cjs +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-7DPTXZZI.cjs.map +0 -1
- package/dist/chunk-D5APTMCT.cjs +0 -16
- package/dist/chunk-D5APTMCT.cjs.map +0 -1
- package/dist/chunk-FN4GUZAI.js.map +0 -1
- package/dist/chunk-YT4QN3KO.js +0 -16
- package/dist/chunk-YT4QN3KO.js.map +0 -1
- package/dist/multi-agent-orchestrator-KFYIDKTF.cjs +0 -2
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {q,f,r,g,i as i$1,k,m,o,p,n,s,x,w,h,c,d,e,l,j,a as a$2,u,t as t$1}from'./chunk-G7CRWJT7.js';import {i,a as a$1,d as d$1,g as g$1}from'./chunk-UR5BMWEN.js';import {a,b}from'./chunk-FBT73WFY.js';import {b as b$1}from'./chunk-HRR45JZX.js';import {t,createModule,createSystem}from'@directive-run/core';import {requirementGuard,createCallbackPlugin,setBridgeFact,getBridgeFact}from'@directive-run/core/adapter-utils';var Ke=500,Xe=200;function Rt(ke){let{runner:ee,factsSchema:ye={},init:ve,constraints:Ye={},resolvers:Ve={},guardrails:G={},onApprovalRequest:ie,autoApproveToolCalls:ue=true,maxTokenBudget:V,budgetWarningThreshold:te=.8,onBudgetWarning:be,plugins:Je=[],debug:we=false,approvalTimeoutMs:ce=3e5,agentRetry:re,hooks:Te={},memory:B,circuitBreaker:le,selfHealing:R,outputSchema:ze,maxSchemaRetries:Qe,checkpointStore:Re,breakpoints:_,onBreakpoint:Ze,breakpointTimeoutMs:et}=ke,E=typeof we=="object"?true:!!we,de=5e3;if(E&&R&&!le&&console.warn("[Directive] selfHealing config has no effect without a circuitBreaker \u2014 fallback behavior requires the circuit breaker to detect failures."),te<0||te>1)throw new Error(`[Directive Orchestrator] budgetWarningThreshold must be between 0 and 1, got ${te}`);if(!ue&&!ie)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`);function q$1(e,r){try{Te[e]?.(r);}catch(o){E&&console.debug(`[Directive] hooks.${e} threw:`,o);}}let Ae=["agent","approval","conversation","toolCalls"];for(let e of Object.keys(ye))if(Ae.includes(e))throw new Error(`[Directive] Facts schema key "${e}" conflicts with orchestrator state. Reserved keys: ${Ae.join(", ")}. Rename your fact to avoid the collision.`);let tt={facts:{...i.facts,...ye,__budgetWarningFired:t.boolean()},derivations:{},events:{},requirements:{}},Se,t$2,Ce=q(Ye);V&&(Ce.__budgetLimit={priority:100,when:e=>f(e).tokenUsage>V,require:{type:"__PAUSE_BUDGET_EXCEEDED"}});let Oe=r(Ve,(e,r,o,a)=>Se(e,r,o,a),()=>t$2.facts);Oe.__pause={requirement:requirementGuard("__PAUSE_BUDGET_EXCEEDED"),resolve:async(e,r)=>{let o=f(r.facts);g(r.facts,{...o,status:"paused"});}};let y=null;E&&(y=a({getSnapshotId:()=>{try{return t$2.history?.currentIndex??null}catch{return null}},goToSnapshot:e=>{try{t$2.history?.goTo?.(e);}catch{}}}));let rt=createCallbackPlugin("directive-ai-callbacks",{}),nt=createModule("directive-ai-orchestrator",{schema:tt,init:e=>{if(g(e,{status:"idle",currentAgent:null,input:null,output:null,error:null,tokenUsage:0,turnCount:0,startedAt:null,completedAt:null}),i$1(e,{pending:[],approved:[],rejected:[]}),k(e,[]),m(e,[]),o(e,{pending:[],resolved:[],cancelled:[]}),setBridgeFact(e,"__budgetWarningFired",false),ve){let r=p(e),o={...e,...r};ve(o);}},constraints:Ce,resolvers:Oe}),_e=[...Je,rt];E&&y&&_e.push(b(y,()=>{try{return t$2.history?.currentIndex??null}catch{return null}})),t$2=createSystem({module:nt,plugins:_e,history:E?true:void 0}),t$2.start();async function Ee(e,r,o,a,i){if(le)try{return await le.execute(()=>De(e,r,o,a,i))}catch(c){if(R){if(R.fallbackRunners)for(let p of R.fallbackRunners)try{let v={originalAgent:e.name,reroutedTo:"fallback-runner",reason:c instanceof Error?c.message:String(c),timestamp:Date.now()};try{R.onReroute?.(v);}catch{}return y&&y.record({type:"reroute",timestamp:Date.now(),agentId:e.name,snapshotId:null,from:e.name,to:"fallback-runner",reason:c instanceof Error?c.message:String(c)}),await p(e,r,a)}catch{}if(R.fallbackAgent)try{let p={originalAgent:e.name,reroutedTo:R.fallbackAgent.name,reason:c instanceof Error?c.message:String(c),timestamp:Date.now()};try{R.onReroute?.(p);}catch{}return y&&y.record({type:"reroute",timestamp:Date.now(),agentId:e.name,snapshotId:null,from:e.name,to:R.fallbackAgent.name,reason:c instanceof Error?c.message:String(c)}),await ee(R.fallbackAgent,r,a)}catch{}if(R.degradation==="fallback-response"&&R.fallbackResponse!==void 0)return {output:R.fallbackResponse,messages:[],toolCalls:[],totalTokens:0}}throw c}return De(e,r,o,a,i)}async function De(e$1,r,o,a,i){let c$1=Date.now();if(B){let n=B.getContextMessages();if(n.length>0){let u=n.map(g=>`${g.role}: ${g.content}`).join(`
|
|
4
|
+
`);e$1={...e$1,instructions:`${e$1.instructions??""}
|
|
5
|
+
|
|
6
|
+
Conversation context:
|
|
7
|
+
${u}`};}}if(ke.metaContext){let n=a$2(t$2.inspect());n&&(e$1={...e$1,instructions:`${e$1.instructions??""}
|
|
8
|
+
|
|
9
|
+
${n}`});}if(_&&_.length>0){let n={agentId:e$1.name,agentName:e$1.name,input:r,state:t$2.facts.$store.toObject(),breakpointType:"pre_input_guardrails"},u=await ne("pre_input_guardrails",n,i?.signal??a?.signal);if(u?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};u?.input&&(r=u.input);}let p=i?.inputGuardrails!==void 0?i.inputGuardrails:G.input??[],v=i?.outputGuardrails!==void 0?i.outputGuardrails:G.output??[],$=p.map((n,u)=>c(n,u,"input"));for(let n of $){let{name:u}=n,g={agentName:e$1.name,input:r,facts:t$2.facts.$store.toObject()},D=Date.now(),m=await d(n,{input:r,agentName:e$1.name},g);if(q$1("onGuardrailCheck",{agentId:e$1.name,guardrailName:u,guardrailType:"input",passed:m.passed,reason:m.reason,durationMs:Date.now()-D,timestamp:Date.now()}),!m.passed)throw new a$1({code:"INPUT_GUARDRAIL_FAILED",message:`Input guardrail "${u}" failed: ${m.reason}`,guardrailName:u,guardrailType:"input",userMessage:m.reason??"Input validation failed",agentName:e$1.name,input:r});m.transformed!==void 0&&(r=m.transformed);}if(q$1("onAgentStart",{agentName:e$1.name,input:r,timestamp:c$1}),y&&y.record({type:"agent_start",timestamp:Date.now(),agentId:e$1.name,snapshotId:null,inputLength:r.length,modelId:e$1.model??void 0,...e$1.instructions?{instructions:e$1.instructions.slice(0,de)}:{},input:r.slice(0,de)}),t$2.batch(()=>{let n=f(t$2.facts);g(t$2.facts,{...n,status:"running",currentAgent:e$1.name,input:r,startedAt:Date.now()});}),_&&_.length>0){let n={agentId:e$1.name,agentName:e$1.name,input:r,state:t$2.facts.$store.toObject(),breakpointType:"pre_agent_run"},u=await ne("pre_agent_run",n,i?.signal??a?.signal);if(u?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};u?.input&&(r=u.input);}let A=i?.outputSchema!==void 0?i.outputSchema:ze,C=ee;A&&(C=b$1(ee,{schema:A,maxRetries:i?.maxSchemaRetries??Qe??2}));let l$1=await e(C,e$1,r,{...a,signal:a?.signal,onMessage:n=>{let g=[...j(t$2.facts),n];k(t$2.facts,g.length>Ke?g.slice(-Ke):g),a?.onMessage?.(n);},onToolCall:async n=>{let u=(G.toolCall??[]).map((m,x)=>c(m,x,"toolCall"));for(let m of u){let{name:x}=m,M={agentName:e$1.name,input:r,facts:t$2.facts.$store.toObject()},d$1=Date.now(),b=await d(m,{toolCall:n,agentName:e$1.name,input:r},M);if(q$1("onGuardrailCheck",{agentId:e$1.name,guardrailName:x,guardrailType:"toolCall",passed:b.passed,reason:b.reason,durationMs:Date.now()-d$1,timestamp:Date.now()}),!b.passed)throw new a$1({code:"TOOL_CALL_GUARDRAIL_FAILED",message:`Tool call guardrail "${x}" failed: ${b.reason}`,guardrailName:x,guardrailType:"toolCall",userMessage:b.reason??"Tool call blocked",data:{toolCall:n},agentName:e$1.name,input:r})}if(!ue){let m=`tool-${n.id}`,x={id:m,type:"tool_call",agentName:e$1.name,description:`Tool call: ${n.name}`,data:n,requestedAt:Date.now()};t$2.batch(()=>{let M=h(t$2.facts);i$1(t$2.facts,{...M,pending:[...M.pending,x]});}),ie?.(x),await xe(m,i?.signal??a?.signal);}let D=[...l(t$2.facts),n];m(t$2.facts,D.length>Xe?D.slice(-Xe):D),a?.onToolCall?.(n);}},re?{...re,onRetry:(n,u,g)=>{re.onRetry?.(n,u,g),q$1("onAgentRetry",{agentName:e$1.name,input:r,attempt:n,error:u,delayMs:g,timestamp:Date.now()});}}:void 0);if(_&&_.length>0){let n={agentId:e$1.name,agentName:e$1.name,input:r,state:t$2.facts.$store.toObject(),breakpointType:"pre_output_guardrails"},u=await ne("pre_output_guardrails",n,i?.signal??a?.signal);if(u?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};u?.input&&(r=u.input);}let U=v.map((n,u)=>c(n,u,"output"));for(let n of U){let{name:u}=n,g={agentName:e$1.name,input:r,facts:t$2.facts.$store.toObject()},D=Date.now(),m=await d(n,{output:l$1.output,agentName:e$1.name,input:r,messages:l$1.messages},g);if(q$1("onGuardrailCheck",{agentId:e$1.name,guardrailName:u,guardrailType:"output",passed:m.passed,reason:m.reason,durationMs:Date.now()-D,timestamp:Date.now()}),!m.passed)throw new a$1({code:"OUTPUT_GUARDRAIL_FAILED",message:`Output guardrail "${u}" failed: ${m.reason}`,guardrailName:u,guardrailType:"output",userMessage:m.reason??"Output validation failed",agentName:e$1.name,input:r});m.transformed!==void 0&&(l$1.output=m.transformed);}let ae=false,h$1=0;if(t$2.batch(()=>{let n=f(t$2.facts),u=n.tokenUsage+l$1.totalTokens;if(g(t$2.facts,{...n,status:"completed",output:l$1.output,tokenUsage:u,turnCount:n.turnCount+l$1.messages.length,completedAt:Date.now()}),V&&be){h$1=u/V;let g=getBridgeFact(t$2.facts,"__budgetWarningFired");h$1>=te&&!g&&(setBridgeFact(t$2.facts,"__budgetWarningFired",true),ae=true);}}),ae)try{be({currentTokens:f(t$2.facts).tokenUsage,maxBudget:V,percentage:h$1});}catch(n){E&&console.debug("[Directive Orchestrator] onBudgetWarning threw:",n);}if(B&&l$1.messages.length>0)try{B.addMessages(l$1.messages);}catch(n){E&&console.debug("[Directive] Memory addMessages failed:",n);}if(q$1("onAgentComplete",{agentName:e$1.name,input:r,output:l$1.output,tokenUsage:l$1.totalTokens,durationMs:Date.now()-c$1,timestamp:Date.now()}),y){let n=typeof l$1.output=="string"?l$1.output:JSON.stringify(l$1.output);y.record({type:"agent_complete",timestamp:Date.now(),agentId:e$1.name,snapshotId:null,outputLength:n?.length??0,totalTokens:l$1.totalTokens,inputTokens:l$1.tokenUsage?.inputTokens??0,outputTokens:l$1.tokenUsage?.outputTokens??0,durationMs:Date.now()-c$1,modelId:e$1.model??void 0,output:n.slice(0,de)});}if(_&&_.length>0){let n={agentId:e$1.name,agentName:e$1.name,input:r,state:t$2.facts.$store.toObject(),breakpointType:"post_run"},u=await ne("post_run",n,i?.signal??a?.signal);if(u?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};u?.input&&(r=u.input);}return l$1}Se=Ee;let j$1=new Map,J=new Map;function at(e,r){return r?.aborted?Promise.reject(r.reason??new Error("Aborted while waiting for breakpoint")):new Promise((o,a)=>{let i=false,c=null,p=()=>{i||(i=true,c&&(clearTimeout(c),c=null),r&&r.removeEventListener("abort",v),$());},v=()=>{p(),a(r.reason??new Error(`Breakpoint wait for ${e} aborted`));};r&&r.addEventListener("abort",v,{once:true});let $=t$2.facts.$store.subscribe([g$1],()=>{if(i)return;let C=n(t$2.facts);if(C.resolved.includes(e)){p();let l=j$1.get(e)??null;j$1.delete(e),o(l);}else if(C.cancelled.includes(e)){p(),j$1.delete(e);let l=J.get(e);J.delete(e),a(new Error(l?`Breakpoint ${e} was cancelled: ${l}`:`Breakpoint ${e} was cancelled`));}}),A=et??3e5;c=setTimeout(()=>{i||(p(),j$1.delete(e),J.delete(e),a(new Error(`[Directive] Breakpoint timeout: ${e} not resolved within ${Math.round(A/1e3)}s`)));},A);})}async function ne(e,r,o$1){if(!_||_.length===0)return null;let a=u(_,e,r);if(!a)return null;let i=t$1(),c={id:i,type:e,agentId:r.agentId,input:r.input,label:a.label,requestedAt:Date.now()};t$2.batch(()=>{let v=n(t$2.facts);o(t$2.facts,{...v,pending:[...v.pending,c]});});try{Ze?.(c);}catch{}try{Te.onBreakpoint?.(c);}catch{}y&&y.record({type:"breakpoint_hit",timestamp:Date.now(),snapshotId:null,agentId:r.agentId,breakpointId:i,breakpointType:e,label:a.label});let p=await at(i,o$1);return y&&y.record({type:"breakpoint_resumed",timestamp:Date.now(),snapshotId:null,agentId:r.agentId,breakpointId:i,modified:!!p?.input,skipped:!!p?.skip}),p}function xe(e,r){return r?.aborted?Promise.reject(r.reason??new Error("Aborted while waiting for approval")):new Promise((o,a)=>{let i=false,c=null,p=()=>{i||(i=true,c&&(clearTimeout(c),c=null),r&&r.removeEventListener("abort",v),$());},v=()=>{p(),a(r.reason??new Error(`Approval wait for ${e} aborted`));};r&&r.addEventListener("abort",v,{once:true});let $=t$2.facts.$store.subscribe([d$1],()=>{if(i)return;let A=h(t$2.facts);if(A.approved.includes(e))p(),o();else {let C=A.rejected.find(l=>l.id===e);if(C){p();let l=C.reason?`Request ${e} rejected: ${C.reason}`:`Request ${e} rejected`;a(new Error(l));}}});c=setTimeout(()=>{if(i)return;p();let A=Math.round(ce/1e3);a(new Error(`[Directive] Approval timeout: Request ${e} not resolved within ${A}s.
|
|
10
|
+
Solutions:
|
|
11
|
+
1. Handle via onApprovalRequest callback and call orchestrator.approve()/reject()
|
|
12
|
+
2. Set autoApproveToolCalls: true to auto-approve
|
|
13
|
+
3. Increase approvalTimeoutMs (current: ${ce}ms)
|
|
14
|
+
See: https://directive.run/docs/ai/running-agents`));},ce);})}function Ie(){return {...p(t$2.facts)}}return {system:t$2,get facts(){return Ie()},get totalTokens(){return f(t$2.facts).tokenUsage},get timeline(){return y},async run(e,r,o){return Ee(e,r,Ie(),void 0,o)},runStream(e$1,r,o={}){let a=new AbortController,i=1e4,c$1=[],p=[],v=false,$=Date.now(),A=0,C=1e5,l$1="",U;o.signal&&(U=()=>a.abort(),o.signal.addEventListener("abort",U,{once:true}));let ae=()=>{U&&o.signal&&o.signal.removeEventListener("abort",U);},h$1=d=>{if(v)return;let b=p.shift();b?b(d):(c$1.push(d),c$1.length>i&&c$1.shift());},n=()=>{v=true,ae();for(let d of p)d(null);p.length=0;},u=null,g$1=o.liveContext;if(g$1){if(E&&g$1.system===t$2){let H=["agent","conversation","approvalState"],s=g$1.keys.filter(k=>H.some(w=>k.startsWith(w)));s.length>0&&console.warn(`[Directive] liveContext watches bridge-state keys (${s.join(", ")}) on the orchestrator's own system. The orchestrator's own setAgentState / setConversation / approvalState writes will trigger interruptWhen, self-looping the run. Use a separate system for liveContext, or scope \`keys\` to user-fact namespaces.`);}let d=g$1.notifyOn??"interrupt-only",b=g$1.interruptWhen??(()=>true),O=new Set(g$1.keys),W=g$1.system.facts.$store;if(typeof W?.subscribe=="function"){let H=W.toObject?.()??{};u=W.subscribe(g$1.keys,()=>{if(v)return;let s=W.toObject?.()??{},k=[];for(let T of g$1.keys)s[T]!==H[T]&&k.push(T);if(H=s,k.length===0)return;let w=k.filter(T=>O.has(T));if(w.length===0)return;g$1.onContextUpdate?.(w),b(s,w)?(h$1({type:"interrupted",reason:"liveContext.interruptWhen",partialOutput:l$1,changedKeys:w}),a.abort()):d==="all-changes"&&h$1({type:"context_updated",changedKeys:w});});}}let D=()=>{u&&(u(),u=null);},m$1=(async()=>{h$1({type:"progress",phase:"starting",message:"Running input guardrails"});try{let d$1=r,b=(G.input??[]).map((s,k)=>c(s,k,"input"));for(let s of b){let{name:k}=s,w={agentName:e$1.name,input:d$1,facts:t$2.facts.$store.toObject()},f=await d(s,{input:d$1,agentName:e$1.name},w);if(!f.passed)throw h$1({type:"guardrail_triggered",guardrailName:k,reason:f.reason??"Input validation failed",partialOutput:l$1,stopped:!0}),new a$1({code:"INPUT_GUARDRAIL_FAILED",message:`Input guardrail "${k}" failed: ${f.reason}`,guardrailName:k,guardrailType:"input",userMessage:f.reason??"Input validation failed",agentName:e$1.name,input:d$1});f.transformed!==void 0&&(d$1=f.transformed);}h$1({type:"progress",phase:"generating",message:"Starting agent"}),t$2.batch(()=>{let s=f(t$2.facts);g(t$2.facts,{...s,status:"running",currentAgent:e$1.name,input:d$1,startedAt:Date.now()});});let O=await e(ee,e$1,d$1,{signal:a.signal,onMessage:s=>{let k$1=j(t$2.facts);if(k(t$2.facts,[...k$1,s]),h$1({type:"message",message:s}),s.role==="assistant"&&s.content){let w=Math.ceil(s.content.length/4);A+=w,l$1+=s.content,l$1.length>C&&(l$1=l$1.slice(-C)),h$1({type:"token",data:s.content,tokenCount:A});}},onToolCall:async s=>{h$1({type:"tool_start",tool:s.name,toolCallId:s.id,arguments:s.arguments});let k=(G.toolCall??[]).map((f,T)=>c(f,T,"toolCall"));for(let f of k){let{name:T}=f,oe={agentName:e$1.name,input:d$1,facts:t$2.facts.$store.toObject()},se=await d(f,{toolCall:s,agentName:e$1.name,input:d$1},oe);if(!se.passed)throw h$1({type:"guardrail_triggered",guardrailName:T,reason:se.reason??"Tool call blocked",partialOutput:l$1,stopped:!0}),new a$1({code:"TOOL_CALL_GUARDRAIL_FAILED",message:`Tool call guardrail "${T}" failed: ${se.reason}`,guardrailName:T,guardrailType:"toolCall",userMessage:se.reason??"Tool call blocked",data:{toolCall:s},agentName:e$1.name,input:d$1})}if(!ue){let f=`tool-${s.id}`;h$1({type:"approval_required",requestId:f,toolName:s.name});let T={id:f,type:"tool_call",agentName:e$1.name,description:`Tool call: ${s.name}`,data:s,requestedAt:Date.now()};t$2.batch(()=>{let oe=h(t$2.facts);i$1(t$2.facts,{...oe,pending:[...oe.pending,T]});}),ie?.(T),await xe(f,a.signal),h$1({type:"approval_resolved",requestId:f,approved:!0});}let w=l(t$2.facts);m(t$2.facts,[...w,s]),s.result&&h$1({type:"tool_end",tool:s.name,toolCallId:s.id,result:s.result});}},re);h$1({type:"progress",phase:"finishing",message:"Running output guardrails"});let W=(G.output??[]).map((s,k)=>c(s,k,"output"));for(let s of W){let{name:k}=s,w={agentName:e$1.name,input:d$1,facts:t$2.facts.$store.toObject()},f=await d(s,{output:O.output,agentName:e$1.name,input:d$1,messages:O.messages},w);if(!f.passed)throw h$1({type:"guardrail_triggered",guardrailName:k,reason:f.reason??"Output validation failed",partialOutput:typeof O.output=="string"?O.output:"",stopped:!0}),new a$1({code:"OUTPUT_GUARDRAIL_FAILED",message:`Output guardrail "${k}" failed: ${f.reason}`,guardrailName:k,guardrailType:"output",userMessage:f.reason??"Output validation failed",agentName:e$1.name,input:d$1});f.transformed!==void 0&&(O.output=f.transformed);}t$2.batch(()=>{let s=f(t$2.facts);g(t$2.facts,{...s,status:"completed",output:O.output,tokenUsage:s.tokenUsage+O.totalTokens,turnCount:s.turnCount+O.messages.length,completedAt:Date.now()});});let H=Date.now()-$;return h$1({type:"done",totalTokens:O.totalTokens,duration:H,droppedTokens:0}),n(),O}catch(d){throw h$1({type:"error",error:d instanceof Error?d:new Error(String(d))}),n(),d}})();m$1.catch(()=>{});let x={[Symbol.asyncIterator](){return {async next(){return c$1.length>0?{done:false,value:c$1.shift()}:v?{done:true,value:void 0}:new Promise(d=>{p.push(b=>{d(b===null?{done:true,value:void 0}:{done:false,value:b});});})}}}},M=false;return m$1.finally(()=>{M||D();}).catch(()=>{}),{stream:x,result:m$1,abort:()=>{a.abort(),D(),n();},interrupt:d=>{M=true,h$1({type:"interrupted",reason:d??"caller.interrupt",partialOutput:l$1,changedKeys:[]}),a.abort();}}},async waitForIdle(e){let r=()=>f(t$2.facts).status!=="running";if(r())return;let o=Date.now();for(;!r();){if(e!==void 0&&Date.now()-o>e)throw new Error("[Directive Orchestrator] waitForIdle timed out");await new Promise(a=>setTimeout(a,50));}},approve(e){t$2.batch(()=>{let r=h(t$2.facts);if(!r.pending.some(i=>i.id===e)){E&&console.debug(`[Directive] approve() ignored: no pending request "${e}"`);return}let o=200,a=[...r.approved,e];i$1(t$2.facts,{...r,pending:r.pending.filter(i=>i.id!==e),approved:a.length>o?a.slice(-o):a});});},reject(e,r){t$2.batch(()=>{let o=h(t$2.facts);if(!o.pending.some(p=>p.id===e)){E&&console.debug(`[Directive] reject() ignored: no pending request "${e}"`);return}r&&E&&console.debug(`[Directive] Request ${e} rejected: ${r}`);let a={id:e,reason:r,rejectedAt:Date.now()},i=200,c=[...o.rejected,a];i$1(t$2.facts,{...o,pending:o.pending.filter(p=>p.id!==e),rejected:c.length>i?c.slice(-i):c});});},pause(){let e=f(t$2.facts);g(t$2.facts,{...e,status:"paused"});},resume(){let e=f(t$2.facts);e.status==="paused"&&g(t$2.facts,{...e,status:e.currentAgent?"running":"idle"});},reset(){t$2.batch(()=>{g(t$2.facts,{status:"idle",currentAgent:null,input:null,output:null,error:null,tokenUsage:0,turnCount:0,startedAt:null,completedAt:null}),i$1(t$2.facts,{pending:[],approved:[],rejected:[]}),k(t$2.facts,[]),m(t$2.facts,[]),o(t$2.facts,{pending:[],resolved:[],cancelled:[]}),setBridgeFact(t$2.facts,"__budgetWarningFired",false);}),j$1.clear(),J.clear();},async checkpoint(e){if(f(t$2.facts).status==="running")throw new Error("[Directive] Cannot checkpoint while agent is running");if(!t$2.history?.export)throw new Error("[Directive] Checkpointing requires history. Set `debug: true` in orchestrator options.");let o={version:1,id:w(),createdAt:new Date().toISOString(),label:e?.label,systemExport:t$2.history.export(),timelineExport:y?.export()??null,localState:{type:"single"},memoryExport:B?B.export?.()??null:null,orchestratorType:"single"};return Re&&await Re.save(o),o},restore(e,r){if(!x(e))throw new Error("[Directive] Invalid checkpoint data");if(e.orchestratorType!=="single")throw new Error("[Directive] Cannot restore multi-agent checkpoint in single-agent orchestrator");if(!t$2.history?.import)throw new Error("[Directive] Restoring a checkpoint requires history. Set `debug: true` in orchestrator options.");t$2.history.import(e.systemExport),r?.restoreTimeline!==false&&e.timelineExport&&y&&y.import(e.timelineExport),e.memoryExport!==null&&B&&B.import&&B.import(e.memoryExport);},resumeBreakpoint(e,r){r&&j$1.set(e,r),t$2.batch(()=>{let o$1=n(t$2.facts),a=[...o$1.resolved,e];o(t$2.facts,{...o$1,pending:o$1.pending.filter(i=>i.id!==e),resolved:a.length>s?a.slice(-s):a});});},cancelBreakpoint(e,r){r&&J.set(e,r),t$2.batch(()=>{let o$1=n(t$2.facts),a=[...o$1.cancelled,e];o(t$2.facts,{...o$1,pending:o$1.pending.filter(i=>i.id!==e),cancelled:a.length>s?a.slice(-s):a});});},getPendingBreakpoints(){return [...n(t$2.facts).pending]},destroy(){t$2.destroy();}}}
|
|
15
|
+
export{Rt as a};//# sourceMappingURL=chunk-D72LIBH2.js.map
|
|
16
|
+
//# sourceMappingURL=chunk-D72LIBH2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent-orchestrator.ts"],"names":["MAX_CONVERSATION_MESSAGES","MAX_TOOL_CALLS","createAgentOrchestrator","options","runner","factsSchema","init","constraints","resolvers","guardrails","onApprovalRequest","autoApproveToolCalls","maxTokenBudget","budgetWarningThreshold","onBudgetWarning","plugins","rawDebug","approvalTimeoutMs","agentRetry","hooks","memory","circuitBreaker","selfHealing","outputSchema","maxSchemaRetries","checkpointStore","breakpoints","onBreakpoint","breakpointTimeoutMs","debug","MAX_VERBOSE_LENGTH","fireHook","name","event","hookError","RESERVED_ORCHESTRATOR_KEYS","key","combinedSchema","orchestratorBridgeSchema","t","runAgentWithGuardrailsFn","system","directiveConstraints","convertOrchestratorConstraints","facts","getAgentState","directiveResolvers","convertOrchestratorResolvers","agent","input","currentFacts","opts","requirementGuard","_req","context","currentAgent","setAgentState","timeline","createDebugTimeline","snapshotId","callbackPlugin","createCallbackPlugin","orchestratorModule","createModule","setApprovalState","setConversation","setToolCalls","setBreakpointState","setBridgeFact","state","getOrchestratorState","combinedFacts","allPlugins","createDebugTimelinePlugin","createSystem","runAgentWithGuardrails","_currentFacts","callOptions","runAgentWithGuardrailsInner","error","fallbackRunner","rerouteEvent","startTime","contextMessages","contextStr","m","metaStr","formatSystemMeta","bpContext","mods","handleBreakpoint","effectiveInputGuardrails","effectiveOutputGuardrails","inputGuardrailsList","g","i","normalizeGuardrail","guardrail","guardStartTime","result","executeGuardrailWithRetry","GuardrailError","effectiveSchema","effectiveRunner","withStructuredOutput","executeAgentWithRetry","message","updated","getConversation","toolCall","toolCallGuardrails","guardResult","approvalId","approvalRequest","currentApproval","getApprovalState","waitForApproval","updatedToolCalls","getToolCalls","attempt","delayMs","outputGuardrailsList","shouldFireBudgetWarning","budgetPercentage","newTokenUsage","warningFired","getBridgeFact","callbackError","memoryError","outputStr","breakpointModifications","breakpointCancelReasons","waitForBreakpointResolution","bpId","signal","resolve","reject","settled","timeoutId","cleanupAll","onAbort","unsubscribe","BREAKPOINT_KEY","bpState","getBreakpointState","cancelReason","bpTimeout","type","match","matchBreakpoint","createBreakpointId","request","requestId","APPROVAL_KEY","approval","rejectedRequest","r","errorMsg","timeoutSeconds","getCombinedFacts","abortController","MAX_STREAM_BUFFER","chunks","waiters","closed","tokenCount","MAX_ACCUMULATED_OUTPUT","accumulatedOutput","abortHandler","cleanup","pushChunk","chunk","waiter","closeStream","liveContextUnsub","liveCfg","bridgeKeys","overlap","bk","notifyOn","interruptWhen","watched","store","lastSnapshot","current","changed","k","watchedChanged","tearDownLiveContext","resultPromise","processedInput","inputGuardrails","currentConversation","newTokens","currentToolCalls","outputGuardrails","duration","stream","interruptInitiated","reason","timeoutMs","isIdle","start","MAX_APPROVAL_HISTORY","approved","MAX_REJECTION_HISTORY","rejected","cpOptions","cp","createCheckpointId","restoreOpts","validateCheckpoint","id","modifications","resolved","MAX_BREAKPOINT_HISTORY","cancelled"],"mappings":"maA4GA,IAAMA,EAAAA,CAA4B,GAAA,CAE5BC,EAAAA,CAAiB,GAAA,CAyZhB,SAASC,EAAAA,CAEdC,EAAAA,CAAuD,CACvD,GAAM,CACJ,MAAA,CAAAC,EAAAA,CACA,WAAA,CAAAC,EAAAA,CAAc,EAAC,CACf,IAAA,CAAAC,EAAAA,CACA,WAAA,CAAAC,EAAAA,CAAc,EAAC,CACf,SAAA,CAAAC,EAAAA,CAAY,EAAC,CACb,WAAAC,CAAAA,CAAa,EAAC,CACd,iBAAA,CAAAC,EAAAA,CACA,oBAAA,CAAAC,EAAAA,CAAuB,IAAA,CACvB,eAAAC,CAAAA,CACA,sBAAA,CAAAC,EAAAA,CAAyB,EAAA,CACzB,eAAA,CAAAC,EAAAA,CACA,OAAA,CAAAC,EAAAA,CAAU,EAAC,CACX,KAAA,CAAOC,EAAAA,CAAW,KAAA,CAClB,iBAAA,CAAAC,EAAAA,CAAoB,GAAA,CACpB,UAAA,CAAAC,EAAAA,CACA,KAAA,CAAAC,EAAAA,CAAQ,EAAC,CACT,MAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,GACA,WAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,EAAAA,CACA,gBAAA,CAAAC,EAAAA,CACA,eAAA,CAAAC,EAAAA,CACA,YAAAC,CAAAA,CACA,YAAA,CAAAC,EAAAA,CACA,mBAAA,CAAAC,EACF,CAAA,CAAIzB,EAAAA,CAGE0B,CAAAA,CAAQ,OAAOb,EAAAA,EAAa,QAAA,CAAW,IAAA,CAAO,CAAC,CAACA,EAAAA,CAChDc,EAAAA,CAAqB,GAAA,CAW3B,GARID,CAAAA,EAASP,CAAAA,EAAe,CAACD,EAAAA,EAC3B,OAAA,CAAQ,IAAA,CACN,iJAEF,EAIER,EAAAA,CAAyB,CAAA,EAAKA,EAAAA,CAAyB,CAAA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AAAA,CAAO,KAAA,CAAM,IAAM,CACjB,IAAMsG,GAAAA,CAAUC,CAAAA,CAAmBvG,GAAAA,CAAO,KAAK,EACzC+K,CAAAA,CAAY,CAAC,GAAGzE,GAAAA,CAAQ,SAAA,CAAWqE,CAAE,EAC3CjJ,CAAAA,CAAmB1B,GAAAA,CAAO,KAAA,CAAO,CAC/B,GAAGsG,GAAAA,CACH,QAASA,GAAAA,CAAQ,OAAA,CAAQ,MAAA,CAAQa,CAAAA,EAAMA,CAAAA,CAAE,EAAA,GAAOwD,CAAE,CAAA,CAClD,SAAA,CACEI,CAAAA,CAAU,MAAA,CAASD,CAAAA,CACfC,CAAAA,CAAU,KAAA,CAAM,CAACD,CAAsB,CAAA,CACvCC,CACR,CAAC,EACH,CAAC,EACH,CAAA,CAEA,qBAAA,EAA6C,CAG3C,OAAO,CAAC,GAFQxE,EAAmBvG,GAAAA,CAAO,KAAK,CAAA,CAE5B,OAAO,CAC5B,CAAA,CAEA,OAAA,EAAgB,CACdA,GAAAA,CAAO,OAAA,GACT,CACF,CAGF","file":"chunk-D72LIBH2.js","sourcesContent":["/**\n * Agent Orchestrator — constraint-driven agent execution with guardrails.\n *\n * Single-agent orchestrator backed by a Directive System with reactive state,\n * constraints, guardrails, streaming, approval workflow, and lifecycle hooks.\n */\n\nimport type {\n ModuleSchema,\n Plugin,\n Requirement,\n SingleModuleSystem,\n System,\n} from \"@directive-run/core\";\nimport { createModule, t } from \"@directive-run/core\";\nimport { createSystem } from \"@directive-run/core\";\nimport {\n createCallbackPlugin,\n getBridgeFact,\n requirementGuard,\n setBridgeFact,\n} from \"@directive-run/core/adapter-utils\";\nimport type { CircuitBreaker } from \"@directive-run/core/plugins\";\nimport type { AgentMemory } from \"./memory.js\";\nimport { formatSystemMeta } from \"./meta-context.js\";\nimport type { StreamChunk as StreamChunkBase } from \"./streaming.js\";\n\nimport type {\n AgentLike,\n AgentRetryConfig,\n AgentRunner,\n ApprovalRequest,\n GuardrailFn,\n GuardrailsConfig,\n InputGuardrailData,\n NamedGuardrail,\n OrchestratorConstraint,\n OrchestratorLifecycleHooks,\n OrchestratorResolver,\n OrchestratorState,\n OutputGuardrailData,\n RejectedRequest,\n RerouteEvent,\n RunOptions,\n RunResult,\n SelfHealingConfig,\n} from \"./types.js\";\n\nimport {\n APPROVAL_KEY,\n BREAKPOINT_KEY,\n GuardrailError,\n orchestratorBridgeSchema,\n} from \"./types.js\";\n\nimport {\n type DebugTimeline,\n createDebugTimeline,\n createDebugTimelinePlugin,\n} from \"./debug-timeline.js\";\n\nimport {\n executeAgentWithRetry,\n executeGuardrailWithRetry,\n normalizeGuardrail,\n} from \"./guardrail-utils.js\";\n\nimport {\n convertOrchestratorConstraints,\n convertOrchestratorResolvers,\n getAgentState,\n getApprovalState,\n getBreakpointState,\n getConversation,\n getOrchestratorState,\n getToolCalls,\n setAgentState,\n setApprovalState,\n setBreakpointState,\n setConversation,\n setToolCalls,\n} from \"./orchestrator-bridge.js\";\n\nimport type {\n BreakpointConfig,\n BreakpointContext,\n BreakpointModifications,\n BreakpointRequest,\n} from \"./breakpoints.js\";\nimport {\n MAX_BREAKPOINT_HISTORY,\n createBreakpointId,\n matchBreakpoint,\n} from \"./breakpoints.js\";\nimport {\n type Checkpoint,\n type CheckpointStore,\n createCheckpointId,\n validateCheckpoint,\n} from \"./checkpoint.js\";\nimport {\n type SafeParseable,\n withStructuredOutput,\n} from \"./structured-output.js\";\n\n// Bridge accessors and constraint/resolver converters imported from orchestrator-bridge.ts\n\n/** Maximum conversation messages retained (FIFO eviction) */\nconst MAX_CONVERSATION_MESSAGES = 500;\n/** Maximum tool calls retained (FIFO eviction) */\nconst MAX_TOOL_CALLS = 200;\n\n/** Built-in pause requirement type */\ninterface PauseBudgetExceededReq extends Requirement {\n type: \"__PAUSE_BUDGET_EXCEEDED\";\n}\n\n// ============================================================================\n// Exported Types\n// ============================================================================\n\n/** Orchestrator options */\nexport interface OrchestratorOptions<F extends Record<string, unknown>> {\n /** Function to run an agent */\n runner: AgentRunner;\n /**\n * Schema for custom facts tracked in the orchestrator's Directive System.\n * @example\n * ```typescript\n * import { t } from '@directive-run/core';\n * const orchestrator = createOrchestrator({\n * factsSchema: { confidence: t.number(), category: t.string() },\n * // ...\n * });\n * ```\n */\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 /** Fires when token usage reaches this percentage of maxTokenBudget (0-1). @default 0.8 */\n budgetWarningThreshold?: number;\n /** Callback when budget warning threshold is reached */\n onBudgetWarning?: (event: {\n currentTokens: number;\n maxBudget: number;\n percentage: number;\n }) => void;\n /** Plugins */\n plugins?: Plugin[];\n /**\n * Enable debugging — `true` for default debug, or config object for advanced options\n * @default false\n */\n debug?: boolean | import(\"./types.js\").OrchestratorDebugConfig;\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 /** Self-healing configuration for automatic fallback */\n selfHealing?: SelfHealingConfig;\n /**\n * Default schema for structured output. When set, agent output is parsed and\n * validated against this schema with automatic retry on failure.\n * Any Zod-compatible schema (anything with `safeParse`) works.\n */\n outputSchema?: SafeParseable<unknown>;\n /**\n * Max retries for structured output parsing.\n * @default 2\n */\n maxSchemaRetries?: number;\n /** Optional checkpoint store for save/restore workflow state. */\n checkpointStore?: CheckpointStore;\n /**\n * Breakpoint configurations for human-in-the-loop pause points.\n * Zero overhead when empty — guard checks at each insertion point.\n */\n breakpoints?: BreakpointConfig[];\n /** Callback fired when a breakpoint is hit and waiting for resolution. */\n onBreakpoint?: (request: BreakpointRequest) => void;\n /**\n * Timeout for breakpoint resolution in milliseconds.\n * @default 300000 (5 minutes)\n */\n breakpointTimeoutMs?: number;\n /**\n * Include system meta in agent instructions for structured LLM reasoning.\n * When true, constraint labels, resolver descriptions, fact annotations,\n * and module metadata are injected into the agent's system prompt.\n * @default false\n */\n metaContext?: boolean;\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 * RFC 0005: cancel the in-flight generation but keep the\n * `liveContext` subscription attached. Distinct from `abort()`:\n * `abort` tears the AsyncIterable down AND detaches liveContext;\n * `interrupt` cancels the LLM run but leaves the orchestrator's\n * fact subscriptions alive so the next caller-driven prompt\n * continues against fresh facts. The optional `reason` lands on\n * the emitted `interrupted` chunk.\n */\n interrupt: (reason?: string) => 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 * RFC 0005: a `liveContext`-watched fact changed. Carries the keys\n * whose values changed in this batch so the consumer can decide\n * whether to re-render the system prompt mid-stream. Always emitted\n * when `notifyOn: \"all-changes\"`; emitted only for keys whose\n * change `interruptWhen` returned `true` for when `notifyOn:\n * \"interrupt-only\"` (the default).\n */\n | { type: \"context_updated\"; changedKeys: readonly string[] }\n /**\n * RFC 0005: `liveContext.interruptWhen` returned `true` for at\n * least one changed key. The orchestrator aborted the in-flight\n * LLM run and emits this chunk with the partial output captured\n * up to the abort point. In `mode: \"restart\"` the orchestrator\n * also re-invokes the runner with merged context after the chunk\n * fires; in `mode: \"inject-system-message\"` the consumer is\n * responsible for restarting via a fresh `runStream` call.\n */\n | {\n type: \"interrupted\";\n reason: string;\n partialOutput: string;\n changedKeys: readonly string[];\n };\n\n/**\n * RFC 0005: live-context options for `runStream`. Wires a Directive\n * system's fact subscriptions into the in-flight LLM run so the\n * agent's view of the world stays in sync with reality.\n *\n * @example Market dashboard agent reacting to price ticks\n * ```ts\n * const result = orchestrator.runStream(agent, \"Summarize current state\", {\n * liveContext: {\n * system: marketSystem,\n * keys: [\"lastPrice\"],\n * interruptWhen: (facts) => Math.abs(facts.lastPrice - facts.openPrice) > 5,\n * mode: \"inject-system-message\",\n * },\n * });\n * ```\n */\nexport interface LiveContextOptions<\n F extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** The Directive system whose facts feed the agent. */\n // biome-ignore lint/suspicious/noExplicitAny: System type varies per consumer\n system: System<any>;\n /**\n * Fact keys to watch. The orchestrator subscribes to fact-change\n * notifications keyed on these names. Other facts change without\n * notifying the agent — keep this list tight to bound work.\n */\n keys: readonly (keyof F & string)[];\n /**\n * Predicate run on every batch of fact changes that touches a\n * watched key. Return `true` to interrupt the in-flight LLM run.\n * Receives the FULL fact snapshot + the array of changed keys so\n * the predicate can look at correlations (price + volume, headSha +\n * prState, etc.). Optional — defaults to `() => true` (interrupt\n * on every watched-key change).\n */\n interruptWhen?: (facts: F, changedKeys: readonly string[]) => boolean;\n /**\n * What to do when `interruptWhen` returns true. Today's landing\n * supports a single mode (`\"inject-system-message\"`): the LLM run\n * aborts and an `interrupted` chunk lands on the stream; the\n * consumer is responsible for restarting via a fresh `runStream`\n * call against the still-live liveContext subscription (use\n * `result.interrupt(reason?)` from outside or the automatic\n * `liveContext.interruptWhen` flow from inside).\n *\n * RFC 0005 reserves `\"restart\"` for a follow-up minor that\n * implements automatic re-invocation with merged context. Today\n * `\"restart\"` is accepted by the type for forward-compat but\n * behaves identically to `\"inject-system-message\"`.\n */\n mode?: \"inject-system-message\" | \"restart\";\n /**\n * `\"all-changes\"` emits `context_updated` for every watched-key\n * batch (so the consumer can render a sidebar of fact deltas).\n * `\"interrupt-only\"` (default) emits only for changes that hit\n * `interruptWhen === true`. Choose the noisier variant when\n * you want a live view; choose the default when you only care\n * about the interruption moments.\n */\n notifyOn?: \"all-changes\" | \"interrupt-only\";\n /**\n * Optional hook fired on every watched-key change AFTER the\n * `interruptWhen` predicate runs but BEFORE the chunk emits.\n * Useful for logging / instrumentation that should fire regardless\n * of `notifyOn`.\n */\n onContextUpdate?: (changedKeys: readonly string[]) => void;\n}\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<\n GuardrailFn<OutputGuardrailData> | NamedGuardrail<OutputGuardrailData>\n >;\n /** Override input guardrails for this call only. Set to [] to skip. */\n inputGuardrails?: Array<\n GuardrailFn<InputGuardrailData> | NamedGuardrail<InputGuardrailData>\n >;\n /** Signal for abort */\n signal?: AbortSignal;\n /** Override structured output schema for this call. Set to `null` to opt out. */\n outputSchema?: SafeParseable<unknown> | null;\n /** Override max schema retries for this call. */\n maxSchemaRetries?: number;\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>(\n agent: AgentLike,\n input: string,\n options?: RunCallOptions,\n ): 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>(\n agent: AgentLike,\n input: string,\n options?: {\n signal?: AbortSignal;\n /**\n * RFC 0005: bind the in-flight LLM run to a Directive system's\n * facts. When a watched fact changes, the orchestrator emits a\n * `context_updated` chunk; when `interruptWhen` returns `true`,\n * the LLM run is aborted and an `interrupted` chunk lands on\n * the stream. The companion `createFactPIIGuardrail` plugin\n * MUST be wired on the same system when watched facts may\n * carry PII — `liveContext` expands the source → fact → prompt\n * bypass surface into mid-stream context updates.\n */\n liveContext?: LiveContextOptions<F & OrchestratorState>;\n },\n ): 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 /** Total tokens consumed across all agent runs */\n readonly totalTokens: number;\n /** Debug timeline (null when debug is false) */\n readonly timeline: DebugTimeline | null;\n /** Wait until agent is idle. Resolves immediately if already idle. */\n waitForIdle(timeoutMs?: number): Promise<void>;\n /** Create a checkpoint of the current orchestrator state. Only valid when agent is not running. */\n checkpoint(options?: { label?: string }): Promise<Checkpoint>;\n /** Restore orchestrator state from a checkpoint. */\n restore(\n checkpoint: Checkpoint,\n options?: { restoreTimeline?: boolean },\n ): void;\n /** Resume a pending breakpoint, optionally with input modifications. */\n resumeBreakpoint(id: string, modifications?: BreakpointModifications): void;\n /** Cancel a pending breakpoint with optional reason. */\n cancelBreakpoint(id: string, reason?: string): void;\n /** Get all currently pending breakpoint requests. */\n getPendingBreakpoints(): BreakpointRequest[];\n /** Destroy the orchestrator, releasing all resources. */\n destroy(): void;\n}\n\n// ============================================================================\n// Main Factory\n// ============================================================================\n\n/**\n * Create a constraint-driven agent orchestrator backed by a Directive System.\n *\n * Wraps a single agent runner with reactive state, guardrails, streaming,\n * approval workflows, breakpoints, structured output, and lifecycle hooks.\n * Constraints and resolvers let you declaratively control agent behavior\n * based on runtime facts.\n *\n * @param options - Orchestrator configuration including runner, guardrails, constraints, and plugins.\n * @returns An {@link AgentOrchestrator} instance with `run`, `runStream`, `approve`/`reject`, and checkpoint APIs.\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)).detected;\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 If autoApproveToolCalls is false but no onApprovalRequest callback is provided\n * @public\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 budgetWarningThreshold = 0.8,\n onBudgetWarning,\n plugins = [],\n debug: rawDebug = false,\n approvalTimeoutMs = 300000,\n agentRetry,\n hooks = {},\n memory,\n circuitBreaker,\n selfHealing,\n outputSchema,\n maxSchemaRetries,\n checkpointStore,\n breakpoints,\n onBreakpoint,\n breakpointTimeoutMs,\n } = options;\n\n // Normalize debug config\n const debug = typeof rawDebug === \"object\" ? true : !!rawDebug;\n const MAX_VERBOSE_LENGTH = 5000;\n\n // Warn if selfHealing is configured without circuitBreaker (selfHealing only triggers in CB error path)\n if (debug && selfHealing && !circuitBreaker) {\n console.warn(\n \"[Directive] selfHealing config has no effect without a circuitBreaker — \" +\n \"fallback behavior requires the circuit breaker to detect failures.\",\n );\n }\n\n // Validate budget warning threshold\n if (budgetWarningThreshold < 0 || budgetWarningThreshold > 1) {\n throw new Error(\n `[Directive Orchestrator] budgetWarningThreshold must be between 0 and 1, got ${budgetWarningThreshold}`,\n );\n }\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 /** Safe hook caller — user-provided hooks must never crash the orchestrator */\n function fireHook<K extends keyof OrchestratorLifecycleHooks>(\n name: K,\n event: Parameters<NonNullable<OrchestratorLifecycleHooks[K]>>[0],\n ): void {\n try {\n (hooks[name] as ((e: typeof event) => void) | undefined)?.(event);\n } catch (hookError) {\n if (debug) {\n console.debug(`[Directive] hooks.${name} threw:`, hookError);\n }\n }\n }\n\n // Dev-mode: validate that user-provided facts keys don't collide with bridge state keys\n const RESERVED_ORCHESTRATOR_KEYS = [\n \"agent\",\n \"approval\",\n \"conversation\",\n \"toolCalls\",\n ];\n for (const key of Object.keys(factsSchema)) {\n if (RESERVED_ORCHESTRATOR_KEYS.includes(key)) {\n throw new Error(\n `[Directive] Facts schema key \"${key}\" conflicts with orchestrator state. Reserved keys: ${RESERVED_ORCHESTRATOR_KEYS.join(\", \")}. Rename your fact to avoid the collision.`,\n );\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 __budgetWarningFired: t.boolean(),\n },\n derivations: {},\n events: {},\n requirements: {},\n } satisfies ModuleSchema;\n\n // Forward declaration for runAgentWithGuardrails (used in resolver converter)\n // biome-ignore lint/style/useConst: forward declaration, assigned later\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/style/useConst: forward declaration, assigned later\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) =>\n runAgentWithGuardrailsFn(agent, input, currentFacts, opts),\n () => system.facts,\n );\n\n // Add built-in pause resolver\n directiveResolvers.__pause = {\n requirement: requirementGuard<PauseBudgetExceededReq>(\n \"__PAUSE_BUDGET_EXCEEDED\",\n ),\n // biome-ignore lint/suspicious/noExplicitAny: Context type varies\n resolve: async (_req: Requirement, context: any) => {\n const currentAgent = getAgentState(context.facts);\n setAgentState(context.facts, {\n ...currentAgent,\n status: \"paused\",\n });\n },\n };\n\n // ---- Debug Timeline setup ----\n let timeline: DebugTimeline | null = null;\n if (debug) {\n timeline = createDebugTimeline({\n getSnapshotId: () => {\n try {\n return (system as any).history?.currentIndex ?? null;\n } catch {\n return null;\n }\n },\n goToSnapshot: (snapshotId: number) => {\n try {\n (system as any).history?.goTo?.(snapshotId);\n } catch {\n // System may not support goTo\n }\n },\n });\n }\n\n // Create callback plugin for onApprovalRequest\n const callbackPlugin = createCallbackPlugin(\n \"directive-ai-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(\"directive-ai-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 setBreakpointState(facts, { pending: [], resolved: [], cancelled: [] });\n setBridgeFact(facts, \"__budgetWarningFired\", false);\n if (init) {\n const state = getOrchestratorState(facts);\n const combinedFacts = { ...facts, ...state } as unknown as F &\n OrchestratorState;\n init(combinedFacts);\n }\n },\n constraints: directiveConstraints,\n resolvers: directiveResolvers as any,\n });\n\n // Build plugins array with optional timeline plugin\n const allPlugins = [...plugins, callbackPlugin];\n if (debug && timeline) {\n allPlugins.push(\n createDebugTimelinePlugin(timeline, () => {\n try {\n return (system as any).history?.currentIndex ?? null;\n } catch {\n return null;\n }\n }),\n );\n }\n\n // Create system\n system = createSystem({\n module: orchestratorModule,\n plugins: allPlugins,\n history: debug ? 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 try {\n return await circuitBreaker.execute(() =>\n runAgentWithGuardrailsInner<T>(\n agent,\n input,\n _currentFacts,\n opts,\n callOptions,\n ),\n );\n } catch (error) {\n // Self-healing fallback\n if (selfHealing) {\n // Try fallback runners in order\n if (selfHealing.fallbackRunners) {\n for (const fallbackRunner of selfHealing.fallbackRunners) {\n try {\n const rerouteEvent: RerouteEvent = {\n originalAgent: agent.name,\n reroutedTo: \"fallback-runner\",\n reason:\n error instanceof Error ? error.message : String(error),\n timestamp: Date.now(),\n };\n try {\n selfHealing.onReroute?.(rerouteEvent);\n } catch {\n /* non-fatal */\n }\n if (timeline) {\n timeline.record({\n type: \"reroute\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n from: agent.name,\n to: \"fallback-runner\",\n reason:\n error instanceof Error ? error.message : String(error),\n });\n }\n\n return await fallbackRunner<T>(agent, input, opts);\n } catch {\n // Try next fallback\n }\n }\n }\n\n // Try fallback agent\n if (selfHealing.fallbackAgent) {\n try {\n const rerouteEvent: RerouteEvent = {\n originalAgent: agent.name,\n reroutedTo: selfHealing.fallbackAgent.name,\n reason: error instanceof Error ? error.message : String(error),\n timestamp: Date.now(),\n };\n try {\n selfHealing.onReroute?.(rerouteEvent);\n } catch {\n /* non-fatal */\n }\n if (timeline) {\n timeline.record({\n type: \"reroute\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n from: agent.name,\n to: selfHealing.fallbackAgent.name,\n reason:\n error instanceof Error ? error.message : String(error),\n });\n }\n\n return await runner<T>(selfHealing.fallbackAgent, input, opts);\n } catch {\n // Fallback agent also failed\n }\n }\n\n // Apply degradation policy\n if (\n selfHealing.degradation === \"fallback-response\" &&\n selfHealing.fallbackResponse !== undefined\n ) {\n return {\n output: selfHealing.fallbackResponse as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n }\n throw error;\n }\n }\n\n return runAgentWithGuardrailsInner<T>(\n agent,\n input,\n _currentFacts,\n opts,\n callOptions,\n );\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 // Inject system meta context if enabled\n if (options.metaContext) {\n const metaStr = formatSystemMeta(system.inspect());\n if (metaStr) {\n agent = {\n ...agent,\n instructions: `${agent.instructions ?? \"\"}\\n\\n${metaStr}`,\n };\n }\n }\n\n // Breakpoint: pre_input_guardrails\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_input_guardrails\",\n };\n const mods = await handleBreakpoint(\n \"pre_input_guardrails\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n // Resolve which guardrails to use: per-call override > orchestrator defaults\n const effectiveInputGuardrails =\n callOptions?.inputGuardrails !== undefined\n ? callOptions.inputGuardrails\n : (guardrails.input ?? []);\n const effectiveOutputGuardrails =\n callOptions?.outputGuardrails !== undefined\n ? callOptions.outputGuardrails\n : (guardrails.output ?? []);\n\n // Run input guardrails BEFORE agent_start so timeline shows correct order\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 fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\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 // Call onAgentStart hook (after guardrails pass)\n fireHook(\"onAgentStart\", {\n agentName: agent.name,\n input,\n timestamp: startTime,\n });\n\n if (timeline) {\n timeline.record({\n type: \"agent_start\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n inputLength: input.length,\n modelId: agent.model ?? undefined,\n ...(agent.instructions\n ? { instructions: agent.instructions.slice(0, MAX_VERBOSE_LENGTH) }\n : {}),\n input: input.slice(0, MAX_VERBOSE_LENGTH),\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 // Breakpoint: pre_agent_run\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_agent_run\",\n };\n const mods = await handleBreakpoint(\n \"pre_agent_run\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n // Structured output wrapping\n const effectiveSchema =\n callOptions?.outputSchema !== undefined\n ? callOptions.outputSchema\n : outputSchema;\n\n let effectiveRunner = runner;\n if (effectiveSchema) {\n effectiveRunner = withStructuredOutput(runner, {\n schema: effectiveSchema,\n maxRetries: callOptions?.maxSchemaRetries ?? maxSchemaRetries ?? 2,\n });\n }\n\n // Run the agent with retry support\n const result = await executeAgentWithRetry<T>(\n effectiveRunner,\n agent,\n input,\n {\n ...opts,\n signal: opts?.signal,\n onMessage: (message) => {\n const currentConversation = getConversation(system.facts);\n const updated = [...currentConversation, message];\n setConversation(\n system.facts,\n updated.length > MAX_CONVERSATION_MESSAGES\n ? updated.slice(-MAX_CONVERSATION_MESSAGES)\n : updated,\n );\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 fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\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 (pass signal so abort cancels the wait)\n await waitForApproval(\n approvalId,\n callOptions?.signal ?? opts?.signal,\n );\n }\n\n const currentToolCalls = getToolCalls(system.facts);\n const updatedToolCalls = [...currentToolCalls, toolCall];\n setToolCalls(\n system.facts,\n updatedToolCalls.length > MAX_TOOL_CALLS\n ? updatedToolCalls.slice(-MAX_TOOL_CALLS)\n : updatedToolCalls,\n );\n opts?.onToolCall?.(toolCall);\n },\n },\n agentRetry\n ? {\n ...agentRetry,\n onRetry: (attempt, error, delayMs) => {\n agentRetry.onRetry?.(attempt, error, delayMs);\n fireHook(\"onAgentRetry\", {\n agentName: agent.name,\n input,\n attempt,\n error,\n delayMs,\n timestamp: Date.now(),\n });\n },\n }\n : undefined,\n );\n\n // Breakpoint: pre_output_guardrails\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_output_guardrails\",\n };\n const mods = await handleBreakpoint(\n \"pre_output_guardrails\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\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 fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\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 let shouldFireBudgetWarning = false;\n let budgetPercentage = 0;\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n const newTokenUsage = currentAgent.tokenUsage + result.totalTokens;\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"completed\",\n output: result.output,\n tokenUsage: newTokenUsage,\n turnCount: currentAgent.turnCount + result.messages.length,\n completedAt: Date.now(),\n });\n\n // Check budget warning threshold\n if (maxTokenBudget && onBudgetWarning) {\n budgetPercentage = newTokenUsage / maxTokenBudget;\n const warningFired = getBridgeFact<boolean>(\n system.facts,\n \"__budgetWarningFired\",\n );\n if (budgetPercentage >= budgetWarningThreshold && !warningFired) {\n setBridgeFact(system.facts, \"__budgetWarningFired\", true);\n shouldFireBudgetWarning = true;\n }\n }\n });\n\n // Fire budget warning callback outside of batch (callbacks shouldn't run inside batch)\n if (shouldFireBudgetWarning) {\n try {\n onBudgetWarning!({\n currentTokens: getAgentState(system.facts).tokenUsage,\n maxBudget: maxTokenBudget!,\n percentage: budgetPercentage,\n });\n } catch (callbackError) {\n if (debug) {\n console.debug(\n \"[Directive Orchestrator] onBudgetWarning threw:\",\n callbackError,\n );\n }\n }\n }\n\n // Store messages in memory if configured (best-effort)\n if (memory && result.messages.length > 0) {\n try {\n memory.addMessages(result.messages);\n } catch (memoryError) {\n if (debug) {\n console.debug(\"[Directive] Memory addMessages failed:\", memoryError);\n }\n }\n }\n\n // Call onAgentComplete hook\n fireHook(\"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 if (timeline) {\n const outputStr =\n typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output);\n timeline.record({\n type: \"agent_complete\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n outputLength: outputStr?.length ?? 0,\n totalTokens: result.totalTokens,\n inputTokens: result.tokenUsage?.inputTokens ?? 0,\n outputTokens: result.tokenUsage?.outputTokens ?? 0,\n durationMs: Date.now() - startTime,\n modelId: agent.model ?? undefined,\n output: outputStr.slice(0, MAX_VERBOSE_LENGTH),\n });\n }\n\n // Breakpoint: post_run\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"post_run\",\n };\n const mods = await handleBreakpoint(\n \"post_run\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n return result;\n }\n\n // Assign the function to the forward-declared variable\n runAgentWithGuardrailsFn = runAgentWithGuardrails;\n\n // ---- Breakpoint infrastructure ----\n const breakpointModifications = new Map<string, BreakpointModifications>();\n const breakpointCancelReasons = new Map<string, string>();\n\n function waitForBreakpointResolution(\n bpId: string,\n signal?: AbortSignal,\n ): Promise<BreakpointModifications | null> {\n if (signal?.aborted) {\n return Promise.reject(\n signal.reason ?? new Error(\"Aborted while waiting for breakpoint\"),\n );\n }\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanupAll = () => {\n if (settled) {\n return;\n }\n\n settled = true;\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n unsubscribe();\n };\n\n const onAbort = () => {\n cleanupAll();\n reject(\n signal!.reason ?? new Error(`Breakpoint wait for ${bpId} aborted`),\n );\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const unsubscribe = system.facts.$store.subscribe(\n [BREAKPOINT_KEY],\n () => {\n if (settled) {\n return;\n }\n\n const bpState = getBreakpointState(system.facts);\n if (bpState.resolved.includes(bpId)) {\n cleanupAll();\n const mods = breakpointModifications.get(bpId) ?? null;\n breakpointModifications.delete(bpId);\n resolve(mods);\n } else if (bpState.cancelled.includes(bpId)) {\n cleanupAll();\n breakpointModifications.delete(bpId);\n const cancelReason = breakpointCancelReasons.get(bpId);\n breakpointCancelReasons.delete(bpId);\n reject(\n new Error(\n cancelReason\n ? `Breakpoint ${bpId} was cancelled: ${cancelReason}`\n : `Breakpoint ${bpId} was cancelled`,\n ),\n );\n }\n },\n );\n\n const bpTimeout = breakpointTimeoutMs ?? 300000;\n timeoutId = setTimeout(() => {\n if (settled) {\n return;\n }\n\n cleanupAll();\n breakpointModifications.delete(bpId);\n breakpointCancelReasons.delete(bpId);\n reject(\n new Error(\n `[Directive] Breakpoint timeout: ${bpId} not resolved within ${Math.round(bpTimeout / 1000)}s`,\n ),\n );\n }, bpTimeout);\n });\n }\n\n async function handleBreakpoint(\n type: string,\n context: BreakpointContext,\n signal?: AbortSignal,\n ): Promise<BreakpointModifications | null> {\n if (!breakpoints || breakpoints.length === 0) {\n return null;\n }\n\n const match = matchBreakpoint(\n breakpoints as BreakpointConfig<string>[],\n type,\n context,\n );\n if (!match) {\n return null;\n }\n\n const bpId = createBreakpointId();\n const request: BreakpointRequest = {\n id: bpId,\n type,\n agentId: context.agentId,\n input: context.input,\n label: match.label,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n setBreakpointState(system.facts, {\n ...bpState,\n pending: [...bpState.pending, request],\n });\n });\n\n try {\n onBreakpoint?.(request);\n } catch {\n /* non-fatal */\n }\n try {\n hooks.onBreakpoint?.(request);\n } catch {\n /* non-fatal */\n }\n\n if (timeline) {\n timeline.record({\n type: \"breakpoint_hit\",\n timestamp: Date.now(),\n snapshotId: null,\n agentId: context.agentId,\n breakpointId: bpId,\n breakpointType: type,\n label: match.label,\n });\n }\n\n const mods = await waitForBreakpointResolution(bpId, signal);\n\n if (timeline) {\n timeline.record({\n type: \"breakpoint_resumed\",\n timestamp: Date.now(),\n snapshotId: null,\n agentId: context.agentId,\n breakpointId: bpId,\n modified: !!mods?.input,\n skipped: !!mods?.skip,\n });\n }\n\n return mods;\n }\n\n // Wait for approval with configurable timeout and abort signal support\n function waitForApproval(\n requestId: string,\n signal?: AbortSignal,\n ): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(\n signal.reason ?? new Error(\"Aborted while waiting for approval\"),\n );\n }\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanupAll = () => {\n if (settled) {\n return;\n }\n\n settled = true;\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n unsubscribe();\n };\n\n const onAbort = () => {\n cleanupAll();\n reject(\n signal!.reason ?? new Error(`Approval wait for ${requestId} aborted`),\n );\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const unsubscribe = system.facts.$store.subscribe([APPROVAL_KEY], () => {\n if (settled) {\n return;\n }\n\n const approval = getApprovalState(system.facts);\n if (approval.approved.includes(requestId)) {\n cleanupAll();\n resolve();\n } else {\n const rejectedRequest = approval.rejected.find(\n (r) => r.id === requestId,\n );\n if (rejectedRequest) {\n cleanupAll();\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 if (settled) {\n return;\n }\n\n cleanupAll();\n const timeoutSeconds = Math.round(approvalTimeoutMs / 1000);\n reject(\n new Error(\n `[Directive] Approval timeout: Request ${requestId} not resolved within ${timeoutSeconds}s.\\nSolutions:\\n 1. Handle via onApprovalRequest callback and call orchestrator.approve()/reject()\\n 2. Set autoApproveToolCalls: true to auto-approve\\n 3. Increase approvalTimeoutMs (current: ${approvalTimeoutMs}ms)\\nSee: https://directive.run/docs/ai/running-agents`,\n ),\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\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 get totalTokens() {\n return getAgentState(system.facts).tokenUsage;\n },\n get timeline() {\n return timeline;\n },\n\n async run<T>(\n agent: AgentLike,\n input: string,\n options?: RunCallOptions,\n ): Promise<RunResult<T>> {\n return runAgentWithGuardrails<T>(\n agent,\n input,\n getCombinedFacts(),\n undefined,\n options,\n );\n },\n\n runStream<T>(\n agent: AgentLike,\n input: string,\n options: {\n signal?: AbortSignal;\n liveContext?: LiveContextOptions<F & OrchestratorState>;\n } = {},\n ): OrchestratorStreamResult<T> {\n const abortController = new AbortController();\n const MAX_STREAM_BUFFER = 10_000;\n const chunks: OrchestratorStreamChunk[] = [];\n const waiters: Array<(chunk: OrchestratorStreamChunk | null) => void> =\n [];\n let closed = false;\n const startTime = Date.now();\n let tokenCount = 0;\n const MAX_ACCUMULATED_OUTPUT = 100_000;\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, { once: true });\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 // FIFO eviction when buffer exceeds max\n if (chunks.length > MAX_STREAM_BUFFER) {\n chunks.shift();\n }\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 // RFC 0005: wire liveContext subscriptions BEFORE the resultPromise\n // IIFE constructs (which starts running synchronously). Even though\n // the IIFE's sync prefix today does no fact-mutating work before\n // its first await, hoisting the subscription removes any latent\n // race where a future IIFE prefix change could synchronously\n // mutate facts before subscribe wires up. The subscription\n // callback closes over `closed`, `pushChunk`, `accumulatedOutput`,\n // and `abortController` — all declared above and live by the\n // time a fact change can fire (which requires the IIFE to yield).\n //\n // RFC 0005 dev-mode guard: warn when liveContext.system === the\n // orchestrator's own system AND watched keys overlap bridge-state\n // keys. Without this, the orchestrator's own setAgentState calls\n // could trigger interruptWhen → abort, self-looping the run.\n let liveContextUnsub: (() => void) | null = null;\n const liveCfg = options.liveContext;\n if (liveCfg) {\n if (debug && (liveCfg.system as unknown) === (system as unknown)) {\n const bridgeKeys = [\"agent\", \"conversation\", \"approvalState\"];\n const overlap = liveCfg.keys.filter((k) =>\n bridgeKeys.some((bk) => k.startsWith(bk)),\n );\n if (overlap.length > 0) {\n console.warn(\n `[Directive] liveContext watches bridge-state keys (${overlap.join(\", \")}) on the orchestrator's own system. ` +\n \"The orchestrator's own setAgentState / setConversation / approvalState writes will trigger interruptWhen, \" +\n \"self-looping the run. Use a separate system for liveContext, or scope `keys` to user-fact namespaces.\",\n );\n }\n }\n const notifyOn = liveCfg.notifyOn ?? \"interrupt-only\";\n const interruptWhen = liveCfg.interruptWhen ?? (() => true);\n const watched = new Set(liveCfg.keys);\n // The system's facts $store exposes a key-scoped subscribe via\n // the same shape the breakpoint + approval waiters elsewhere\n // in this file use. We re-use that surface without touching\n // the bridge primitive itself.\n const store = (\n liveCfg.system as unknown as {\n facts: {\n $store: {\n subscribe?: (\n keys: readonly string[],\n listener: () => void,\n ) => () => void;\n toObject?: () => Record<string, unknown>;\n };\n };\n }\n ).facts.$store;\n if (typeof store?.subscribe === \"function\") {\n let lastSnapshot: Record<string, unknown> = store.toObject?.() ?? {};\n liveContextUnsub = store.subscribe(liveCfg.keys, () => {\n if (closed) return;\n const current = store.toObject?.() ?? {};\n const changed: string[] = [];\n for (const k of liveCfg.keys) {\n if (current[k] !== lastSnapshot[k]) changed.push(k);\n }\n lastSnapshot = current;\n if (changed.length === 0) return;\n const watchedChanged = changed.filter((k) => watched.has(k));\n if (watchedChanged.length === 0) return;\n liveCfg.onContextUpdate?.(watchedChanged);\n // biome-ignore lint/suspicious/noExplicitAny: facts type per consumer\n const shouldInterrupt = interruptWhen(\n current as any,\n watchedChanged,\n );\n if (shouldInterrupt) {\n pushChunk({\n type: \"interrupted\",\n reason: \"liveContext.interruptWhen\",\n partialOutput: accumulatedOutput,\n changedKeys: watchedChanged,\n });\n abortController.abort();\n } else if (notifyOn === \"all-changes\") {\n pushChunk({\n type: \"context_updated\",\n changedKeys: watchedChanged,\n });\n }\n });\n }\n }\n\n const tearDownLiveContext = (): void => {\n if (liveContextUnsub) {\n liveContextUnsub();\n liveContextUnsub = null;\n }\n };\n\n // Run the agent with streaming callbacks\n const resultPromise = (async (): Promise<RunResult<T>> => {\n pushChunk({\n type: \"progress\",\n phase: \"starting\",\n message: \"Running input guardrails\",\n });\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({\n type: \"progress\",\n phase: \"generating\",\n message: \"Starting agent\",\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: processedInput,\n startedAt: Date.now(),\n });\n });\n\n // Run agent with streaming callbacks and retry support\n const result = await executeAgentWithRetry<T>(\n runner,\n agent,\n processedInput,\n {\n signal: abortController.signal,\n onMessage: (message) => {\n const currentConversation = getConversation(system.facts);\n setConversation(system.facts, [\n ...currentConversation,\n message,\n ]);\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 if (accumulatedOutput.length > MAX_ACCUMULATED_OUTPUT) {\n accumulatedOutput = accumulatedOutput.slice(\n -MAX_ACCUMULATED_OUTPUT,\n );\n }\n pushChunk({\n type: \"token\",\n data: message.content,\n tokenCount,\n });\n }\n },\n onToolCall: async (toolCall) => {\n pushChunk({\n type: \"tool_start\",\n tool: toolCall.name,\n toolCallId: toolCall.id,\n arguments: toolCall.arguments,\n });\n\n // Run tool call guardrails with retry support\n const toolCallGuardrails = (guardrails.toolCall ?? []).map(\n (g, i) => 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({\n type: \"approval_required\",\n requestId: approvalId,\n toolName: toolCall.name,\n });\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, abortController.signal);\n pushChunk({\n type: \"approval_resolved\",\n requestId: approvalId,\n approved: true,\n });\n }\n\n const currentToolCalls = getToolCalls(system.facts);\n setToolCalls(system.facts, [...currentToolCalls, toolCall]);\n\n if (toolCall.result) {\n pushChunk({\n type: \"tool_end\",\n tool: toolCall.name,\n toolCallId: toolCall.id,\n result: toolCall.result,\n });\n }\n },\n },\n agentRetry,\n );\n\n // Run output guardrails\n pushChunk({\n type: \"progress\",\n phase: \"finishing\",\n message: \"Running output guardrails\",\n });\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:\n 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({\n type: \"done\",\n totalTokens: result.totalTokens,\n duration,\n droppedTokens: 0,\n });\n closeStream();\n\n return result;\n } catch (error) {\n pushChunk({\n type: \"error\",\n error: error instanceof Error ? error : new Error(String(error)),\n });\n closeStream();\n throw error;\n }\n })();\n\n // Prevent unhandled rejection if caller only consumes stream (not .result)\n resultPromise.catch(() => {});\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\n return new Promise<IteratorResult<OrchestratorStreamChunk>>(\n (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\n // Track whether the abort came from interrupt() — if so, the\n // resultPromise.finally MUST NOT tear down the liveContext\n // subscription. The whole differentiator of interrupt vs abort\n // is that interrupt cancels the LLM run but keeps the\n // subscription alive so the next caller-driven prompt continues\n // against fresh facts. Without this flag the abort triggers the\n // resultPromise's catch path → reject → finally → tearDown, and\n // the subscription dies anyway (R11 found this).\n let interruptInitiated = false;\n\n // .finally returns a new promise that re-rejects when resultPromise\n // rejects; swallow with .catch so a rejected resultPromise (e.g. a\n // guardrail block) doesn't surface as an unhandled rejection when\n // the caller only consumes the stream side of the contract.\n resultPromise\n .finally(() => {\n if (!interruptInitiated) {\n tearDownLiveContext();\n }\n })\n .catch(() => {});\n\n return {\n stream,\n result: resultPromise,\n abort: () => {\n abortController.abort();\n tearDownLiveContext();\n closeStream();\n },\n interrupt: (reason?: string) => {\n // RFC 0005: distinct from `abort()` — cancel the in-flight\n // LLM run but leave `liveContext` subscriptions alive so\n // the next caller-driven prompt continues against fresh\n // facts. The interrupted chunk lands with the reason if\n // provided.\n //\n // Set the interrupt flag BEFORE aborting so the\n // resultPromise.finally above sees it and skips\n // tearDownLiveContext. The caller is responsible for\n // either kicking off a new runStream (against the live\n // subscription) or calling abort() to fully tear down.\n interruptInitiated = true;\n pushChunk({\n type: \"interrupted\",\n reason: reason ?? \"caller.interrupt\",\n partialOutput: accumulatedOutput,\n changedKeys: [],\n });\n abortController.abort();\n },\n };\n },\n\n async waitForIdle(timeoutMs?: number): Promise<void> {\n const isIdle = () => getAgentState(system.facts).status !== \"running\";\n if (isIdle()) {\n return;\n }\n\n const start = Date.now();\n while (!isIdle()) {\n if (timeoutMs !== undefined && Date.now() - start > timeoutMs) {\n throw new Error(\"[Directive Orchestrator] waitForIdle timed out\");\n }\n await new Promise((r) => setTimeout(r, 50));\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)\n console.debug(\n `[Directive] approve() ignored: no pending request \"${requestId}\"`,\n );\n\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:\n approved.length > MAX_APPROVAL_HISTORY\n ? approved.slice(-MAX_APPROVAL_HISTORY)\n : 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)\n console.debug(\n `[Directive] reject() ignored: no pending request \"${requestId}\"`,\n );\n\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:\n rejected.length > MAX_REJECTION_HISTORY\n ? rejected.slice(-MAX_REJECTION_HISTORY)\n : 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 setBreakpointState(system.facts, {\n pending: [],\n resolved: [],\n cancelled: [],\n });\n setBridgeFact(system.facts, \"__budgetWarningFired\", false);\n });\n breakpointModifications.clear();\n breakpointCancelReasons.clear();\n },\n\n async checkpoint(cpOptions?: { label?: string }): Promise<Checkpoint> {\n const agentState = getAgentState(system.facts);\n if (agentState.status === \"running\") {\n throw new Error(\"[Directive] Cannot checkpoint while agent is running\");\n }\n if (!system.history?.export) {\n throw new Error(\n \"[Directive] Checkpointing requires history. Set `debug: true` in orchestrator options.\",\n );\n }\n\n const cp: Checkpoint = {\n version: 1,\n id: createCheckpointId(),\n createdAt: new Date().toISOString(),\n label: cpOptions?.label,\n systemExport: system.history.export(),\n timelineExport: timeline?.export() ?? null,\n localState: { type: \"single\" },\n memoryExport: memory ? ((memory as any).export?.() ?? null) : null,\n orchestratorType: \"single\",\n };\n\n if (checkpointStore) {\n await checkpointStore.save(cp);\n }\n\n return cp;\n },\n\n restore(cp: Checkpoint, restoreOpts?: { restoreTimeline?: boolean }): void {\n if (!validateCheckpoint(cp)) {\n throw new Error(\"[Directive] Invalid checkpoint data\");\n }\n if (cp.orchestratorType !== \"single\") {\n throw new Error(\n \"[Directive] Cannot restore multi-agent checkpoint in single-agent orchestrator\",\n );\n }\n if (!system.history?.import) {\n throw new Error(\n \"[Directive] Restoring a checkpoint requires history. Set `debug: true` in orchestrator options.\",\n );\n }\n\n system.history.import(cp.systemExport);\n\n if (\n restoreOpts?.restoreTimeline !== false &&\n cp.timelineExport &&\n timeline\n ) {\n timeline.import(cp.timelineExport);\n }\n\n if (cp.memoryExport !== null && memory && (memory as any).import) {\n (memory as any).import(cp.memoryExport);\n }\n },\n\n resumeBreakpoint(\n id: string,\n modifications?: BreakpointModifications,\n ): void {\n if (modifications) {\n breakpointModifications.set(id, modifications);\n }\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n const resolved = [...bpState.resolved, id];\n setBreakpointState(system.facts, {\n ...bpState,\n pending: bpState.pending.filter((r) => r.id !== id),\n resolved:\n resolved.length > MAX_BREAKPOINT_HISTORY\n ? resolved.slice(-MAX_BREAKPOINT_HISTORY)\n : resolved,\n });\n });\n },\n\n cancelBreakpoint(id: string, reason?: string): void {\n if (reason) {\n breakpointCancelReasons.set(id, reason);\n }\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n const cancelled = [...bpState.cancelled, id];\n setBreakpointState(system.facts, {\n ...bpState,\n pending: bpState.pending.filter((r) => r.id !== id),\n cancelled:\n cancelled.length > MAX_BREAKPOINT_HISTORY\n ? cancelled.slice(-MAX_BREAKPOINT_HISTORY)\n : cancelled,\n });\n });\n },\n\n getPendingBreakpoints(): BreakpointRequest[] {\n const bpState = getBreakpointState(system.facts);\n\n return [...bpState.pending];\n },\n\n destroy(): void {\n system.destroy();\n },\n };\n\n return orchestrator;\n}\n"]}
|