@directive-run/ai 0.8.5 → 0.8.7

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.
Files changed (64) hide show
  1. package/README.md +7 -0
  2. package/dist/anthropic.cjs +2 -3
  3. package/dist/anthropic.cjs.map +1 -1
  4. package/dist/anthropic.d.cts +1 -1
  5. package/dist/anthropic.d.ts +1 -1
  6. package/dist/anthropic.js +2 -3
  7. package/dist/anthropic.js.map +1 -1
  8. package/dist/chunk-265ZKXYE.js +3 -0
  9. package/dist/chunk-265ZKXYE.js.map +1 -0
  10. package/dist/chunk-7EJPXKDP.js +50 -0
  11. package/dist/chunk-7EJPXKDP.js.map +1 -0
  12. package/dist/chunk-B4ATEGA2.cjs +50 -0
  13. package/dist/chunk-B4ATEGA2.cjs.map +1 -0
  14. package/dist/chunk-MNYANBNX.js +14 -0
  15. package/dist/chunk-MNYANBNX.js.map +1 -0
  16. package/dist/chunk-QXMXSHYS.cjs +3 -0
  17. package/dist/chunk-QXMXSHYS.cjs.map +1 -0
  18. package/dist/chunk-W6MVJKWN.cjs +3 -0
  19. package/dist/chunk-W6MVJKWN.cjs.map +1 -0
  20. package/dist/chunk-W6WZBQER.js +3 -0
  21. package/dist/chunk-W6WZBQER.js.map +1 -0
  22. package/dist/chunk-WCJFIC22.cjs +14 -0
  23. package/dist/chunk-WCJFIC22.cjs.map +1 -0
  24. package/dist/gemini.cjs +2 -3
  25. package/dist/gemini.cjs.map +1 -1
  26. package/dist/gemini.d.cts +1 -1
  27. package/dist/gemini.d.ts +1 -1
  28. package/dist/gemini.js +2 -3
  29. package/dist/gemini.js.map +1 -1
  30. package/dist/index.cjs +30 -89
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.cts +194 -27
  33. package/dist/index.d.ts +194 -27
  34. package/dist/index.js +30 -89
  35. package/dist/index.js.map +1 -1
  36. package/dist/multi-agent-orchestrator-FEHVHZXA.js +2 -0
  37. package/dist/multi-agent-orchestrator-FEHVHZXA.js.map +1 -0
  38. package/dist/multi-agent-orchestrator-QWJNM4EZ.cjs +2 -0
  39. package/dist/multi-agent-orchestrator-QWJNM4EZ.cjs.map +1 -0
  40. package/dist/ollama.cjs +2 -2
  41. package/dist/ollama.cjs.map +1 -1
  42. package/dist/ollama.d.cts +1 -1
  43. package/dist/ollama.d.ts +1 -1
  44. package/dist/ollama.js +2 -2
  45. package/dist/ollama.js.map +1 -1
  46. package/dist/openai.cjs +2 -3
  47. package/dist/openai.cjs.map +1 -1
  48. package/dist/openai.d.cts +2 -2
  49. package/dist/openai.d.ts +2 -2
  50. package/dist/openai.js +2 -3
  51. package/dist/openai.js.map +1 -1
  52. package/dist/{multi-agent-orchestrator-DHp8gHXi.d.ts → orchestrator-types-DryFJyW9.d.ts} +6 -142
  53. package/dist/{multi-agent-orchestrator-C3VKkLzg.d.cts → orchestrator-types-tATJCBi5.d.cts} +6 -142
  54. package/dist/{semantic-cache-F0psCRuz.d.cts → semantic-cache-nBpQqILc.d.cts} +5 -5
  55. package/dist/{semantic-cache-F0psCRuz.d.ts → semantic-cache-nBpQqILc.d.ts} +5 -5
  56. package/dist/testing.cjs +1 -48
  57. package/dist/testing.cjs.map +1 -1
  58. package/dist/testing.d.cts +2 -2
  59. package/dist/testing.d.ts +2 -2
  60. package/dist/testing.js +1 -48
  61. package/dist/testing.js.map +1 -1
  62. package/dist/{types-BM-6xZf_.d.cts → types-CRmwFnVk.d.cts} +1 -1
  63. package/dist/{types-BM-6xZf_.d.ts → types-CRmwFnVk.d.ts} +1 -1
  64. package/package.json +3 -3
@@ -0,0 +1,14 @@
1
+ import {f,w,l,x,m,g,o,q,s,u,v,h,t as t$1,y,D,C,n,i,j,a,k,r,p,G,A,z,d,e}from'./chunk-7EJPXKDP.js';import {t,createModule,createSystem}from'@directive-run/core';import {requirementGuard,createCallbackPlugin,setBridgeFact,getBridgeFact}from'@directive-run/core/adapter-utils';var Le=500,qe=200;function kt(Ue){let{runner:V,factsSchema:ge={},init:me,constraints:je={},resolvers:He={},guardrails:P={},onApprovalRequest:re,autoApproveToolCalls:ne=true,maxTokenBudget:H,budgetWarningThreshold:J=.8,onBudgetWarning:fe,plugins:We=[],debug:he=false,approvalTimeoutMs:ae=3e5,agentRetry:z$1,hooks:ke={},memory:_,circuitBreaker:oe,selfHealing:T,outputSchema:Xe,maxSchemaRetries:Ke,checkpointStore:ve,breakpoints:S,onBreakpoint:Ye,breakpointTimeoutMs:Ve}=Ue,C$1=typeof he=="object"?true:!!he,se=5e3;if(C$1&&T&&!oe&&console.warn("[Directive] selfHealing config has no effect without a circuitBreaker \u2014 fallback behavior requires the circuit breaker to detect failures."),J<0||J>1)throw new Error(`[Directive Orchestrator] budgetWarningThreshold must be between 0 and 1, got ${J}`);if(!ne&&!re)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 $(e,r){try{ke[e]?.(r);}catch(o){C$1&&console.debug(`[Directive] hooks.${e} threw:`,o);}}let be=["agent","approval","conversation","toolCalls"];for(let e of Object.keys(ge))if(be.includes(e))throw new Error(`[Directive] Facts schema key "${e}" conflicts with orchestrator state. Reserved keys: ${be.join(", ")}. Rename your fact to avoid the collision.`);let Je={facts:{...f.facts,...ge,__budgetWarningFired:t.boolean()},derivations:{},events:{},requirements:{}},ye,t$2,Te=w(je);H&&(Te.__budgetLimit={priority:100,when:e=>l(e).tokenUsage>H,require:{type:"__PAUSE_BUDGET_EXCEEDED"}});let we=x(He,(e,r,o,a)=>ye(e,r,o,a),()=>t$2.facts);we.__pause={requirement:requirementGuard("__PAUSE_BUDGET_EXCEEDED"),resolve:async(e,r)=>{let o=l(r.facts);m(r.facts,{...o,status:"paused"});}};let f$1=null;C$1&&(f$1=g({getSnapshotId:()=>{try{return t$2.history?.currentIndex??null}catch{return null}},goToSnapshot:e=>{try{t$2.history?.goTo?.(e);}catch{}}}));let ze=createCallbackPlugin("directive-ai-callbacks",{}),Qe=createModule("directive-ai-orchestrator",{schema:Je,init:e=>{if(m(e,{status:"idle",currentAgent:null,input:null,output:null,error:null,tokenUsage:0,turnCount:0,startedAt:null,completedAt:null}),o(e,{pending:[],approved:[],rejected:[]}),q(e,[]),s(e,[]),u(e,{pending:[],resolved:[],cancelled:[]}),setBridgeFact(e,"__budgetWarningFired",false),me){let r=v(e),o={...e,...r};me(o);}},constraints:Te,resolvers:we}),Re=[...We,ze];C$1&&f$1&&Re.push(h(f$1,()=>{try{return t$2.history?.currentIndex??null}catch{return null}})),t$2=createSystem({module:Qe,plugins:Re,history:C$1?true:void 0}),t$2.start();async function Ae(e,r,o,a,i){if(oe)try{return await oe.execute(()=>Se(e,r,o,a,i))}catch(u){if(T){if(T.fallbackRunners)for(let g of T.fallbackRunners)try{let b={originalAgent:e.name,reroutedTo:"fallback-runner",reason:u instanceof Error?u.message:String(u),timestamp:Date.now()};try{T.onReroute?.(b);}catch{}return f$1&&f$1.record({type:"reroute",timestamp:Date.now(),agentId:e.name,snapshotId:null,from:e.name,to:"fallback-runner",reason:u instanceof Error?u.message:String(u)}),await g(e,r,a)}catch{}if(T.fallbackAgent)try{let g={originalAgent:e.name,reroutedTo:T.fallbackAgent.name,reason:u instanceof Error?u.message:String(u),timestamp:Date.now()};try{T.onReroute?.(g);}catch{}return f$1&&f$1.record({type:"reroute",timestamp:Date.now(),agentId:e.name,snapshotId:null,from:e.name,to:T.fallbackAgent.name,reason:u instanceof Error?u.message:String(u)}),await V(T.fallbackAgent,r,a)}catch{}if(T.degradation==="fallback-response"&&T.fallbackResponse!==void 0)return {output:T.fallbackResponse,messages:[],toolCalls:[],totalTokens:0}}throw u}return Se(e,r,o,a,i)}async function Se(e,r$1,o$1,a$1,i$1){let u=Date.now();if(_){let n=_.getContextMessages();if(n.length>0){let c=n.map(v=>`${v.role}: ${v.content}`).join(`
4
+ `);e={...e,instructions:(e.instructions??"")+`
5
+
6
+ Conversation context:
7
+ `+c};}}if(S&&S.length>0){let n={agentId:e.name,agentName:e.name,input:r$1,state:t$2.facts.$store.toObject(),breakpointType:"pre_input_guardrails"},c=await Q("pre_input_guardrails",n,i$1?.signal??a$1?.signal);if(c?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};c?.input&&(r$1=c.input);}let g=i$1?.inputGuardrails!==void 0?i$1.inputGuardrails:P.input??[],b=i$1?.outputGuardrails!==void 0?i$1.outputGuardrails:P.output??[],D=g.map((n,c)=>i(n,c,"input"));for(let n of D){let{name:c}=n,v={agentName:e.name,input:r$1,facts:t$2.facts.$store.toObject()},d=Date.now(),p=await j(n,{input:r$1,agentName:e.name},v);if($("onGuardrailCheck",{agentId:e.name,guardrailName:c,guardrailType:"input",passed:p.passed,reason:p.reason,durationMs:Date.now()-d,timestamp:Date.now()}),!p.passed)throw new a({code:"INPUT_GUARDRAIL_FAILED",message:`Input guardrail "${c}" failed: ${p.reason}`,guardrailName:c,guardrailType:"input",userMessage:p.reason??"Input validation failed",agentName:e.name,input:r$1});p.transformed!==void 0&&(r$1=p.transformed);}if($("onAgentStart",{agentName:e.name,input:r$1,timestamp:u}),f$1&&f$1.record({type:"agent_start",timestamp:Date.now(),agentId:e.name,snapshotId:null,inputLength:r$1.length,modelId:e.model??void 0,...e.instructions?{instructions:e.instructions.slice(0,se)}:{},input:r$1.slice(0,se)}),t$2.batch(()=>{let n=l(t$2.facts);m(t$2.facts,{...n,status:"running",currentAgent:e.name,input:r$1,startedAt:Date.now()});}),S&&S.length>0){let n={agentId:e.name,agentName:e.name,input:r$1,state:t$2.facts.$store.toObject(),breakpointType:"pre_agent_run"},c=await Q("pre_agent_run",n,i$1?.signal??a$1?.signal);if(c?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};c?.input&&(r$1=c.input);}let w=i$1?.outputSchema!==void 0?i$1.outputSchema:Xe,A=V;w&&(A=G(V,{schema:w,maxRetries:i$1?.maxSchemaRetries??Ke??2}));let l$1=await k(A,e,r$1,{...a$1,signal:a$1?.signal,onMessage:n=>{let v=[...p(t$2.facts),n];q(t$2.facts,v.length>Le?v.slice(-Le):v),a$1?.onMessage?.(n);},onToolCall:async n$1=>{let c=(P.toolCall??[]).map((p,h)=>i(p,h,"toolCall"));for(let p of c){let{name:h}=p,L={agentName:e.name,input:r$1,facts:t$2.facts.$store.toObject()},ie=Date.now(),s=await j(p,{toolCall:n$1,agentName:e.name,input:r$1},L);if($("onGuardrailCheck",{agentId:e.name,guardrailName:h,guardrailType:"toolCall",passed:s.passed,reason:s.reason,durationMs:Date.now()-ie,timestamp:Date.now()}),!s.passed)throw new a({code:"TOOL_CALL_GUARDRAIL_FAILED",message:`Tool call guardrail "${h}" failed: ${s.reason}`,guardrailName:h,guardrailType:"toolCall",userMessage:s.reason??"Tool call blocked",data:{toolCall:n$1},agentName:e.name,input:r$1})}if(!ne){let p=`tool-${n$1.id}`,h={id:p,type:"tool_call",agentName:e.name,description:`Tool call: ${n$1.name}`,data:n$1,requestedAt:Date.now()};t$2.batch(()=>{let L=n(t$2.facts);o(t$2.facts,{...L,pending:[...L.pending,h]});}),re?.(h),await Ce(p,i$1?.signal??a$1?.signal);}let d=[...r(t$2.facts),n$1];s(t$2.facts,d.length>qe?d.slice(-qe):d),a$1?.onToolCall?.(n$1);}},z$1?{...z$1,onRetry:(n,c,v)=>{z$1.onRetry?.(n,c,v),$("onAgentRetry",{agentName:e.name,input:r$1,attempt:n,error:c,delayMs:v,timestamp:Date.now()});}}:void 0);if(S&&S.length>0){let n={agentId:e.name,agentName:e.name,input:r$1,state:t$2.facts.$store.toObject(),breakpointType:"pre_output_guardrails"},c=await Q("pre_output_guardrails",n,i$1?.signal??a$1?.signal);if(c?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};c?.input&&(r$1=c.input);}let F=b.map((n,c)=>i(n,c,"output"));for(let n of F){let{name:c}=n,v={agentName:e.name,input:r$1,facts:t$2.facts.$store.toObject()},d=Date.now(),p=await j(n,{output:l$1.output,agentName:e.name,input:r$1,messages:l$1.messages},v);if($("onGuardrailCheck",{agentId:e.name,guardrailName:c,guardrailType:"output",passed:p.passed,reason:p.reason,durationMs:Date.now()-d,timestamp:Date.now()}),!p.passed)throw new a({code:"OUTPUT_GUARDRAIL_FAILED",message:`Output guardrail "${c}" failed: ${p.reason}`,guardrailName:c,guardrailType:"output",userMessage:p.reason??"Output validation failed",agentName:e.name,input:r$1});p.transformed!==void 0&&(l$1.output=p.transformed);}let Z=false,k$1=0;if(t$2.batch(()=>{let n=l(t$2.facts),c=n.tokenUsage+l$1.totalTokens;if(m(t$2.facts,{...n,status:"completed",output:l$1.output,tokenUsage:c,turnCount:n.turnCount+l$1.messages.length,completedAt:Date.now()}),H&&fe){k$1=c/H;let v=getBridgeFact(t$2.facts,"__budgetWarningFired");k$1>=J&&!v&&(setBridgeFact(t$2.facts,"__budgetWarningFired",true),Z=true);}}),Z)try{fe({currentTokens:l(t$2.facts).tokenUsage,maxBudget:H,percentage:k$1});}catch(n){C$1&&console.debug("[Directive Orchestrator] onBudgetWarning threw:",n);}if(_&&l$1.messages.length>0)try{_.addMessages(l$1.messages);}catch(n){C$1&&console.debug("[Directive] Memory addMessages failed:",n);}if($("onAgentComplete",{agentName:e.name,input:r$1,output:l$1.output,tokenUsage:l$1.totalTokens,durationMs:Date.now()-u,timestamp:Date.now()}),f$1){let n=typeof l$1.output=="string"?l$1.output:JSON.stringify(l$1.output);f$1.record({type:"agent_complete",timestamp:Date.now(),agentId:e.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()-u,modelId:e.model??void 0,output:n.slice(0,se)});}if(S&&S.length>0){let n={agentId:e.name,agentName:e.name,input:r$1,state:t$2.facts.$store.toObject(),breakpointType:"post_run"},c=await Q("post_run",n,i$1?.signal??a$1?.signal);if(c?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};c?.input&&(r$1=c.input);}return l$1}ye=Ae;let G$1=new Map,W=new Map;function Ze(e$1,r){return r?.aborted?Promise.reject(r.reason??new Error("Aborted while waiting for breakpoint")):new Promise((o,a)=>{let i=false,u=null,g=()=>{i||(i=true,u&&(clearTimeout(u),u=null),r&&r.removeEventListener("abort",b),D());},b=()=>{g(),a(r.reason??new Error(`Breakpoint wait for ${e$1} aborted`));};r&&r.addEventListener("abort",b,{once:true});let D=t$2.facts.$store.subscribe([e],()=>{if(i)return;let A=t$1(t$2.facts);if(A.resolved.includes(e$1)){g();let l=G$1.get(e$1)??null;G$1.delete(e$1),o(l);}else if(A.cancelled.includes(e$1)){g(),G$1.delete(e$1);let l=W.get(e$1);W.delete(e$1),a(new Error(l?`Breakpoint ${e$1} was cancelled: ${l}`:`Breakpoint ${e$1} was cancelled`));}}),w=Ve??3e5;u=setTimeout(()=>{i||(g(),G$1.delete(e$1),W.delete(e$1),a(new Error(`[Directive] Breakpoint timeout: ${e$1} not resolved within ${Math.round(w/1e3)}s`)));},w);})}async function Q(e,r,o){if(!S||S.length===0)return null;let a=A(S,e,r);if(!a)return null;let i=z(),u$1={id:i,type:e,agentId:r.agentId,input:r.input,label:a.label,requestedAt:Date.now()};t$2.batch(()=>{let b=t$1(t$2.facts);u(t$2.facts,{...b,pending:[...b.pending,u$1]});});try{Ye?.(u$1);}catch{}try{ke.onBreakpoint?.(u$1);}catch{}f$1&&f$1.record({type:"breakpoint_hit",timestamp:Date.now(),snapshotId:null,agentId:r.agentId,breakpointId:i,breakpointType:e,label:a.label});let g=await Ze(i,o);return f$1&&f$1.record({type:"breakpoint_resumed",timestamp:Date.now(),snapshotId:null,agentId:r.agentId,breakpointId:i,modified:!!g?.input,skipped:!!g?.skip}),g}function Ce(e,r){return r?.aborted?Promise.reject(r.reason??new Error("Aborted while waiting for approval")):new Promise((o,a)=>{let i=false,u=null,g=()=>{i||(i=true,u&&(clearTimeout(u),u=null),r&&r.removeEventListener("abort",b),D());},b=()=>{g(),a(r.reason??new Error(`Approval wait for ${e} aborted`));};r&&r.addEventListener("abort",b,{once:true});let D=t$2.facts.$store.subscribe([d],()=>{if(i)return;let w=n(t$2.facts);if(w.approved.includes(e))g(),o();else {let A=w.rejected.find(l=>l.id===e);if(A){g();let l=A.reason?`Request ${e} rejected: ${A.reason}`:`Request ${e} rejected`;a(new Error(l));}}});u=setTimeout(()=>{if(i)return;g();let w=Math.round(ae/1e3);a(new Error(`[Directive] Approval timeout: Request ${e} not resolved within ${w}s.
8
+ Solutions:
9
+ 1. Handle via onApprovalRequest callback and call orchestrator.approve()/reject()
10
+ 2. Set autoApproveToolCalls: true to auto-approve
11
+ 3. Increase approvalTimeoutMs (current: ${ae}ms)
12
+ See: https://directive.run/docs/ai/running-agents`));},ae);})}function Ee(){return {...v(t$2.facts)}}return {system:t$2,get facts(){return Ee()},get totalTokens(){return l(t$2.facts).tokenUsage},get timeline(){return f$1},async run(e,r,o){return Ae(e,r,Ee(),void 0,o)},runStream(e,r$1,o$1={}){let a$1=new AbortController,i$1=1e4,u=[],g=[],b=false,D=Date.now(),w=0,A=1e5,l$1="",F;o$1.signal&&(F=()=>a$1.abort(),o$1.signal.addEventListener("abort",F,{once:true}));let Z=()=>{F&&o$1.signal&&o$1.signal.removeEventListener("abort",F);},k$1=d=>{if(b)return;let p=g.shift();p?p(d):(u.push(d),u.length>i$1&&u.shift());},n$1=()=>{b=true,Z();for(let d of g)d(null);g.length=0;},c=(async()=>{k$1({type:"progress",phase:"starting",message:"Running input guardrails"});try{let d=r$1,p$1=(P.input??[]).map((s,y)=>i(s,y,"input"));for(let s of p$1){let{name:y}=s,B={agentName:e.name,input:d,facts:t$2.facts.$store.toObject()},m=await j(s,{input:d,agentName:e.name},B);if(!m.passed)throw k$1({type:"guardrail_triggered",guardrailName:y,reason:m.reason??"Input validation failed",partialOutput:l$1,stopped:!0}),new a({code:"INPUT_GUARDRAIL_FAILED",message:`Input guardrail "${y}" failed: ${m.reason}`,guardrailName:y,guardrailType:"input",userMessage:m.reason??"Input validation failed",agentName:e.name,input:d});m.transformed!==void 0&&(d=m.transformed);}k$1({type:"progress",phase:"generating",message:"Starting agent"}),t$2.batch(()=>{let s=l(t$2.facts);m(t$2.facts,{...s,status:"running",currentAgent:e.name,input:d,startedAt:Date.now()});});let h=await k(V,e,d,{signal:a$1.signal,onMessage:s=>{let y=p(t$2.facts);if(q(t$2.facts,[...y,s]),k$1({type:"message",message:s}),s.role==="assistant"&&s.content){let B=Math.ceil(s.content.length/4);w+=B,l$1+=s.content,l$1.length>A&&(l$1=l$1.slice(-A)),k$1({type:"token",data:s.content,tokenCount:w});}},onToolCall:async s$1=>{k$1({type:"tool_start",tool:s$1.name,toolCallId:s$1.id,arguments:s$1.arguments});let y=(P.toolCall??[]).map((m,O)=>i(m,O,"toolCall"));for(let m of y){let{name:O}=m,ee={agentName:e.name,input:d,facts:t$2.facts.$store.toObject()},te=await j(m,{toolCall:s$1,agentName:e.name,input:d},ee);if(!te.passed)throw k$1({type:"guardrail_triggered",guardrailName:O,reason:te.reason??"Tool call blocked",partialOutput:l$1,stopped:!0}),new a({code:"TOOL_CALL_GUARDRAIL_FAILED",message:`Tool call guardrail "${O}" failed: ${te.reason}`,guardrailName:O,guardrailType:"toolCall",userMessage:te.reason??"Tool call blocked",data:{toolCall:s$1},agentName:e.name,input:d})}if(!ne){let m=`tool-${s$1.id}`;k$1({type:"approval_required",requestId:m,toolName:s$1.name});let O={id:m,type:"tool_call",agentName:e.name,description:`Tool call: ${s$1.name}`,data:s$1,requestedAt:Date.now()};t$2.batch(()=>{let ee=n(t$2.facts);o(t$2.facts,{...ee,pending:[...ee.pending,O]});}),re?.(O),await Ce(m,a$1.signal),k$1({type:"approval_resolved",requestId:m,approved:!0});}let B=r(t$2.facts);s(t$2.facts,[...B,s$1]),s$1.result&&k$1({type:"tool_end",tool:s$1.name,toolCallId:s$1.id,result:s$1.result});}},z$1);k$1({type:"progress",phase:"finishing",message:"Running output guardrails"});let L=(P.output??[]).map((s,y)=>i(s,y,"output"));for(let s of L){let{name:y}=s,B={agentName:e.name,input:d,facts:t$2.facts.$store.toObject()},m=await j(s,{output:h.output,agentName:e.name,input:d,messages:h.messages},B);if(!m.passed)throw k$1({type:"guardrail_triggered",guardrailName:y,reason:m.reason??"Output validation failed",partialOutput:typeof h.output=="string"?h.output:"",stopped:!0}),new a({code:"OUTPUT_GUARDRAIL_FAILED",message:`Output guardrail "${y}" failed: ${m.reason}`,guardrailName:y,guardrailType:"output",userMessage:m.reason??"Output validation failed",agentName:e.name,input:d});m.transformed!==void 0&&(h.output=m.transformed);}t$2.batch(()=>{let s=l(t$2.facts);m(t$2.facts,{...s,status:"completed",output:h.output,tokenUsage:s.tokenUsage+h.totalTokens,turnCount:s.turnCount+h.messages.length,completedAt:Date.now()});});let ie=Date.now()-D;return k$1({type:"done",totalTokens:h.totalTokens,duration:ie,droppedTokens:0}),n$1(),h}catch(d){throw k$1({type:"error",error:d instanceof Error?d:new Error(String(d))}),n$1(),d}})();return c.catch(()=>{}),{stream:{[Symbol.asyncIterator](){return {async next(){return u.length>0?{done:false,value:u.shift()}:b?{done:true,value:void 0}:new Promise(d=>{g.push(p=>{d(p===null?{done:true,value:void 0}:{done:false,value:p});});})}}}},result:c,abort:()=>{a$1.abort(),n$1();}}},async waitForIdle(e){let r=()=>l(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=n(t$2.facts);if(!r.pending.some(i=>i.id===e)){C$1&&console.debug(`[Directive] approve() ignored: no pending request "${e}"`);return}let o$1=200,a=[...r.approved,e];o(t$2.facts,{...r,pending:r.pending.filter(i=>i.id!==e),approved:a.length>o$1?a.slice(-o$1):a});});},reject(e,r){t$2.batch(()=>{let o$1=n(t$2.facts);if(!o$1.pending.some(g=>g.id===e)){C$1&&console.debug(`[Directive] reject() ignored: no pending request "${e}"`);return}r&&C$1&&console.debug(`[Directive] Request ${e} rejected: ${r}`);let a={id:e,reason:r,rejectedAt:Date.now()},i=200,u=[...o$1.rejected,a];o(t$2.facts,{...o$1,pending:o$1.pending.filter(g=>g.id!==e),rejected:u.length>i?u.slice(-i):u});});},pause(){let e=l(t$2.facts);m(t$2.facts,{...e,status:"paused"});},resume(){let e=l(t$2.facts);e.status==="paused"&&m(t$2.facts,{...e,status:e.currentAgent?"running":"idle"});},reset(){t$2.batch(()=>{m(t$2.facts,{status:"idle",currentAgent:null,input:null,output:null,error:null,tokenUsage:0,turnCount:0,startedAt:null,completedAt:null}),o(t$2.facts,{pending:[],approved:[],rejected:[]}),q(t$2.facts,[]),s(t$2.facts,[]),u(t$2.facts,{pending:[],resolved:[],cancelled:[]}),setBridgeFact(t$2.facts,"__budgetWarningFired",false);}),G$1.clear(),W.clear();},async checkpoint(e){if(l(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:C(),createdAt:new Date().toISOString(),label:e?.label,systemExport:t$2.history.export(),timelineExport:f$1?.export()??null,localState:{type:"single"},memoryExport:_?_.export?.()??null:null,orchestratorType:"single"};return ve&&await ve.save(o),o},restore(e,r){if(!D(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&&f$1&&f$1.import(e.timelineExport),e.memoryExport!==null&&_&&_.import&&_.import(e.memoryExport);},resumeBreakpoint(e,r){r&&G$1.set(e,r),t$2.batch(()=>{let o=t$1(t$2.facts),a=[...o.resolved,e];u(t$2.facts,{...o,pending:o.pending.filter(i=>i.id!==e),resolved:a.length>y?a.slice(-y):a});});},cancelBreakpoint(e,r){r&&W.set(e,r),t$2.batch(()=>{let o=t$1(t$2.facts),a=[...o.cancelled,e];u(t$2.facts,{...o,pending:o.pending.filter(i=>i.id!==e),cancelled:a.length>y?a.slice(-y):a});});},getPendingBreakpoints(){return [...t$1(t$2.facts).pending]},destroy(){t$2.destroy();}}}
13
+ export{kt as a};//# sourceMappingURL=chunk-MNYANBNX.js.map
14
+ //# sourceMappingURL=chunk-MNYANBNX.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","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","resultPromise","processedInput","inputGuardrails","currentConversation","newTokens","currentToolCalls","outputGuardrails","duration","timeoutMs","isIdle","start","MAX_APPROVAL_HISTORY","approved","reason","MAX_REJECTION_HISTORY","rejected","cpOptions","cp","createCheckpointId","restoreOpts","validateCheckpoint","id","modifications","resolved","MAX_BREAKPOINT_HISTORY","cancelled"],"mappings":"iRA2GA,IAAMA,EAAAA,CAA4B,GAAA,CAE5BC,EAAAA,CAAiB,GAAA,CA4RhB,SAASC,EAAAA,CAEdC,EAAAA,CAAuD,CACvD,GAAM,CACJ,MAAA,CAAAC,CAAAA,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,CAAAA,CAAyB,EAAA,CACzB,eAAA,CAAAC,EAA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dA,GAAAA,CAAO,OAAA,GACT,CACF,CAGF","file":"chunk-MNYANBNX.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 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\n/** Streaming run result from orchestrator */\nexport interface OrchestratorStreamResult<T = unknown> {\n /** Async iterator for streaming chunks */\n stream: AsyncIterable<OrchestratorStreamChunk>;\n /** Promise that resolves to the final result */\n result: Promise<RunResult<T>>;\n /** Abort the stream */\n abort: () => void;\n}\n\n/** Stream chunk types for orchestrator — extends StreamChunk with approval events */\nexport type OrchestratorStreamChunk =\n | StreamChunkBase\n | { type: \"approval_required\"; requestId: string; toolName: string }\n | { type: \"approval_resolved\"; requestId: string; approved: boolean };\n\n/** Per-call options for run() */\nexport interface RunCallOptions {\n /** Override output guardrails for this call only. Set to [] to skip. */\n outputGuardrails?: Array<\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?: { signal?: AbortSignal },\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);\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. ` +\n `Reserved keys: ${RESERVED_ORCHESTRATOR_KEYS.join(\", \")}. ` +\n \"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:\n (agent.instructions ?? \"\") +\n \"\\n\\nConversation context:\\n\" +\n contextStr,\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.\\n` +\n \"Solutions:\\n\" +\n \" 1. Handle via onApprovalRequest callback and call orchestrator.approve()/reject()\\n\" +\n \" 2. Set autoApproveToolCalls: true to auto-approve\\n\" +\n ` 3. Increase approvalTimeoutMs (current: ${approvalTimeoutMs}ms)\\n` +\n \"See: https://directive.run/docs/ai/running-agents\",\n ),\n );\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: { signal?: AbortSignal } = {},\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 // 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 return {\n stream,\n result: resultPromise,\n abort: () => {\n abortController.abort();\n closeStream();\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"]}
@@ -0,0 +1,3 @@
1
+ 'use strict';async function k(e,t){let n=await e.text().catch(()=>"");throw new Error(`[Directive] ${t} streaming error ${e.status}${n?` \u2013 ${n.slice(0,200)}`:""}`)}function w(e){let t=e.body?.getReader();if(!t)throw new Error("[Directive] No response body");return t}function E(e,t){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&!e&&console.warn(`[Directive] ${t}: apiKey is empty. API calls will fail.`);}async function T(e,t,n,o){let s=new TextDecoder,i="",a="",f=0,l=0;try{for(;;){let{done:g,value:m}=await e.read();if(g)break;i+=s.decode(m,{stream:!0});let d=i.split(`
2
+ `);i=d.pop()??"";for(let p of d){if(!p.startsWith("data: "))continue;let c=p.slice(6).trim();if(c!=="[DONE]")try{let u=JSON.parse(c),r=n(u);r.text&&(a+=r.text,t?.(r.text)),r.inputTokens!==void 0&&(f=r.inputTokens),r.outputTokens!==void 0&&(l=r.outputTokens);}catch(u){if(u instanceof SyntaxError)typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[Directive] Malformed SSE event from ${o}:`,c);else throw u}}}}finally{e.cancel().catch(()=>{});}return {fullText:a,inputTokens:f,outputTokens:l}}function v(e,t,n){let o=Date.now();return e?.onBeforeCall?.({agent:t,input:n,timestamp:o}),o}function y(e,t,n,o,s,i,a){e?.onAfterCall?.({agent:t,input:n,output:o,totalTokens:s,tokenUsage:i,durationMs:Date.now()-a,timestamp:Date.now()});}function b(e,t,n,o,s){o instanceof Error&&e?.onError?.({agent:t,input:n,error:o,durationMs:Date.now()-s,timestamp:Date.now()});}function x(e,t,n,o){return {output:t,messages:[{role:"user",content:e},{role:"assistant",content:t}],toolCalls:[],totalTokens:n,tokenUsage:o}}exports.a=k;exports.b=w;exports.c=E;exports.d=T;exports.e=v;exports.f=y;exports.g=b;exports.h=x;//# sourceMappingURL=chunk-QXMXSHYS.cjs.map
3
+ //# sourceMappingURL=chunk-QXMXSHYS.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/shared.ts"],"names":["throwStreamingHTTPError","response","adapterName","errBody","getSSEReader","reader","warnIfMissingApiKey","apiKey","functionName","parseSSEStream","onToken","parseEvent","decoder","buf","fullText","inputTokens","outputTokens","done","value","lines","line","data","event","result","parseErr","fireBeforeCallHook","hooks","agent","input","startTime","fireAfterCallHook","output","totalTokens","tokenUsage","fireErrorHook","err","buildStreamingResult"],"mappings":"aAsBA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACgB,CAChB,IAAMC,CAAAA,CAAU,MAAMF,CAAAA,CAAS,IAAA,EAAK,CAAE,KAAA,CAAM,IAAM,EAAE,CAAA,CAEpD,MAAM,IAAI,KAAA,CACR,CAAA,YAAA,EAAeC,CAAW,CAAA,iBAAA,EAAoBD,CAAAA,CAAS,MAAM,CAAA,EAAGE,CAAAA,CAAU,CAAA,QAAA,EAAMA,CAAAA,CAAQ,KAAA,CAAM,CAAA,CAAG,GAAG,CAAC,CAAA,CAAA,CAAK,EAAE,CAAA,CAC9G,CACF,CAKO,SAASC,CAAAA,CACdH,CAAAA,CACyC,CACzC,IAAMI,CAAAA,CAASJ,CAAAA,CAAS,IAAA,EAAM,SAAA,EAAU,CACxC,GAAI,CAACI,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,8BAA8B,CAAA,CAGhD,OAAOA,CACT,CASO,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACM,CAEJ,OAAO,OAAA,CAAY,GAAA,EACnB,OAAA,CAAQ,GAAA,EAAK,QAAA,GAAa,YAAA,EAC1B,CAACD,CAAAA,EAED,OAAA,CAAQ,IAAA,CACN,CAAA,YAAA,EAAeC,CAAY,CAAA,uCAAA,CAC7B,EAEJ,CA4BA,eAAsBC,CAAAA,CACpBJ,CAAAA,CACAK,CAAAA,CACAC,CAAAA,CACAT,CAAAA,CAC0E,CAC1E,IAAMU,CAAAA,CAAU,IAAI,WAAA,CAChBC,CAAAA,CAAM,EAAA,CACNC,CAAAA,CAAW,EAAA,CACXC,CAAAA,CAAc,CAAA,CACdC,CAAAA,CAAe,CAAA,CAEnB,GAAI,CACF,OAAa,CACX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,MAAA,CAAQnB,CAAAA,CACR,QAAA,CAAU,CAAC,CAAE,IAAA,CAAM,MAAA,CAAiB,OAAA,CAASc,CAAM,CAAA,CAJvB,CAAE,KAAM,WAAA,CAAa,OAAA,CAASd,CAAS,CAID,CAAA,CAClE,SAAA,CAAW,EAAC,CACZ,WAAA,CAAAkB,CAAAA,CACA,UAAA,CAAAC,CACF,CACF","file":"chunk-QXMXSHYS.cjs","sourcesContent":["/**\n * Shared utilities for streaming adapters.\n *\n * Extracts common SSE parsing, error handling, hook lifecycle, and response\n * building logic used across Anthropic, OpenAI, and Gemini streaming runners.\n */\n\nimport type {\n AdapterHooks,\n AgentLike,\n Message,\n TokenUsage,\n} from \"../types.js\";\n\n// ============================================================================\n// HTTP Error Handling\n// ============================================================================\n\n/**\n * Throw a standardized HTTP error from a streaming response.\n * Reads up to 200 chars of the error body for diagnostics.\n */\nexport async function throwStreamingHTTPError(\n response: Response,\n adapterName: string,\n): Promise<never> {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] ${adapterName} streaming error ${response.status}${errBody ? ` – ${errBody.slice(0, 200)}` : \"\"}`,\n );\n}\n\n/**\n * Get an SSE reader from a response, throwing if body is missing.\n */\nexport function getSSEReader(\n response: Response,\n): ReadableStreamDefaultReader<Uint8Array> {\n const reader = response.body?.getReader();\n if (!reader) {\n throw new Error(\"[Directive] No response body\");\n }\n\n return reader;\n}\n\n// ============================================================================\n// API Key Validation\n// ============================================================================\n\n/**\n * Warn in non-production environments if an API key is empty.\n */\nexport function warnIfMissingApiKey(\n apiKey: string | undefined,\n functionName: string,\n): void {\n if (\n typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\" &&\n !apiKey\n ) {\n console.warn(\n `[Directive] ${functionName}: apiKey is empty. API calls will fail.`,\n );\n }\n}\n\n// ============================================================================\n// SSE Stream Parser\n// ============================================================================\n\n/** Result from parsing a single SSE event (provider-specific). */\nexport interface SSEEventResult {\n /** Text token to append to output. */\n text?: string;\n /** Updated input token count (cumulative, not delta). */\n inputTokens?: number;\n /** Updated output token count (cumulative, not delta). */\n outputTokens?: number;\n}\n\n/**\n * Parse an SSE stream from a Response, calling `onToken` for each text chunk\n * and `parseEvent` for provider-specific event extraction.\n *\n * Handles buffering, `[DONE]` sentinels, malformed JSON, and reader cleanup.\n *\n * @param reader - The ReadableStream reader from the response body.\n * @param onToken - Callback for each text token (may be undefined).\n * @param parseEvent - Provider-specific function to extract text and tokens from a parsed SSE event.\n * @param adapterName - Adapter name for dev-mode warnings.\n * @returns The full text output and final token counts.\n */\nexport async function parseSSEStream(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n onToken: ((token: string) => void) | undefined,\n parseEvent: (event: Record<string, unknown>) => SSEEventResult,\n adapterName: string,\n): Promise<{ fullText: string; inputTokens: number; outputTokens: number }> {\n const decoder = new TextDecoder();\n let buf = \"\";\n let fullText = \"\";\n let inputTokens = 0;\n let outputTokens = 0;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n buf += decoder.decode(value, { stream: true });\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) {\n continue;\n }\n const data = line.slice(6).trim();\n if (data === \"[DONE]\") {\n continue;\n }\n\n try {\n const event = JSON.parse(data);\n const result = parseEvent(event);\n if (result.text) {\n fullText += result.text;\n onToken?.(result.text);\n }\n if (result.inputTokens !== undefined) {\n inputTokens = result.inputTokens;\n }\n if (result.outputTokens !== undefined) {\n outputTokens = result.outputTokens;\n }\n } catch (parseErr) {\n if (parseErr instanceof SyntaxError) {\n if (\n typeof process !== \"undefined\" &&\n process.env?.NODE_ENV === \"development\"\n ) {\n console.warn(\n `[Directive] Malformed SSE event from ${adapterName}:`,\n data,\n );\n }\n } else {\n throw parseErr;\n }\n }\n }\n }\n } finally {\n reader.cancel().catch(() => {});\n }\n\n return { fullText, inputTokens, outputTokens };\n}\n\n// ============================================================================\n// Hook Lifecycle Helpers\n// ============================================================================\n\n/**\n * Fire the onBeforeCall hook and return the start timestamp.\n */\nexport function fireBeforeCallHook(\n hooks: AdapterHooks | undefined,\n agent: AgentLike,\n input: string,\n): number {\n const startTime = Date.now();\n hooks?.onBeforeCall?.({ agent, input, timestamp: startTime });\n\n return startTime;\n}\n\n/**\n * Fire the onAfterCall hook with timing and token data.\n */\nexport function fireAfterCallHook(\n hooks: AdapterHooks | undefined,\n agent: AgentLike,\n input: string,\n output: string,\n totalTokens: number,\n tokenUsage: TokenUsage,\n startTime: number,\n): void {\n hooks?.onAfterCall?.({\n agent,\n input,\n output,\n totalTokens,\n tokenUsage,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n });\n}\n\n/**\n * Fire the onError hook if the error is an Error instance.\n */\nexport function fireErrorHook(\n hooks: AdapterHooks | undefined,\n agent: AgentLike,\n input: string,\n err: unknown,\n startTime: number,\n): void {\n if (err instanceof Error) {\n hooks?.onError?.({\n agent,\n input,\n error: err,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n });\n }\n}\n\n// ============================================================================\n// Streaming Response Builder\n// ============================================================================\n\n/**\n * Build the standard streaming runner return value.\n */\nexport function buildStreamingResult(\n input: string,\n fullText: string,\n totalTokens: number,\n tokenUsage: TokenUsage,\n): {\n output: string;\n messages: Message[];\n toolCalls: never[];\n totalTokens: number;\n tokenUsage: TokenUsage;\n} {\n const assistantMsg: Message = { role: \"assistant\", content: fullText };\n\n return {\n output: fullText,\n messages: [{ role: \"user\" as const, content: input }, assistantMsg],\n toolCalls: [],\n totalTokens,\n tokenUsage,\n };\n}\n"]}
@@ -0,0 +1,3 @@
1
+ 'use strict';function x(e){return e.status==="running"}function M(e){return e.pending.length>0}function O(e,t){return e/1e6*t}var b=new Set(["http:","https:"]);function D(e){try{let t=new URL(e);if(!b.has(t.protocol))throw new Error(`[Directive] Invalid baseURL protocol "${t.protocol}" \u2013 only http: and https: are allowed`)}catch(t){throw t instanceof Error&&t.message.startsWith("[Directive]")?t:new Error(`[Directive] Invalid baseURL "${e}" \u2013 must be a valid URL (e.g. "https://api.openai.com/v1")`)}}function L(e){let{fetch:t=globalThis.fetch,buildRequest:T,parseResponse:f,parseOutput:m,hooks:u}=e,k=m??(s=>{try{return JSON.parse(s)}catch{return s}});return async(s,o,p)=>{let c=Date.now();u?.onBeforeCall?.({agent:s,input:o,timestamp:c});let l=[{role:"user",content:o}];try{let{url:r,init:i}=T(s,o,l),d=p?.signal?{...i,signal:p.signal}:i,a=await t(r,d);if(!a.ok){let R=await a.text().catch(()=>"");throw new Error(`[Directive] AgentRunner request failed: ${a.status} ${a.statusText}${R?` \u2013 ${R.slice(0,300)}`:""}`)}let n=await f(a,l),g={inputTokens:n.inputTokens??0,outputTokens:n.outputTokens??0},h={role:"assistant",content:n.text},w=[...l,h];p?.onMessage?.(h);let A=Date.now()-c;return u?.onAfterCall?.({agent:s,input:o,output:n.text,totalTokens:n.totalTokens,tokenUsage:g,durationMs:A,timestamp:Date.now()}),{output:k(n.text),messages:w,toolCalls:[],totalTokens:n.totalTokens,tokenUsage:g}}catch(r){let i=Date.now()-c;throw r instanceof Error&&u?.onError?.({agent:s,input:o,error:r,durationMs:i,timestamp:Date.now()}),r}}}
2
+ exports.a=x;exports.b=M;exports.c=O;exports.d=D;exports.e=L;//# sourceMappingURL=chunk-W6MVJKWN.cjs.map
3
+ //# sourceMappingURL=chunk-W6MVJKWN.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent-utils.ts"],"names":["isAgentRunning","state","hasPendingApprovals","estimateCost","tokenUsage","ratePerMillionTokens","ALLOWED_PROTOCOLS","validateBaseURL","baseURL","url","err","createRunner","options","fetchFn","buildRequest","parseResponse","parseOutput","hooks","parse","text","agent","input","runOptions","startTime","messages","init","fetchInit","response","errBody","parsed","assistantMessage","allMessages","durationMs"],"mappings":"aA0BO,SAASA,EAAeC,CAAAA,CAA4B,CACzD,OAAOA,CAAAA,CAAM,SAAW,SAC1B,CAQO,S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,MAAAG,CAAAA,CACA,KAAA,CAAAC,EACA,MAAA,CAAQQ,CAAAA,CAAO,IAAA,CACf,WAAA,CAAaA,EAAO,WAAA,CACpB,UAAA,CAAAzB,CAAAA,CACA,UAAA,CAAA4B,EACA,SAAA,CAAW,IAAA,CAAK,GAAA,EAClB,CAAC,CAAA,CAEM,CACL,OAAQd,CAAAA,CAASW,CAAAA,CAAO,IAAI,CAAA,CAC5B,QAAA,CAAUE,CAAAA,CACV,SAAA,CAAW,EAAC,CACZ,WAAA,CAAaF,CAAAA,CAAO,WAAA,CACpB,WAAAzB,CACF,CACF,CAAA,MAASM,CAAAA,CAAK,CACZ,IAAMsB,CAAAA,CAAa,KAAK,GAAA,EAAI,CAAIT,EAChC,MAAIb,CAAAA,YAAe,KAAA,EACjBO,CAAAA,EAAO,UAAU,CACf,KAAA,CAAAG,EACA,KAAA,CAAAC,CAAAA,CACA,MAAOX,CAAAA,CACP,UAAA,CAAAsB,CAAAA,CACA,SAAA,CAAW,KAAK,GAAA,EAClB,CAAC,CAAA,CAGGtB,CACR,CACF,CACF","file":"chunk-W6MVJKWN.cjs","sourcesContent":["/**\n * Agent utilities — createRunner, estimateCost, state queries, URL validation.\n */\n\nimport type {\n AdapterHooks,\n AgentLike,\n AgentRunner,\n AgentState,\n ApprovalState,\n Message,\n RunOptions,\n RunResult,\n TokenUsage,\n} from \"./types.js\";\n\n// ============================================================================\n// State Query Helpers\n// ============================================================================\n\n/**\n * Check whether an agent is currently executing a run.\n *\n * @param state - The current {@link AgentState} to inspect.\n * @returns `true` when the agent status is `\"running\"`.\n */\nexport function isAgentRunning(state: AgentState): boolean {\n return state.status === \"running\";\n}\n\n/**\n * Check whether there are tool-call approvals waiting for user confirmation.\n *\n * @param state - The current {@link ApprovalState} to inspect.\n * @returns `true` when one or more approvals are pending.\n */\nexport function hasPendingApprovals(state: ApprovalState): boolean {\n return state.pending.length > 0;\n}\n\n// ============================================================================\n// Cost Estimation\n// ============================================================================\n\n/**\n * Estimate the dollar cost of an agent run based on total token usage.\n *\n * @remarks\n * No default rate is provided — callers must supply the current per-million-token\n * price to avoid silently using stale pricing.\n *\n * @param tokenUsage - Total number of tokens consumed (input + output).\n * @param ratePerMillionTokens - Cost in dollars per one million tokens.\n * @returns Estimated cost in dollars.\n */\nexport function estimateCost(\n tokenUsage: number,\n ratePerMillionTokens: number,\n): number {\n return (tokenUsage / 1_000_000) * ratePerMillionTokens;\n}\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\nconst ALLOWED_PROTOCOLS = new Set([\"http:\", \"https:\"]);\n\n/**\n * Validate that a base URL uses the `http:` or `https:` protocol.\n * Throws immediately at adapter creation time (not at call time) to surface\n * configuration errors before any LLM requests are made.\n *\n * @param baseURL - The base URL string to validate.\n * @throws When the URL is malformed or uses a protocol other than `http:` or `https:`.\n */\nexport function validateBaseURL(baseURL: string): void {\n try {\n const url = new URL(baseURL);\n if (!ALLOWED_PROTOCOLS.has(url.protocol)) {\n throw new Error(\n `[Directive] Invalid baseURL protocol \"${url.protocol}\" – only http: and https: are allowed`,\n );\n }\n } catch (err) {\n if (err instanceof Error && err.message.startsWith(\"[Directive]\")) {\n throw err;\n }\n\n throw new Error(\n `[Directive] Invalid baseURL \"${baseURL}\" – must be a valid URL (e.g. \"https://api.openai.com/v1\")`,\n );\n }\n}\n\n// ============================================================================\n// createRunner Helper\n// ============================================================================\n\n/** Parsed response from an LLM provider */\nexport interface ParsedResponse {\n text: string;\n totalTokens: number;\n /** Input token count, when available from the provider */\n inputTokens?: number;\n /** Output token count, when available from the provider */\n outputTokens?: number;\n}\n\n/** Options for creating an AgentRunner from buildRequest/parseResponse */\nexport interface CreateRunnerOptions {\n fetch?: typeof globalThis.fetch;\n buildRequest: (\n agent: AgentLike,\n input: string,\n messages: Message[],\n ) => { url: string; init: RequestInit };\n parseResponse: (\n response: Response,\n messages: Message[],\n ) => Promise<ParsedResponse>;\n parseOutput?: <T>(text: string) => T;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n}\n\n/**\n * Create an {@link AgentRunner} from `buildRequest`/`parseResponse` helpers, reducing\n * ~50 lines of fetch boilerplate to ~20 lines of configuration.\n *\n * @remarks\n * Supports lifecycle hooks for observability:\n * - `onBeforeCall` fires before each API request\n * - `onAfterCall` fires after a successful response (includes token breakdown)\n * - `onError` fires when the request fails\n *\n * Output parsing defaults to `JSON.parse` with a string fallback. Supply a custom\n * `parseOutput` to override (e.g. for structured output schemas).\n *\n * @param options - Configuration for the runner, including request building, response parsing, and hooks.\n * @returns An {@link AgentRunner} function that performs LLM calls via fetch.\n *\n * @example\n * ```typescript\n * const runClaude = createRunner({\n * buildRequest: (agent, input) => ({\n * url: \"/api/claude\",\n * init: {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({\n * model: agent.model ?? \"claude-haiku-4-5-20251001\",\n * system: agent.instructions ?? \"\",\n * messages: [{ role: \"user\", content: input }],\n * }),\n * },\n * }),\n * parseResponse: async (res) => {\n * const data = await res.json();\n * const inputTokens = data.usage?.input_tokens ?? 0;\n * const outputTokens = data.usage?.output_tokens ?? 0;\n * return {\n * text: data.content?.[0]?.text ?? \"\",\n * totalTokens: inputTokens + outputTokens,\n * inputTokens,\n * outputTokens,\n * };\n * },\n * hooks: {\n * onAfterCall: ({ durationMs, tokenUsage }) => {\n * console.log(`LLM call: ${durationMs}ms, ${tokenUsage.inputTokens}in/${tokenUsage.outputTokens}out`);\n * },\n * },\n * });\n * ```\n *\n * @public\n */\nexport function createRunner(options: CreateRunnerOptions): AgentRunner {\n const {\n fetch: fetchFn = globalThis.fetch,\n buildRequest,\n parseResponse,\n parseOutput,\n hooks,\n } = options;\n\n const defaultParseOutput = <T>(text: string): T => {\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n };\n\n const parse = parseOutput ?? defaultParseOutput;\n\n return async <T = unknown>(\n agent: AgentLike,\n input: string,\n runOptions?: RunOptions,\n ): Promise<RunResult<T>> => {\n const startTime = Date.now();\n hooks?.onBeforeCall?.({ agent, input, timestamp: startTime });\n\n const messages: Message[] = [{ role: \"user\", content: input }];\n\n try {\n const { url, init } = buildRequest(agent, input, messages);\n\n const fetchInit: RequestInit = runOptions?.signal\n ? { ...init, signal: runOptions.signal }\n : init;\n\n const response = await fetchFn(url, fetchInit);\n\n if (!response.ok) {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] AgentRunner request failed: ${response.status} ${response.statusText}${errBody ? ` – ${errBody.slice(0, 300)}` : \"\"}`,\n );\n }\n\n const parsed = await parseResponse(response, messages);\n const tokenUsage: TokenUsage = {\n inputTokens: parsed.inputTokens ?? 0,\n outputTokens: parsed.outputTokens ?? 0,\n };\n\n const assistantMessage: Message = {\n role: \"assistant\",\n content: parsed.text,\n };\n const allMessages: Message[] = [...messages, assistantMessage];\n\n runOptions?.onMessage?.(assistantMessage);\n\n const durationMs = Date.now() - startTime;\n hooks?.onAfterCall?.({\n agent,\n input,\n output: parsed.text,\n totalTokens: parsed.totalTokens,\n tokenUsage,\n durationMs,\n timestamp: Date.now(),\n });\n\n return {\n output: parse<T>(parsed.text),\n messages: allMessages,\n toolCalls: [],\n totalTokens: parsed.totalTokens,\n tokenUsage,\n };\n } catch (err) {\n const durationMs = Date.now() - startTime;\n if (err instanceof Error) {\n hooks?.onError?.({\n agent,\n input,\n error: err,\n durationMs,\n timestamp: Date.now(),\n });\n }\n\n throw err;\n }\n };\n}\n"]}
@@ -0,0 +1,3 @@
1
+ function x(e){return e.status==="running"}function M(e){return e.pending.length>0}function O(e,t){return e/1e6*t}var b=new Set(["http:","https:"]);function D(e){try{let t=new URL(e);if(!b.has(t.protocol))throw new Error(`[Directive] Invalid baseURL protocol "${t.protocol}" \u2013 only http: and https: are allowed`)}catch(t){throw t instanceof Error&&t.message.startsWith("[Directive]")?t:new Error(`[Directive] Invalid baseURL "${e}" \u2013 must be a valid URL (e.g. "https://api.openai.com/v1")`)}}function L(e){let{fetch:t=globalThis.fetch,buildRequest:T,parseResponse:f,parseOutput:m,hooks:u}=e,k=m??(s=>{try{return JSON.parse(s)}catch{return s}});return async(s,o,p)=>{let c=Date.now();u?.onBeforeCall?.({agent:s,input:o,timestamp:c});let l=[{role:"user",content:o}];try{let{url:r,init:i}=T(s,o,l),d=p?.signal?{...i,signal:p.signal}:i,a=await t(r,d);if(!a.ok){let R=await a.text().catch(()=>"");throw new Error(`[Directive] AgentRunner request failed: ${a.status} ${a.statusText}${R?` \u2013 ${R.slice(0,300)}`:""}`)}let n=await f(a,l),g={inputTokens:n.inputTokens??0,outputTokens:n.outputTokens??0},h={role:"assistant",content:n.text},w=[...l,h];p?.onMessage?.(h);let A=Date.now()-c;return u?.onAfterCall?.({agent:s,input:o,output:n.text,totalTokens:n.totalTokens,tokenUsage:g,durationMs:A,timestamp:Date.now()}),{output:k(n.text),messages:w,toolCalls:[],totalTokens:n.totalTokens,tokenUsage:g}}catch(r){let i=Date.now()-c;throw r instanceof Error&&u?.onError?.({agent:s,input:o,error:r,durationMs:i,timestamp:Date.now()}),r}}}
2
+ export{x as a,M as b,O as c,D as d,L as e};//# sourceMappingURL=chunk-W6WZBQER.js.map
3
+ //# sourceMappingURL=chunk-W6WZBQER.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent-utils.ts"],"names":["isAgentRunning","state","hasPendingApprovals","estimateCost","tokenUsage","ratePerMillionTokens","ALLOWED_PROTOCOLS","validateBaseURL","baseURL","url","err","createRunner","options","fetchFn","buildRequest","parseResponse","parseOutput","hooks","parse","text","agent","input","runOptions","startTime","messages","init","fetchInit","response","errBody","parsed","assistantMessage","allMessages","durationMs"],"mappings":"AA0BO,SAASA,EAAeC,CAAAA,CAA4B,CACzD,OAAOA,CAAAA,CAAM,SAAW,SAC1B,CAQO,SAASC,CAAAA,CAAoBD,EAA+B,CACjE,OAAOA,EAAM,OAAA,CAAQ,MAAA,CAAS,CAChC,CAiBO,SAASE,CAAAA,CACdC,CAAAA,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A,CAAAzB,CAAAA,CACA,UAAA,CAAA4B,EACA,SAAA,CAAW,IAAA,CAAK,GAAA,EAClB,CAAC,CAAA,CAEM,CACL,OAAQd,CAAAA,CAASW,CAAAA,CAAO,IAAI,CAAA,CAC5B,QAAA,CAAUE,CAAAA,CACV,SAAA,CAAW,EAAC,CACZ,WAAA,CAAaF,CAAAA,CAAO,WAAA,CACpB,WAAAzB,CACF,CACF,CAAA,MAASM,CAAAA,CAAK,CACZ,IAAMsB,CAAAA,CAAa,KAAK,GAAA,EAAI,CAAIT,EAChC,MAAIb,CAAAA,YAAe,KAAA,EACjBO,CAAAA,EAAO,UAAU,CACf,KAAA,CAAAG,EACA,KAAA,CAAAC,CAAAA,CACA,MAAOX,CAAAA,CACP,UAAA,CAAAsB,CAAAA,CACA,SAAA,CAAW,KAAK,GAAA,EAClB,CAAC,CAAA,CAGGtB,CACR,CACF,CACF","file":"chunk-W6WZBQER.js","sourcesContent":["/**\n * Agent utilities — createRunner, estimateCost, state queries, URL validation.\n */\n\nimport type {\n AdapterHooks,\n AgentLike,\n AgentRunner,\n AgentState,\n ApprovalState,\n Message,\n RunOptions,\n RunResult,\n TokenUsage,\n} from \"./types.js\";\n\n// ============================================================================\n// State Query Helpers\n// ============================================================================\n\n/**\n * Check whether an agent is currently executing a run.\n *\n * @param state - The current {@link AgentState} to inspect.\n * @returns `true` when the agent status is `\"running\"`.\n */\nexport function isAgentRunning(state: AgentState): boolean {\n return state.status === \"running\";\n}\n\n/**\n * Check whether there are tool-call approvals waiting for user confirmation.\n *\n * @param state - The current {@link ApprovalState} to inspect.\n * @returns `true` when one or more approvals are pending.\n */\nexport function hasPendingApprovals(state: ApprovalState): boolean {\n return state.pending.length > 0;\n}\n\n// ============================================================================\n// Cost Estimation\n// ============================================================================\n\n/**\n * Estimate the dollar cost of an agent run based on total token usage.\n *\n * @remarks\n * No default rate is provided — callers must supply the current per-million-token\n * price to avoid silently using stale pricing.\n *\n * @param tokenUsage - Total number of tokens consumed (input + output).\n * @param ratePerMillionTokens - Cost in dollars per one million tokens.\n * @returns Estimated cost in dollars.\n */\nexport function estimateCost(\n tokenUsage: number,\n ratePerMillionTokens: number,\n): number {\n return (tokenUsage / 1_000_000) * ratePerMillionTokens;\n}\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\nconst ALLOWED_PROTOCOLS = new Set([\"http:\", \"https:\"]);\n\n/**\n * Validate that a base URL uses the `http:` or `https:` protocol.\n * Throws immediately at adapter creation time (not at call time) to surface\n * configuration errors before any LLM requests are made.\n *\n * @param baseURL - The base URL string to validate.\n * @throws When the URL is malformed or uses a protocol other than `http:` or `https:`.\n */\nexport function validateBaseURL(baseURL: string): void {\n try {\n const url = new URL(baseURL);\n if (!ALLOWED_PROTOCOLS.has(url.protocol)) {\n throw new Error(\n `[Directive] Invalid baseURL protocol \"${url.protocol}\" – only http: and https: are allowed`,\n );\n }\n } catch (err) {\n if (err instanceof Error && err.message.startsWith(\"[Directive]\")) {\n throw err;\n }\n\n throw new Error(\n `[Directive] Invalid baseURL \"${baseURL}\" – must be a valid URL (e.g. \"https://api.openai.com/v1\")`,\n );\n }\n}\n\n// ============================================================================\n// createRunner Helper\n// ============================================================================\n\n/** Parsed response from an LLM provider */\nexport interface ParsedResponse {\n text: string;\n totalTokens: number;\n /** Input token count, when available from the provider */\n inputTokens?: number;\n /** Output token count, when available from the provider */\n outputTokens?: number;\n}\n\n/** Options for creating an AgentRunner from buildRequest/parseResponse */\nexport interface CreateRunnerOptions {\n fetch?: typeof globalThis.fetch;\n buildRequest: (\n agent: AgentLike,\n input: string,\n messages: Message[],\n ) => { url: string; init: RequestInit };\n parseResponse: (\n response: Response,\n messages: Message[],\n ) => Promise<ParsedResponse>;\n parseOutput?: <T>(text: string) => T;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n}\n\n/**\n * Create an {@link AgentRunner} from `buildRequest`/`parseResponse` helpers, reducing\n * ~50 lines of fetch boilerplate to ~20 lines of configuration.\n *\n * @remarks\n * Supports lifecycle hooks for observability:\n * - `onBeforeCall` fires before each API request\n * - `onAfterCall` fires after a successful response (includes token breakdown)\n * - `onError` fires when the request fails\n *\n * Output parsing defaults to `JSON.parse` with a string fallback. Supply a custom\n * `parseOutput` to override (e.g. for structured output schemas).\n *\n * @param options - Configuration for the runner, including request building, response parsing, and hooks.\n * @returns An {@link AgentRunner} function that performs LLM calls via fetch.\n *\n * @example\n * ```typescript\n * const runClaude = createRunner({\n * buildRequest: (agent, input) => ({\n * url: \"/api/claude\",\n * init: {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({\n * model: agent.model ?? \"claude-haiku-4-5-20251001\",\n * system: agent.instructions ?? \"\",\n * messages: [{ role: \"user\", content: input }],\n * }),\n * },\n * }),\n * parseResponse: async (res) => {\n * const data = await res.json();\n * const inputTokens = data.usage?.input_tokens ?? 0;\n * const outputTokens = data.usage?.output_tokens ?? 0;\n * return {\n * text: data.content?.[0]?.text ?? \"\",\n * totalTokens: inputTokens + outputTokens,\n * inputTokens,\n * outputTokens,\n * };\n * },\n * hooks: {\n * onAfterCall: ({ durationMs, tokenUsage }) => {\n * console.log(`LLM call: ${durationMs}ms, ${tokenUsage.inputTokens}in/${tokenUsage.outputTokens}out`);\n * },\n * },\n * });\n * ```\n *\n * @public\n */\nexport function createRunner(options: CreateRunnerOptions): AgentRunner {\n const {\n fetch: fetchFn = globalThis.fetch,\n buildRequest,\n parseResponse,\n parseOutput,\n hooks,\n } = options;\n\n const defaultParseOutput = <T>(text: string): T => {\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n };\n\n const parse = parseOutput ?? defaultParseOutput;\n\n return async <T = unknown>(\n agent: AgentLike,\n input: string,\n runOptions?: RunOptions,\n ): Promise<RunResult<T>> => {\n const startTime = Date.now();\n hooks?.onBeforeCall?.({ agent, input, timestamp: startTime });\n\n const messages: Message[] = [{ role: \"user\", content: input }];\n\n try {\n const { url, init } = buildRequest(agent, input, messages);\n\n const fetchInit: RequestInit = runOptions?.signal\n ? { ...init, signal: runOptions.signal }\n : init;\n\n const response = await fetchFn(url, fetchInit);\n\n if (!response.ok) {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] AgentRunner request failed: ${response.status} ${response.statusText}${errBody ? ` – ${errBody.slice(0, 300)}` : \"\"}`,\n );\n }\n\n const parsed = await parseResponse(response, messages);\n const tokenUsage: TokenUsage = {\n inputTokens: parsed.inputTokens ?? 0,\n outputTokens: parsed.outputTokens ?? 0,\n };\n\n const assistantMessage: Message = {\n role: \"assistant\",\n content: parsed.text,\n };\n const allMessages: Message[] = [...messages, assistantMessage];\n\n runOptions?.onMessage?.(assistantMessage);\n\n const durationMs = Date.now() - startTime;\n hooks?.onAfterCall?.({\n agent,\n input,\n output: parsed.text,\n totalTokens: parsed.totalTokens,\n tokenUsage,\n durationMs,\n timestamp: Date.now(),\n });\n\n return {\n output: parse<T>(parsed.text),\n messages: allMessages,\n toolCalls: [],\n totalTokens: parsed.totalTokens,\n tokenUsage,\n };\n } catch (err) {\n const durationMs = Date.now() - startTime;\n if (err instanceof Error) {\n hooks?.onError?.({\n agent,\n input,\n error: err,\n durationMs,\n timestamp: Date.now(),\n });\n }\n\n throw err;\n }\n };\n}\n"]}
@@ -0,0 +1,14 @@
1
+ 'use strict';var chunkB4ATEGA2_cjs=require('./chunk-B4ATEGA2.cjs'),core=require('@directive-run/core'),adapterUtils=require('@directive-run/core/adapter-utils');var Le=500,qe=200;function kt(Ue){let{runner:V,factsSchema:ge={},init:me,constraints:je={},resolvers:He={},guardrails:P={},onApprovalRequest:re,autoApproveToolCalls:ne=true,maxTokenBudget:H,budgetWarningThreshold:J=.8,onBudgetWarning:fe,plugins:We=[],debug:he=false,approvalTimeoutMs:ae=3e5,agentRetry:z,hooks:ke={},memory:_,circuitBreaker:oe,selfHealing:T,outputSchema:Xe,maxSchemaRetries:Ke,checkpointStore:ve,breakpoints:S,onBreakpoint:Ye,breakpointTimeoutMs:Ve}=Ue,C=typeof he=="object"?true:!!he,se=5e3;if(C&&T&&!oe&&console.warn("[Directive] selfHealing config has no effect without a circuitBreaker \u2014 fallback behavior requires the circuit breaker to detect failures."),J<0||J>1)throw new Error(`[Directive Orchestrator] budgetWarningThreshold must be between 0 and 1, got ${J}`);if(!ne&&!re)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 $(e,r){try{ke[e]?.(r);}catch(o){C&&console.debug(`[Directive] hooks.${e} threw:`,o);}}let be=["agent","approval","conversation","toolCalls"];for(let e of Object.keys(ge))if(be.includes(e))throw new Error(`[Directive] Facts schema key "${e}" conflicts with orchestrator state. Reserved keys: ${be.join(", ")}. Rename your fact to avoid the collision.`);let Je={facts:{...chunkB4ATEGA2_cjs.f.facts,...ge,__budgetWarningFired:core.t.boolean()},derivations:{},events:{},requirements:{}},ye,t,Te=chunkB4ATEGA2_cjs.w(je);H&&(Te.__budgetLimit={priority:100,when:e=>chunkB4ATEGA2_cjs.l(e).tokenUsage>H,require:{type:"__PAUSE_BUDGET_EXCEEDED"}});let we=chunkB4ATEGA2_cjs.x(He,(e,r,o,a)=>ye(e,r,o,a),()=>t.facts);we.__pause={requirement:adapterUtils.requirementGuard("__PAUSE_BUDGET_EXCEEDED"),resolve:async(e,r)=>{let o=chunkB4ATEGA2_cjs.l(r.facts);chunkB4ATEGA2_cjs.m(r.facts,{...o,status:"paused"});}};let f=null;C&&(f=chunkB4ATEGA2_cjs.g({getSnapshotId:()=>{try{return t.history?.currentIndex??null}catch{return null}},goToSnapshot:e=>{try{t.history?.goTo?.(e);}catch{}}}));let ze=adapterUtils.createCallbackPlugin("directive-ai-callbacks",{}),Qe=core.createModule("directive-ai-orchestrator",{schema:Je,init:e=>{if(chunkB4ATEGA2_cjs.m(e,{status:"idle",currentAgent:null,input:null,output:null,error:null,tokenUsage:0,turnCount:0,startedAt:null,completedAt:null}),chunkB4ATEGA2_cjs.o(e,{pending:[],approved:[],rejected:[]}),chunkB4ATEGA2_cjs.q(e,[]),chunkB4ATEGA2_cjs.s(e,[]),chunkB4ATEGA2_cjs.u(e,{pending:[],resolved:[],cancelled:[]}),adapterUtils.setBridgeFact(e,"__budgetWarningFired",false),me){let r=chunkB4ATEGA2_cjs.v(e),o={...e,...r};me(o);}},constraints:Te,resolvers:we}),Re=[...We,ze];C&&f&&Re.push(chunkB4ATEGA2_cjs.h(f,()=>{try{return t.history?.currentIndex??null}catch{return null}})),t=core.createSystem({module:Qe,plugins:Re,history:C?true:void 0}),t.start();async function Ae(e,r,o,a,i){if(oe)try{return await oe.execute(()=>Se(e,r,o,a,i))}catch(u){if(T){if(T.fallbackRunners)for(let g of T.fallbackRunners)try{let b={originalAgent:e.name,reroutedTo:"fallback-runner",reason:u instanceof Error?u.message:String(u),timestamp:Date.now()};try{T.onReroute?.(b);}catch{}return f&&f.record({type:"reroute",timestamp:Date.now(),agentId:e.name,snapshotId:null,from:e.name,to:"fallback-runner",reason:u instanceof Error?u.message:String(u)}),await g(e,r,a)}catch{}if(T.fallbackAgent)try{let g={originalAgent:e.name,reroutedTo:T.fallbackAgent.name,reason:u instanceof Error?u.message:String(u),timestamp:Date.now()};try{T.onReroute?.(g);}catch{}return f&&f.record({type:"reroute",timestamp:Date.now(),agentId:e.name,snapshotId:null,from:e.name,to:T.fallbackAgent.name,reason:u instanceof Error?u.message:String(u)}),await V(T.fallbackAgent,r,a)}catch{}if(T.degradation==="fallback-response"&&T.fallbackResponse!==void 0)return {output:T.fallbackResponse,messages:[],toolCalls:[],totalTokens:0}}throw u}return Se(e,r,o,a,i)}async function Se(e,r,o,a,i){let u=Date.now();if(_){let n=_.getContextMessages();if(n.length>0){let c=n.map(v=>`${v.role}: ${v.content}`).join(`
4
+ `);e={...e,instructions:(e.instructions??"")+`
5
+
6
+ Conversation context:
7
+ `+c};}}if(S&&S.length>0){let n={agentId:e.name,agentName:e.name,input:r,state:t.facts.$store.toObject(),breakpointType:"pre_input_guardrails"},c=await Q("pre_input_guardrails",n,i?.signal??a?.signal);if(c?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};c?.input&&(r=c.input);}let g=i?.inputGuardrails!==void 0?i.inputGuardrails:P.input??[],b=i?.outputGuardrails!==void 0?i.outputGuardrails:P.output??[],D=g.map((n,c)=>chunkB4ATEGA2_cjs.i(n,c,"input"));for(let n of D){let{name:c}=n,v={agentName:e.name,input:r,facts:t.facts.$store.toObject()},d=Date.now(),p=await chunkB4ATEGA2_cjs.j(n,{input:r,agentName:e.name},v);if($("onGuardrailCheck",{agentId:e.name,guardrailName:c,guardrailType:"input",passed:p.passed,reason:p.reason,durationMs:Date.now()-d,timestamp:Date.now()}),!p.passed)throw new chunkB4ATEGA2_cjs.a({code:"INPUT_GUARDRAIL_FAILED",message:`Input guardrail "${c}" failed: ${p.reason}`,guardrailName:c,guardrailType:"input",userMessage:p.reason??"Input validation failed",agentName:e.name,input:r});p.transformed!==void 0&&(r=p.transformed);}if($("onAgentStart",{agentName:e.name,input:r,timestamp:u}),f&&f.record({type:"agent_start",timestamp:Date.now(),agentId:e.name,snapshotId:null,inputLength:r.length,modelId:e.model??void 0,...e.instructions?{instructions:e.instructions.slice(0,se)}:{},input:r.slice(0,se)}),t.batch(()=>{let n=chunkB4ATEGA2_cjs.l(t.facts);chunkB4ATEGA2_cjs.m(t.facts,{...n,status:"running",currentAgent:e.name,input:r,startedAt:Date.now()});}),S&&S.length>0){let n={agentId:e.name,agentName:e.name,input:r,state:t.facts.$store.toObject(),breakpointType:"pre_agent_run"},c=await Q("pre_agent_run",n,i?.signal??a?.signal);if(c?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};c?.input&&(r=c.input);}let w=i?.outputSchema!==void 0?i.outputSchema:Xe,A=V;w&&(A=chunkB4ATEGA2_cjs.G(V,{schema:w,maxRetries:i?.maxSchemaRetries??Ke??2}));let l=await chunkB4ATEGA2_cjs.k(A,e,r,{...a,signal:a?.signal,onMessage:n=>{let v=[...chunkB4ATEGA2_cjs.p(t.facts),n];chunkB4ATEGA2_cjs.q(t.facts,v.length>Le?v.slice(-Le):v),a?.onMessage?.(n);},onToolCall:async n=>{let c=(P.toolCall??[]).map((p,h)=>chunkB4ATEGA2_cjs.i(p,h,"toolCall"));for(let p of c){let{name:h}=p,L={agentName:e.name,input:r,facts:t.facts.$store.toObject()},ie=Date.now(),s=await chunkB4ATEGA2_cjs.j(p,{toolCall:n,agentName:e.name,input:r},L);if($("onGuardrailCheck",{agentId:e.name,guardrailName:h,guardrailType:"toolCall",passed:s.passed,reason:s.reason,durationMs:Date.now()-ie,timestamp:Date.now()}),!s.passed)throw new chunkB4ATEGA2_cjs.a({code:"TOOL_CALL_GUARDRAIL_FAILED",message:`Tool call guardrail "${h}" failed: ${s.reason}`,guardrailName:h,guardrailType:"toolCall",userMessage:s.reason??"Tool call blocked",data:{toolCall:n},agentName:e.name,input:r})}if(!ne){let p=`tool-${n.id}`,h={id:p,type:"tool_call",agentName:e.name,description:`Tool call: ${n.name}`,data:n,requestedAt:Date.now()};t.batch(()=>{let L=chunkB4ATEGA2_cjs.n(t.facts);chunkB4ATEGA2_cjs.o(t.facts,{...L,pending:[...L.pending,h]});}),re?.(h),await Ce(p,i?.signal??a?.signal);}let d=[...chunkB4ATEGA2_cjs.r(t.facts),n];chunkB4ATEGA2_cjs.s(t.facts,d.length>qe?d.slice(-qe):d),a?.onToolCall?.(n);}},z?{...z,onRetry:(n,c,v)=>{z.onRetry?.(n,c,v),$("onAgentRetry",{agentName:e.name,input:r,attempt:n,error:c,delayMs:v,timestamp:Date.now()});}}:void 0);if(S&&S.length>0){let n={agentId:e.name,agentName:e.name,input:r,state:t.facts.$store.toObject(),breakpointType:"pre_output_guardrails"},c=await Q("pre_output_guardrails",n,i?.signal??a?.signal);if(c?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};c?.input&&(r=c.input);}let F=b.map((n,c)=>chunkB4ATEGA2_cjs.i(n,c,"output"));for(let n of F){let{name:c}=n,v={agentName:e.name,input:r,facts:t.facts.$store.toObject()},d=Date.now(),p=await chunkB4ATEGA2_cjs.j(n,{output:l.output,agentName:e.name,input:r,messages:l.messages},v);if($("onGuardrailCheck",{agentId:e.name,guardrailName:c,guardrailType:"output",passed:p.passed,reason:p.reason,durationMs:Date.now()-d,timestamp:Date.now()}),!p.passed)throw new chunkB4ATEGA2_cjs.a({code:"OUTPUT_GUARDRAIL_FAILED",message:`Output guardrail "${c}" failed: ${p.reason}`,guardrailName:c,guardrailType:"output",userMessage:p.reason??"Output validation failed",agentName:e.name,input:r});p.transformed!==void 0&&(l.output=p.transformed);}let Z=false,k=0;if(t.batch(()=>{let n=chunkB4ATEGA2_cjs.l(t.facts),c=n.tokenUsage+l.totalTokens;if(chunkB4ATEGA2_cjs.m(t.facts,{...n,status:"completed",output:l.output,tokenUsage:c,turnCount:n.turnCount+l.messages.length,completedAt:Date.now()}),H&&fe){k=c/H;let v=adapterUtils.getBridgeFact(t.facts,"__budgetWarningFired");k>=J&&!v&&(adapterUtils.setBridgeFact(t.facts,"__budgetWarningFired",true),Z=true);}}),Z)try{fe({currentTokens:chunkB4ATEGA2_cjs.l(t.facts).tokenUsage,maxBudget:H,percentage:k});}catch(n){C&&console.debug("[Directive Orchestrator] onBudgetWarning threw:",n);}if(_&&l.messages.length>0)try{_.addMessages(l.messages);}catch(n){C&&console.debug("[Directive] Memory addMessages failed:",n);}if($("onAgentComplete",{agentName:e.name,input:r,output:l.output,tokenUsage:l.totalTokens,durationMs:Date.now()-u,timestamp:Date.now()}),f){let n=typeof l.output=="string"?l.output:JSON.stringify(l.output);f.record({type:"agent_complete",timestamp:Date.now(),agentId:e.name,snapshotId:null,outputLength:n?.length??0,totalTokens:l.totalTokens,inputTokens:l.tokenUsage?.inputTokens??0,outputTokens:l.tokenUsage?.outputTokens??0,durationMs:Date.now()-u,modelId:e.model??void 0,output:n.slice(0,se)});}if(S&&S.length>0){let n={agentId:e.name,agentName:e.name,input:r,state:t.facts.$store.toObject(),breakpointType:"post_run"},c=await Q("post_run",n,i?.signal??a?.signal);if(c?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};c?.input&&(r=c.input);}return l}ye=Ae;let G=new Map,W=new Map;function Ze(e,r){return r?.aborted?Promise.reject(r.reason??new Error("Aborted while waiting for breakpoint")):new Promise((o,a)=>{let i=false,u=null,g=()=>{i||(i=true,u&&(clearTimeout(u),u=null),r&&r.removeEventListener("abort",b),D());},b=()=>{g(),a(r.reason??new Error(`Breakpoint wait for ${e} aborted`));};r&&r.addEventListener("abort",b,{once:true});let D=t.facts.$store.subscribe([chunkB4ATEGA2_cjs.e],()=>{if(i)return;let A=chunkB4ATEGA2_cjs.t(t.facts);if(A.resolved.includes(e)){g();let l=G.get(e)??null;G.delete(e),o(l);}else if(A.cancelled.includes(e)){g(),G.delete(e);let l=W.get(e);W.delete(e),a(new Error(l?`Breakpoint ${e} was cancelled: ${l}`:`Breakpoint ${e} was cancelled`));}}),w=Ve??3e5;u=setTimeout(()=>{i||(g(),G.delete(e),W.delete(e),a(new Error(`[Directive] Breakpoint timeout: ${e} not resolved within ${Math.round(w/1e3)}s`)));},w);})}async function Q(e,r,o){if(!S||S.length===0)return null;let a=chunkB4ATEGA2_cjs.A(S,e,r);if(!a)return null;let i=chunkB4ATEGA2_cjs.z(),u={id:i,type:e,agentId:r.agentId,input:r.input,label:a.label,requestedAt:Date.now()};t.batch(()=>{let b=chunkB4ATEGA2_cjs.t(t.facts);chunkB4ATEGA2_cjs.u(t.facts,{...b,pending:[...b.pending,u]});});try{Ye?.(u);}catch{}try{ke.onBreakpoint?.(u);}catch{}f&&f.record({type:"breakpoint_hit",timestamp:Date.now(),snapshotId:null,agentId:r.agentId,breakpointId:i,breakpointType:e,label:a.label});let g=await Ze(i,o);return f&&f.record({type:"breakpoint_resumed",timestamp:Date.now(),snapshotId:null,agentId:r.agentId,breakpointId:i,modified:!!g?.input,skipped:!!g?.skip}),g}function Ce(e,r){return r?.aborted?Promise.reject(r.reason??new Error("Aborted while waiting for approval")):new Promise((o,a)=>{let i=false,u=null,g=()=>{i||(i=true,u&&(clearTimeout(u),u=null),r&&r.removeEventListener("abort",b),D());},b=()=>{g(),a(r.reason??new Error(`Approval wait for ${e} aborted`));};r&&r.addEventListener("abort",b,{once:true});let D=t.facts.$store.subscribe([chunkB4ATEGA2_cjs.d],()=>{if(i)return;let w=chunkB4ATEGA2_cjs.n(t.facts);if(w.approved.includes(e))g(),o();else {let A=w.rejected.find(l=>l.id===e);if(A){g();let l=A.reason?`Request ${e} rejected: ${A.reason}`:`Request ${e} rejected`;a(new Error(l));}}});u=setTimeout(()=>{if(i)return;g();let w=Math.round(ae/1e3);a(new Error(`[Directive] Approval timeout: Request ${e} not resolved within ${w}s.
8
+ Solutions:
9
+ 1. Handle via onApprovalRequest callback and call orchestrator.approve()/reject()
10
+ 2. Set autoApproveToolCalls: true to auto-approve
11
+ 3. Increase approvalTimeoutMs (current: ${ae}ms)
12
+ See: https://directive.run/docs/ai/running-agents`));},ae);})}function Ee(){return {...chunkB4ATEGA2_cjs.v(t.facts)}}return {system:t,get facts(){return Ee()},get totalTokens(){return chunkB4ATEGA2_cjs.l(t.facts).tokenUsage},get timeline(){return f},async run(e,r,o){return Ae(e,r,Ee(),void 0,o)},runStream(e,r,o={}){let a=new AbortController,i=1e4,u=[],g=[],b=false,D=Date.now(),w=0,A=1e5,l="",F;o.signal&&(F=()=>a.abort(),o.signal.addEventListener("abort",F,{once:true}));let Z=()=>{F&&o.signal&&o.signal.removeEventListener("abort",F);},k=d=>{if(b)return;let p=g.shift();p?p(d):(u.push(d),u.length>i&&u.shift());},n=()=>{b=true,Z();for(let d of g)d(null);g.length=0;},c=(async()=>{k({type:"progress",phase:"starting",message:"Running input guardrails"});try{let d=r,p=(P.input??[]).map((s,y)=>chunkB4ATEGA2_cjs.i(s,y,"input"));for(let s of p){let{name:y}=s,B={agentName:e.name,input:d,facts:t.facts.$store.toObject()},m=await chunkB4ATEGA2_cjs.j(s,{input:d,agentName:e.name},B);if(!m.passed)throw k({type:"guardrail_triggered",guardrailName:y,reason:m.reason??"Input validation failed",partialOutput:l,stopped:!0}),new chunkB4ATEGA2_cjs.a({code:"INPUT_GUARDRAIL_FAILED",message:`Input guardrail "${y}" failed: ${m.reason}`,guardrailName:y,guardrailType:"input",userMessage:m.reason??"Input validation failed",agentName:e.name,input:d});m.transformed!==void 0&&(d=m.transformed);}k({type:"progress",phase:"generating",message:"Starting agent"}),t.batch(()=>{let s=chunkB4ATEGA2_cjs.l(t.facts);chunkB4ATEGA2_cjs.m(t.facts,{...s,status:"running",currentAgent:e.name,input:d,startedAt:Date.now()});});let h=await chunkB4ATEGA2_cjs.k(V,e,d,{signal:a.signal,onMessage:s=>{let y=chunkB4ATEGA2_cjs.p(t.facts);if(chunkB4ATEGA2_cjs.q(t.facts,[...y,s]),k({type:"message",message:s}),s.role==="assistant"&&s.content){let B=Math.ceil(s.content.length/4);w+=B,l+=s.content,l.length>A&&(l=l.slice(-A)),k({type:"token",data:s.content,tokenCount:w});}},onToolCall:async s=>{k({type:"tool_start",tool:s.name,toolCallId:s.id,arguments:s.arguments});let y=(P.toolCall??[]).map((m,O)=>chunkB4ATEGA2_cjs.i(m,O,"toolCall"));for(let m of y){let{name:O}=m,ee={agentName:e.name,input:d,facts:t.facts.$store.toObject()},te=await chunkB4ATEGA2_cjs.j(m,{toolCall:s,agentName:e.name,input:d},ee);if(!te.passed)throw k({type:"guardrail_triggered",guardrailName:O,reason:te.reason??"Tool call blocked",partialOutput:l,stopped:!0}),new chunkB4ATEGA2_cjs.a({code:"TOOL_CALL_GUARDRAIL_FAILED",message:`Tool call guardrail "${O}" failed: ${te.reason}`,guardrailName:O,guardrailType:"toolCall",userMessage:te.reason??"Tool call blocked",data:{toolCall:s},agentName:e.name,input:d})}if(!ne){let m=`tool-${s.id}`;k({type:"approval_required",requestId:m,toolName:s.name});let O={id:m,type:"tool_call",agentName:e.name,description:`Tool call: ${s.name}`,data:s,requestedAt:Date.now()};t.batch(()=>{let ee=chunkB4ATEGA2_cjs.n(t.facts);chunkB4ATEGA2_cjs.o(t.facts,{...ee,pending:[...ee.pending,O]});}),re?.(O),await Ce(m,a.signal),k({type:"approval_resolved",requestId:m,approved:!0});}let B=chunkB4ATEGA2_cjs.r(t.facts);chunkB4ATEGA2_cjs.s(t.facts,[...B,s]),s.result&&k({type:"tool_end",tool:s.name,toolCallId:s.id,result:s.result});}},z);k({type:"progress",phase:"finishing",message:"Running output guardrails"});let L=(P.output??[]).map((s,y)=>chunkB4ATEGA2_cjs.i(s,y,"output"));for(let s of L){let{name:y}=s,B={agentName:e.name,input:d,facts:t.facts.$store.toObject()},m=await chunkB4ATEGA2_cjs.j(s,{output:h.output,agentName:e.name,input:d,messages:h.messages},B);if(!m.passed)throw k({type:"guardrail_triggered",guardrailName:y,reason:m.reason??"Output validation failed",partialOutput:typeof h.output=="string"?h.output:"",stopped:!0}),new chunkB4ATEGA2_cjs.a({code:"OUTPUT_GUARDRAIL_FAILED",message:`Output guardrail "${y}" failed: ${m.reason}`,guardrailName:y,guardrailType:"output",userMessage:m.reason??"Output validation failed",agentName:e.name,input:d});m.transformed!==void 0&&(h.output=m.transformed);}t.batch(()=>{let s=chunkB4ATEGA2_cjs.l(t.facts);chunkB4ATEGA2_cjs.m(t.facts,{...s,status:"completed",output:h.output,tokenUsage:s.tokenUsage+h.totalTokens,turnCount:s.turnCount+h.messages.length,completedAt:Date.now()});});let ie=Date.now()-D;return k({type:"done",totalTokens:h.totalTokens,duration:ie,droppedTokens:0}),n(),h}catch(d){throw k({type:"error",error:d instanceof Error?d:new Error(String(d))}),n(),d}})();return c.catch(()=>{}),{stream:{[Symbol.asyncIterator](){return {async next(){return u.length>0?{done:false,value:u.shift()}:b?{done:true,value:void 0}:new Promise(d=>{g.push(p=>{d(p===null?{done:true,value:void 0}:{done:false,value:p});});})}}}},result:c,abort:()=>{a.abort(),n();}}},async waitForIdle(e){let r=()=>chunkB4ATEGA2_cjs.l(t.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.batch(()=>{let r=chunkB4ATEGA2_cjs.n(t.facts);if(!r.pending.some(i=>i.id===e)){C&&console.debug(`[Directive] approve() ignored: no pending request "${e}"`);return}let o=200,a=[...r.approved,e];chunkB4ATEGA2_cjs.o(t.facts,{...r,pending:r.pending.filter(i=>i.id!==e),approved:a.length>o?a.slice(-o):a});});},reject(e,r){t.batch(()=>{let o=chunkB4ATEGA2_cjs.n(t.facts);if(!o.pending.some(g=>g.id===e)){C&&console.debug(`[Directive] reject() ignored: no pending request "${e}"`);return}r&&C&&console.debug(`[Directive] Request ${e} rejected: ${r}`);let a={id:e,reason:r,rejectedAt:Date.now()},i=200,u=[...o.rejected,a];chunkB4ATEGA2_cjs.o(t.facts,{...o,pending:o.pending.filter(g=>g.id!==e),rejected:u.length>i?u.slice(-i):u});});},pause(){let e=chunkB4ATEGA2_cjs.l(t.facts);chunkB4ATEGA2_cjs.m(t.facts,{...e,status:"paused"});},resume(){let e=chunkB4ATEGA2_cjs.l(t.facts);e.status==="paused"&&chunkB4ATEGA2_cjs.m(t.facts,{...e,status:e.currentAgent?"running":"idle"});},reset(){t.batch(()=>{chunkB4ATEGA2_cjs.m(t.facts,{status:"idle",currentAgent:null,input:null,output:null,error:null,tokenUsage:0,turnCount:0,startedAt:null,completedAt:null}),chunkB4ATEGA2_cjs.o(t.facts,{pending:[],approved:[],rejected:[]}),chunkB4ATEGA2_cjs.q(t.facts,[]),chunkB4ATEGA2_cjs.s(t.facts,[]),chunkB4ATEGA2_cjs.u(t.facts,{pending:[],resolved:[],cancelled:[]}),adapterUtils.setBridgeFact(t.facts,"__budgetWarningFired",false);}),G.clear(),W.clear();},async checkpoint(e){if(chunkB4ATEGA2_cjs.l(t.facts).status==="running")throw new Error("[Directive] Cannot checkpoint while agent is running");if(!t.history?.export)throw new Error("[Directive] Checkpointing requires history. Set `debug: true` in orchestrator options.");let o={version:1,id:chunkB4ATEGA2_cjs.C(),createdAt:new Date().toISOString(),label:e?.label,systemExport:t.history.export(),timelineExport:f?.export()??null,localState:{type:"single"},memoryExport:_?_.export?.()??null:null,orchestratorType:"single"};return ve&&await ve.save(o),o},restore(e,r){if(!chunkB4ATEGA2_cjs.D(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.history?.import)throw new Error("[Directive] Restoring a checkpoint requires history. Set `debug: true` in orchestrator options.");t.history.import(e.systemExport),r?.restoreTimeline!==false&&e.timelineExport&&f&&f.import(e.timelineExport),e.memoryExport!==null&&_&&_.import&&_.import(e.memoryExport);},resumeBreakpoint(e,r){r&&G.set(e,r),t.batch(()=>{let o=chunkB4ATEGA2_cjs.t(t.facts),a=[...o.resolved,e];chunkB4ATEGA2_cjs.u(t.facts,{...o,pending:o.pending.filter(i=>i.id!==e),resolved:a.length>chunkB4ATEGA2_cjs.y?a.slice(-chunkB4ATEGA2_cjs.y):a});});},cancelBreakpoint(e,r){r&&W.set(e,r),t.batch(()=>{let o=chunkB4ATEGA2_cjs.t(t.facts),a=[...o.cancelled,e];chunkB4ATEGA2_cjs.u(t.facts,{...o,pending:o.pending.filter(i=>i.id!==e),cancelled:a.length>chunkB4ATEGA2_cjs.y?a.slice(-chunkB4ATEGA2_cjs.y):a});});},getPendingBreakpoints(){return [...chunkB4ATEGA2_cjs.t(t.facts).pending]},destroy(){t.destroy();}}}
13
+ exports.a=kt;//# sourceMappingURL=chunk-WCJFIC22.cjs.map
14
+ //# sourceMappingURL=chunk-WCJFIC22.cjs.map