@directive-run/ai 1.21.0 → 1.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-IR3IHBVQ.cjs → chunk-7JTR4QBA.cjs} +2 -2
- package/dist/{chunk-IR3IHBVQ.cjs.map → chunk-7JTR4QBA.cjs.map} +1 -1
- package/dist/{chunk-G7CRWJT7.js → chunk-7KCLEIAG.js} +3 -3
- package/dist/chunk-7KCLEIAG.js.map +1 -0
- package/dist/{chunk-5JQ2A3JK.js → chunk-BZB3RDI2.js} +2 -2
- package/dist/{chunk-5JQ2A3JK.js.map → chunk-BZB3RDI2.js.map} +1 -1
- package/dist/{chunk-RHJAMXLS.js → chunk-CXWHLEBQ.js} +3 -3
- package/dist/{chunk-RHJAMXLS.js.map → chunk-CXWHLEBQ.js.map} +1 -1
- package/dist/{chunk-TH2D22JP.cjs → chunk-ESJQSOKJ.cjs} +7 -7
- package/dist/chunk-ESJQSOKJ.cjs.map +1 -0
- package/dist/{chunk-7EJN6TYX.cjs → chunk-GWWZXJOG.cjs} +3 -3
- package/dist/chunk-GWWZXJOG.cjs.map +1 -0
- package/dist/{chunk-QRDBUGPO.js → chunk-LOHC2KP5.js} +3 -3
- package/dist/chunk-LOHC2KP5.js.map +1 -0
- package/dist/{chunk-ZGJ2XHGI.cjs → chunk-MPMBFW2P.cjs} +2 -2
- package/dist/chunk-MPMBFW2P.cjs.map +1 -0
- package/dist/{chunk-XGHNOSXT.cjs → chunk-PEM2LPOC.cjs} +4 -4
- package/dist/{chunk-XGHNOSXT.cjs.map → chunk-PEM2LPOC.cjs.map} +1 -1
- package/dist/{chunk-VSVR4RFK.js → chunk-TEPEQE42.js} +2 -2
- package/dist/chunk-TEPEQE42.js.map +1 -0
- package/dist/devtools.cjs +1 -1
- package/dist/devtools.js +1 -1
- package/dist/guardrails.cjs +1 -1
- package/dist/guardrails.js +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.js +1 -1
- package/dist/{multi-agent-orchestrator-RMTLPKB4.js → multi-agent-orchestrator-FIF4GLVR.js} +2 -2
- package/dist/{multi-agent-orchestrator-RMTLPKB4.js.map → multi-agent-orchestrator-FIF4GLVR.js.map} +1 -1
- package/dist/multi-agent-orchestrator-PHDHFCW3.cjs +2 -0
- package/dist/{multi-agent-orchestrator-OX2TKD5Y.cjs.map → multi-agent-orchestrator-PHDHFCW3.cjs.map} +1 -1
- package/dist/multi-agent.cjs +1 -1
- package/dist/multi-agent.js +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-7EJN6TYX.cjs.map +0 -1
- package/dist/chunk-G7CRWJT7.js.map +0 -1
- package/dist/chunk-QRDBUGPO.js.map +0 -1
- package/dist/chunk-TH2D22JP.cjs.map +0 -1
- package/dist/chunk-VSVR4RFK.js.map +0 -1
- package/dist/chunk-ZGJ2XHGI.cjs.map +0 -1
- package/dist/multi-agent-orchestrator-OX2TKD5Y.cjs +0 -2
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkGWWZXJOG_cjs=require('./chunk-GWWZXJOG.cjs'),chunkK64WKZ22_cjs=require('./chunk-K64WKZ22.cjs'),chunkWOFIBIPW_cjs=require('./chunk-WOFIBIPW.cjs'),chunkWCQK3JOR_cjs=require('./chunk-WCQK3JOR.cjs'),core=require('@directive-run/core'),adapterUtils=require('@directive-run/core/adapter-utils');var Qe=500,Ze=200,et=false;function xt(ve){let{runner:ne,factsSchema:be={},init:we,constraints:tt={},resolvers:nt={},guardrails:q={},onApprovalRequest:le,autoApproveToolCalls:de=true,maxTokenBudget:I,budgetWarningThreshold:re=.8,onBudgetWarning:Te,budgetEstimateTokens:ae,retryInsideCircuit:Re=false,plugins:rt=[],debug:Ae=false,approvalTimeoutMs:pe=3e5,agentRetry:oe,hooks:Se={},memory:M,circuitBreaker:j,selfHealing:R,outputSchema:at,maxSchemaRetries:ot,checkpointStore:Ce,breakpoints:_,onBreakpoint:st,breakpointTimeoutMs:it}=ve,D=typeof Ae=="object"?true:!!Ae,ge=5e3;if(D&&R&&!j&&console.warn("[Directive] selfHealing config has no effect without a circuitBreaker \u2014 fallback behavior requires the circuit breaker to detect failures."),re<0||re>1)throw new Error(`[Directive Orchestrator] budgetWarningThreshold must be between 0 and 1, got ${re}`);if(!de&&!le)throw new Error(`[Directive] Invalid approval configuration: autoApproveToolCalls is false but no onApprovalRequest callback provided. Tool calls would wait for approval indefinitely. Either:
|
|
2
2
|
- Set autoApproveToolCalls: true to auto-approve all tool calls
|
|
3
|
-
- Provide an onApprovalRequest callback to handle approvals programmatically`);function W(e,t){try{Se[e]?.(t);}catch(a){D&&console.debug(`[Directive] hooks.${e} threw:`,a);}}let Oe=["agent","approval","conversation","toolCalls"];for(let e of Object.keys(be))if(Oe.includes(e))throw new Error(`[Directive] Facts schema key "${e}" conflicts with orchestrator state. Reserved keys: ${Oe.join(", ")}. Rename your fact to avoid the collision.`);let ut={facts:{...chunkK64WKZ22_cjs.i.facts,...be,__budgetWarningFired:core.t.boolean()},derivations:{},events:{},requirements:{}},Ee,n,_e=
|
|
3
|
+
- Provide an onApprovalRequest callback to handle approvals programmatically`);function W(e,t){try{Se[e]?.(t);}catch(a){D&&console.debug(`[Directive] hooks.${e} threw:`,a);}}let Oe=["agent","approval","conversation","toolCalls"];for(let e of Object.keys(be))if(Oe.includes(e))throw new Error(`[Directive] Facts schema key "${e}" conflicts with orchestrator state. Reserved keys: ${Oe.join(", ")}. Rename your fact to avoid the collision.`);let ut={facts:{...chunkK64WKZ22_cjs.i.facts,...be,__budgetWarningFired:core.t.boolean()},derivations:{},events:{},requirements:{}},Ee,n,_e=chunkGWWZXJOG_cjs.q(tt);I&&(_e.__budgetLimit={priority:100,when:e=>chunkGWWZXJOG_cjs.f(e).tokenUsage>I,require:{type:"__PAUSE_BUDGET_EXCEEDED"}});let De=chunkGWWZXJOG_cjs.r(nt,(e,t,a,r)=>Ee(e,t,a,r),()=>n.facts);De.__pause={requirement:adapterUtils.requirementGuard("__PAUSE_BUDGET_EXCEEDED"),resolve:async(e,t)=>{let a=chunkGWWZXJOG_cjs.f(t.facts);chunkGWWZXJOG_cjs.g(t.facts,{...a,status:"paused"});}};let y=null;D&&(y=chunkWOFIBIPW_cjs.a({getSnapshotId:()=>{try{return n.history?.currentIndex??null}catch{return null}},goToSnapshot:e=>{try{n.history?.goTo?.(e);}catch{}}}));let ct=adapterUtils.createCallbackPlugin("directive-ai-callbacks",{}),lt=core.createModule("directive-ai-orchestrator",{schema:ut,init:e=>{if(chunkGWWZXJOG_cjs.g(e,{status:"idle",currentAgent:null,input:null,output:null,error:null,tokenUsage:0,turnCount:0,startedAt:null,completedAt:null}),chunkGWWZXJOG_cjs.i(e,{pending:[],approved:[],rejected:[]}),chunkGWWZXJOG_cjs.k(e,[]),chunkGWWZXJOG_cjs.m(e,[]),chunkGWWZXJOG_cjs.o(e,{pending:[],resolved:[],cancelled:[]}),adapterUtils.setBridgeFact(e,"__budgetWarningFired",false),we){let t=chunkGWWZXJOG_cjs.p(e),a={...e,...t};we(a);}},constraints:_e,resolvers:De}),xe=[...rt,ct];D&&y&&xe.push(chunkWOFIBIPW_cjs.b(y,()=>{try{return n.history?.currentIndex??null}catch{return null}})),n=core.createSystem({module:lt,plugins:xe,history:D?true:void 0}),n.start();let $={count:0};function Be(e,t){if(ae===void 0)return 0;if(typeof ae=="number")return Math.max(0,Math.floor(ae));try{let a=ae(t,e);return Number.isFinite(a)?Math.max(0,Math.floor(a)):0}catch{return 0}}async function Ie(e,t,a,r,s){let c=0;if(I){let g=chunkGWWZXJOG_cjs.f(n.facts).tokenUsage;if(c=Be(e,t),g+$.count+c>I)throw new Error(`[Directive] Agent budget would be exceeded by this call: current=${g} + in-flight=${$.count} + estimate=${c} > maxTokenBudget=${I}. Raise \`maxTokenBudget\`, lower \`budgetEstimateTokens\`, or reset \`tokenUsage\`.`);$.count+=c;}try{return await dt(e,t,a,r,s)}finally{I&&c>0&&($.count=Math.max(0,$.count-c));}}async function Me(e,t,a){let r=Be(e,t);if(r<=0)return await a();$.count+=r;try{return await a()}finally{$.count=Math.max(0,$.count-r);}}async function $e(e,t,a,r){if(!R)throw e;if(R.fallbackRunners)for(let s of R.fallbackRunners)try{let c={originalAgent:t.name,reroutedTo:"fallback-runner",reason:e instanceof Error?e.message:String(e),timestamp:Date.now()};try{R.onReroute?.(c);}catch{}return y&&y.record({type:"reroute",timestamp:Date.now(),agentId:t.name,snapshotId:null,from:t.name,to:"fallback-runner",reason:e instanceof Error?e.message:String(e)}),await Me(t,a,()=>s(t,a,r))}catch{}if(R.fallbackAgent)try{let s={originalAgent:t.name,reroutedTo:R.fallbackAgent.name,reason:e instanceof Error?e.message:String(e),timestamp:Date.now()};try{R.onReroute?.(s);}catch{}y&&y.record({type:"reroute",timestamp:Date.now(),agentId:t.name,snapshotId:null,from:t.name,to:R.fallbackAgent.name,reason:e instanceof Error?e.message:String(e)});let c=R.fallbackAgent;return await Me(c,a,()=>ne(c,a,r))}catch{}if(R.degradation==="fallback-response"&&R.fallbackResponse!==void 0)return {output:R.fallbackResponse,messages:[],toolCalls:[],totalTokens:0};throw e}async function dt(e,t,a,r,s){if(j&&Re)try{return await j.execute(()=>Fe(e,t,a,r,s))}catch(c){return $e(c,e,t,r)}try{return await Fe(e,t,a,r,s)}catch(c){if(j||R)return $e(c,e,t,r);throw c}}async function Fe(e,t,a,r,s){let c=Date.now();if(M){let o=M.getContextMessages();if(o.length>0){let i=o.map(p=>`${p.role}: ${p.content}`).join(`
|
|
4
4
|
`);e={...e,instructions:`${e.instructions??""}
|
|
5
5
|
|
|
6
6
|
Conversation context:
|
|
7
|
-
${i}`};}}if(ve.metaContext){let o=
|
|
7
|
+
${i}`};}}if(ve.metaContext){let o=chunkGWWZXJOG_cjs.a(n.inspect());o&&(e={...e,instructions:`${e.instructions??""}
|
|
8
8
|
|
|
9
|
-
${o}`});}if(_&&_.length>0){let o={agentId:e.name,agentName:e.name,input:t,state:n.facts.$store.toObject(),breakpointType:"pre_input_guardrails"},i=await se("pre_input_guardrails",o,s?.signal??r?.signal);if(i?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};i?.input&&(t=i.input);}let g=s?.inputGuardrails!==void 0?s.inputGuardrails:q.input??[],b=s?.outputGuardrails!==void 0?s.outputGuardrails:q.output??[],F=g.map((o,i)=>
|
|
9
|
+
${o}`});}if(_&&_.length>0){let o={agentId:e.name,agentName:e.name,input:t,state:n.facts.$store.toObject(),breakpointType:"pre_input_guardrails"},i=await se("pre_input_guardrails",o,s?.signal??r?.signal);if(i?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};i?.input&&(t=i.input);}let g=s?.inputGuardrails!==void 0?s.inputGuardrails:q.input??[],b=s?.outputGuardrails!==void 0?s.outputGuardrails:q.output??[],F=g.map((o,i)=>chunkGWWZXJOG_cjs.c(o,i,"input"));for(let o of F){let{name:i}=o,p={agentName:e.name,input:t,facts:n.facts.$store.toObject()},O=Date.now(),m=await chunkGWWZXJOG_cjs.d(o,{input:t,agentName:e.name},p);if(W("onGuardrailCheck",{agentId:e.name,guardrailName:i,guardrailType:"input",passed:m.passed,reason:m.reason,durationMs:Date.now()-O,timestamp:Date.now()}),!m.passed)throw new chunkK64WKZ22_cjs.a({code:"INPUT_GUARDRAIL_FAILED",message:`Input guardrail "${i}" failed: ${m.reason}`,guardrailName:i,guardrailType:"input",userMessage:m.reason??"Input validation failed",agentName:e.name,input:t});m.transformed!==void 0&&(t=m.transformed);}if(W("onAgentStart",{agentName:e.name,input:t,timestamp:c}),y&&y.record({type:"agent_start",timestamp:Date.now(),agentId:e.name,snapshotId:null,inputLength:t.length,modelId:e.model??void 0,...e.instructions?{instructions:e.instructions.slice(0,ge)}:{},input:t.slice(0,ge)}),n.batch(()=>{let o=chunkGWWZXJOG_cjs.f(n.facts);chunkGWWZXJOG_cjs.g(n.facts,{...o,status:"running",currentAgent:e.name,input:t,startedAt:Date.now()});}),_&&_.length>0){let o={agentId:e.name,agentName:e.name,input:t,state:n.facts.$store.toObject(),breakpointType:"pre_agent_run"},i=await se("pre_agent_run",o,s?.signal??r?.signal);if(i?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};i?.input&&(t=i.input);}let C=s?.outputSchema!==void 0?s.outputSchema:at,A=ne;if(C&&(A=chunkWCQK3JOR_cjs.b(ne,{schema:C,maxRetries:s?.maxSchemaRetries??ot??2})),j&&!Re){let o=A;A=((i,p,O)=>j.execute(()=>o(i,p,O)));}let l=await chunkGWWZXJOG_cjs.e(A,e,t,{...r,signal:r?.signal,onMessage:o=>{let p=[...chunkGWWZXJOG_cjs.j(n.facts),o];chunkGWWZXJOG_cjs.k(n.facts,p.length>Qe?p.slice(-Qe):p),r?.onMessage?.(o);},onToolCall:async o=>{let i=(q.toolCall??[]).map((m,x)=>chunkGWWZXJOG_cjs.c(m,x,"toolCall"));for(let m of i){let{name:x}=m,L={agentName:e.name,input:t,facts:n.facts.$store.toObject()},d=Date.now(),w=await chunkGWWZXJOG_cjs.d(m,{toolCall:o,agentName:e.name,input:t},L);if(W("onGuardrailCheck",{agentId:e.name,guardrailName:x,guardrailType:"toolCall",passed:w.passed,reason:w.reason,durationMs:Date.now()-d,timestamp:Date.now()}),!w.passed)throw new chunkK64WKZ22_cjs.a({code:"TOOL_CALL_GUARDRAIL_FAILED",message:`Tool call guardrail "${x}" failed: ${w.reason}`,guardrailName:x,guardrailType:"toolCall",userMessage:w.reason??"Tool call blocked",data:{toolCall:o},agentName:e.name,input:t})}if(!de){let m=`tool-${o.id}`,x={id:m,type:"tool_call",agentName:e.name,description:`Tool call: ${o.name}`,data:o,requestedAt:Date.now()};n.batch(()=>{let L=chunkGWWZXJOG_cjs.h(n.facts);chunkGWWZXJOG_cjs.i(n.facts,{...L,pending:[...L.pending,x]});}),le?.(x),await Le(m,s?.signal??r?.signal);}let O=[...chunkGWWZXJOG_cjs.l(n.facts),o];chunkGWWZXJOG_cjs.m(n.facts,O.length>Ze?O.slice(-Ze):O),r?.onToolCall?.(o);}},oe?{...oe,onRetry:(o,i,p)=>{oe.onRetry?.(o,i,p),W("onAgentRetry",{agentName:e.name,input:t,attempt:o,error:i,delayMs:p,timestamp:Date.now()});}}:void 0);if(_&&_.length>0){let o={agentId:e.name,agentName:e.name,input:t,state:n.facts.$store.toObject(),breakpointType:"pre_output_guardrails"},i=await se("pre_output_guardrails",o,s?.signal??r?.signal);if(i?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};i?.input&&(t=i.input);}let K=b.map((o,i)=>chunkGWWZXJOG_cjs.c(o,i,"output"));for(let o of K){let{name:i}=o,p={agentName:e.name,input:t,facts:n.facts.$store.toObject()},O=Date.now(),m=await chunkGWWZXJOG_cjs.d(o,{output:l.output,agentName:e.name,input:t,messages:l.messages},p);if(W("onGuardrailCheck",{agentId:e.name,guardrailName:i,guardrailType:"output",passed:m.passed,reason:m.reason,durationMs:Date.now()-O,timestamp:Date.now()}),!m.passed)throw new chunkK64WKZ22_cjs.a({code:"OUTPUT_GUARDRAIL_FAILED",message:`Output guardrail "${i}" failed: ${m.reason}`,guardrailName:i,guardrailType:"output",userMessage:m.reason??"Output validation failed",agentName:e.name,input:t});m.transformed!==void 0&&(l.output=m.transformed);}let ie=false,h=0;if(n.batch(()=>{let o=chunkGWWZXJOG_cjs.f(n.facts),i=o.tokenUsage+l.totalTokens;if(chunkGWWZXJOG_cjs.g(n.facts,{...o,status:"completed",output:l.output,tokenUsage:i,turnCount:o.turnCount+l.messages.length,completedAt:Date.now()}),I&&Te){h=i/I;let p=adapterUtils.getBridgeFact(n.facts,"__budgetWarningFired");h>=re&&!p&&(adapterUtils.setBridgeFact(n.facts,"__budgetWarningFired",true),ie=true);}}),ie)try{Te({currentTokens:chunkGWWZXJOG_cjs.f(n.facts).tokenUsage,maxBudget:I,percentage:h});}catch(o){D&&console.debug("[Directive Orchestrator] onBudgetWarning threw:",o);}if(M&&l.messages.length>0)try{M.addMessages(l.messages);}catch(o){D&&console.debug("[Directive] Memory addMessages failed:",o);}if(W("onAgentComplete",{agentName:e.name,input:t,output:l.output,tokenUsage:l.totalTokens,durationMs:Date.now()-c,timestamp:Date.now()}),y){let o=typeof l.output=="string"?l.output:JSON.stringify(l.output);y.record({type:"agent_complete",timestamp:Date.now(),agentId:e.name,snapshotId:null,outputLength:o?.length??0,totalTokens:l.totalTokens,inputTokens:l.tokenUsage?.inputTokens??0,outputTokens:l.tokenUsage?.outputTokens??0,durationMs:Date.now()-c,modelId:e.model??void 0,output:o.slice(0,ge)});}if(_&&_.length>0){let o={agentId:e.name,agentName:e.name,input:t,state:n.facts.$store.toObject(),breakpointType:"post_run"},i=await se("post_run",o,s?.signal??r?.signal);if(i?.skip)return {output:void 0,messages:[],toolCalls:[],totalTokens:0};i?.input&&(t=i.input);}return l}Ee=Ie;let H=new Map,Q=new Map;function pt(e,t){return t?.aborted?Promise.reject(t.reason??new Error("Aborted while waiting for breakpoint")):new Promise((a,r)=>{let s=false,c=null,g=()=>{s||(s=true,c&&(clearTimeout(c),c=null),t&&t.removeEventListener("abort",b),F());},b=()=>{g(),r(t.reason??new Error(`Breakpoint wait for ${e} aborted`));};t&&t.addEventListener("abort",b,{once:true});let F=n.facts.$store.subscribe([chunkK64WKZ22_cjs.g],()=>{if(s)return;let A=chunkGWWZXJOG_cjs.n(n.facts);if(A.resolved.includes(e)){g();let l=H.get(e)??null;H.delete(e),a(l);}else if(A.cancelled.includes(e)){g(),H.delete(e);let l=Q.get(e);Q.delete(e),r(new Error(l?`Breakpoint ${e} was cancelled: ${l}`:`Breakpoint ${e} was cancelled`));}}),C=it??3e5;c=setTimeout(()=>{s||(g(),H.delete(e),Q.delete(e),r(new Error(`[Directive] Breakpoint timeout: ${e} not resolved within ${Math.round(C/1e3)}s`)));},C);})}async function se(e,t,a){if(!_||_.length===0)return null;let r=chunkGWWZXJOG_cjs.u(_,e,t);if(!r)return null;let s=chunkGWWZXJOG_cjs.t(),c={id:s,type:e,agentId:t.agentId,input:t.input,label:r.label,requestedAt:Date.now()};n.batch(()=>{let b=chunkGWWZXJOG_cjs.n(n.facts);chunkGWWZXJOG_cjs.o(n.facts,{...b,pending:[...b.pending,c]});});try{st?.(c);}catch{}try{Se.onBreakpoint?.(c);}catch{}y&&y.record({type:"breakpoint_hit",timestamp:Date.now(),snapshotId:null,agentId:t.agentId,breakpointId:s,breakpointType:e,label:r.label});let g=await pt(s,a);return y&&y.record({type:"breakpoint_resumed",timestamp:Date.now(),snapshotId:null,agentId:t.agentId,breakpointId:s,modified:!!g?.input,skipped:!!g?.skip}),g}function Le(e,t){return t?.aborted?Promise.reject(t.reason??new Error("Aborted while waiting for approval")):new Promise((a,r)=>{let s=false,c=null,g=()=>{s||(s=true,c&&(clearTimeout(c),c=null),t&&t.removeEventListener("abort",b),F());},b=()=>{g(),r(t.reason??new Error(`Approval wait for ${e} aborted`));};t&&t.addEventListener("abort",b,{once:true});let F=n.facts.$store.subscribe([chunkK64WKZ22_cjs.d],()=>{if(s)return;let C=chunkGWWZXJOG_cjs.h(n.facts);if(C.approved.includes(e))g(),a();else {let A=C.rejected.find(l=>l.id===e);if(A){g();let l=A.reason?`Request ${e} rejected: ${A.reason}`:`Request ${e} rejected`;r(new Error(l));}}});c=setTimeout(()=>{if(s)return;g();let C=Math.round(pe/1e3);r(new Error(`[Directive] Approval timeout: Request ${e} not resolved within ${C}s.
|
|
10
10
|
Solutions:
|
|
11
11
|
1. Handle via onApprovalRequest callback and call orchestrator.approve()/reject()
|
|
12
12
|
2. Set autoApproveToolCalls: true to auto-approve
|
|
13
13
|
3. Increase approvalTimeoutMs (current: ${pe}ms)
|
|
14
|
-
See: https://directive.run/docs/ai/running-agents`));},pe);})}function Pe(){return {...
|
|
15
|
-
exports.a=xt;//# sourceMappingURL=chunk-
|
|
16
|
-
//# sourceMappingURL=chunk-
|
|
14
|
+
See: https://directive.run/docs/ai/running-agents`));},pe);})}function Pe(){return {...chunkGWWZXJOG_cjs.p(n.facts)}}return {system:n,get facts(){return Pe()},get totalTokens(){return chunkGWWZXJOG_cjs.f(n.facts).tokenUsage},get timeline(){return y},async run(e,t,a){return Ie(e,t,Pe(),void 0,a)},runStream(e,t,a={}){let r=new AbortController,s=1e4,c=[],g=[],b=false,F=Date.now(),C=0,A=1e5,l="",K;a.signal&&(K=()=>r.abort(),a.signal.addEventListener("abort",K,{once:true}));let ie=()=>{K&&a.signal&&a.signal.removeEventListener("abort",K);},h=d=>{if(b)return;let w=g.shift();w?w(d):(c.push(d),c.length>s&&c.shift());},o=()=>{b=true,ie();for(let d of g)d(null);g.length=0;},i=null,p=a.liveContext;if(p){if(p.mode!==void 0&&!et&&(et=true,console.warn("[Directive] liveContext.mode is deprecated and has no runtime behavior \u2014 the 1.x landing ships abort-and-emit only. Remove the field; automatic re-prompt semantics will return in a follow-up RFC.")),D&&p.system===n){let Y=["agent","conversation","approvalState"],u=p.keys.filter(k=>Y.some(T=>k.startsWith(T)));u.length>0&&console.warn(`[Directive] liveContext watches bridge-state keys (${u.join(", ")}) on the orchestrator's own system. The orchestrator's own setAgentState / setConversation / approvalState writes will trigger interruptWhen, self-looping the run. Use a separate system for liveContext, or scope \`keys\` to user-fact namespaces.`);}let d=p.notifyOn??"interrupt-only",w=p.interruptWhen??(()=>true),E=new Set(p.keys),X=p.system.facts.$store;if(typeof X?.subscribe=="function"){let Y=X.toObject?.()??{};i=X.subscribe(p.keys,()=>{if(b)return;let u=X.toObject?.()??{},k=[];for(let v of p.keys)u[v]!==Y[v]&&k.push(v);if(Y=u,k.length===0)return;let T=k.filter(v=>E.has(v));if(T.length===0)return;let f=false;try{f=w(u,T);}catch(v){console.error("[Directive] liveContext.interruptWhen threw \u2014 treating as non-interrupt",v),f=false;}try{p.onContextUpdate?.(T);}catch(v){console.error("[Directive] liveContext.onContextUpdate threw",v);}f?(h({type:"interrupted",reason:"liveContext.interruptWhen",partialOutput:l,changedKeys:T}),r.abort()):d==="all-changes"&&h({type:"context_updated",changedKeys:T});});}}let O=()=>{i&&(i(),i=null);},m=(async()=>{h({type:"progress",phase:"starting",message:"Running input guardrails"});try{let d=t,w=(q.input??[]).map((u,k)=>chunkGWWZXJOG_cjs.c(u,k,"input"));for(let u of w){let{name:k}=u,T={agentName:e.name,input:d,facts:n.facts.$store.toObject()},f=await chunkGWWZXJOG_cjs.d(u,{input:d,agentName:e.name},T);if(!f.passed)throw h({type:"guardrail_triggered",guardrailName:k,reason:f.reason??"Input validation failed",partialOutput:l,stopped:!0}),new chunkK64WKZ22_cjs.a({code:"INPUT_GUARDRAIL_FAILED",message:`Input guardrail "${k}" failed: ${f.reason}`,guardrailName:k,guardrailType:"input",userMessage:f.reason??"Input validation failed",agentName:e.name,input:d});f.transformed!==void 0&&(d=f.transformed);}h({type:"progress",phase:"generating",message:"Starting agent"}),n.batch(()=>{let u=chunkGWWZXJOG_cjs.f(n.facts);chunkGWWZXJOG_cjs.g(n.facts,{...u,status:"running",currentAgent:e.name,input:d,startedAt:Date.now()});});let E=await chunkGWWZXJOG_cjs.e(ne,e,d,{signal:r.signal,onMessage:u=>{let k=chunkGWWZXJOG_cjs.j(n.facts);if(chunkGWWZXJOG_cjs.k(n.facts,[...k,u]),h({type:"message",message:u}),u.role==="assistant"&&u.content){let T=Math.ceil(u.content.length/4);C+=T,l+=u.content,l.length>A&&(l=l.slice(-A)),h({type:"token",data:u.content,tokenCount:C});}},onToolCall:async u=>{h({type:"tool_start",tool:u.name,toolCallId:u.id,arguments:u.arguments});let k=(q.toolCall??[]).map((f,v)=>chunkGWWZXJOG_cjs.c(f,v,"toolCall"));for(let f of k){let{name:v}=f,ue={agentName:e.name,input:d,facts:n.facts.$store.toObject()},ce=await chunkGWWZXJOG_cjs.d(f,{toolCall:u,agentName:e.name,input:d},ue);if(!ce.passed)throw h({type:"guardrail_triggered",guardrailName:v,reason:ce.reason??"Tool call blocked",partialOutput:l,stopped:!0}),new chunkK64WKZ22_cjs.a({code:"TOOL_CALL_GUARDRAIL_FAILED",message:`Tool call guardrail "${v}" failed: ${ce.reason}`,guardrailName:v,guardrailType:"toolCall",userMessage:ce.reason??"Tool call blocked",data:{toolCall:u},agentName:e.name,input:d})}if(!de){let f=`tool-${u.id}`;h({type:"approval_required",requestId:f,toolName:u.name});let v={id:f,type:"tool_call",agentName:e.name,description:`Tool call: ${u.name}`,data:u,requestedAt:Date.now()};n.batch(()=>{let ue=chunkGWWZXJOG_cjs.h(n.facts);chunkGWWZXJOG_cjs.i(n.facts,{...ue,pending:[...ue.pending,v]});}),le?.(v),await Le(f,r.signal),h({type:"approval_resolved",requestId:f,approved:!0});}let T=chunkGWWZXJOG_cjs.l(n.facts);chunkGWWZXJOG_cjs.m(n.facts,[...T,u]),u.result&&h({type:"tool_end",tool:u.name,toolCallId:u.id,result:u.result});}},oe);h({type:"progress",phase:"finishing",message:"Running output guardrails"});let X=(q.output??[]).map((u,k)=>chunkGWWZXJOG_cjs.c(u,k,"output"));for(let u of X){let{name:k}=u,T={agentName:e.name,input:d,facts:n.facts.$store.toObject()},f=await chunkGWWZXJOG_cjs.d(u,{output:E.output,agentName:e.name,input:d,messages:E.messages},T);if(!f.passed)throw h({type:"guardrail_triggered",guardrailName:k,reason:f.reason??"Output validation failed",partialOutput:typeof E.output=="string"?E.output:"",stopped:!0}),new chunkK64WKZ22_cjs.a({code:"OUTPUT_GUARDRAIL_FAILED",message:`Output guardrail "${k}" failed: ${f.reason}`,guardrailName:k,guardrailType:"output",userMessage:f.reason??"Output validation failed",agentName:e.name,input:d});f.transformed!==void 0&&(E.output=f.transformed);}n.batch(()=>{let u=chunkGWWZXJOG_cjs.f(n.facts);chunkGWWZXJOG_cjs.g(n.facts,{...u,status:"completed",output:E.output,tokenUsage:u.tokenUsage+E.totalTokens,turnCount:u.turnCount+E.messages.length,completedAt:Date.now()});});let Y=Date.now()-F;return h({type:"done",totalTokens:E.totalTokens,duration:Y,droppedTokens:0}),o(),E}catch(d){throw h({type:"error",error:d instanceof Error?d:new Error(String(d))}),o(),d}})();m.catch(()=>{});let x={[Symbol.asyncIterator](){return {async next(){return c.length>0?{done:false,value:c.shift()}:b?{done:true,value:void 0}:new Promise(d=>{g.push(w=>{d(w===null?{done:true,value:void 0}:{done:false,value:w});});})}}}},L=false;return m.finally(()=>{L||O();}).catch(()=>{}),{stream:x,result:m,abort:()=>{r.abort(),O(),o();},interrupt:d=>{L=true,h({type:"interrupted",reason:d??"caller.interrupt",partialOutput:l,changedKeys:[]}),r.abort();}}},async waitForIdle(e){let t=()=>chunkGWWZXJOG_cjs.f(n.facts).status!=="running";if(t())return;let a=Date.now();for(;!t();){if(e!==void 0&&Date.now()-a>e)throw new Error("[Directive Orchestrator] waitForIdle timed out");await new Promise(r=>setTimeout(r,50));}},approve(e){n.batch(()=>{let t=chunkGWWZXJOG_cjs.h(n.facts);if(!t.pending.some(s=>s.id===e)){D&&console.debug(`[Directive] approve() ignored: no pending request "${e}"`);return}let a=200,r=[...t.approved,e];chunkGWWZXJOG_cjs.i(n.facts,{...t,pending:t.pending.filter(s=>s.id!==e),approved:r.length>a?r.slice(-a):r});});},reject(e,t){n.batch(()=>{let a=chunkGWWZXJOG_cjs.h(n.facts);if(!a.pending.some(g=>g.id===e)){D&&console.debug(`[Directive] reject() ignored: no pending request "${e}"`);return}t&&D&&console.debug(`[Directive] Request ${e} rejected: ${t}`);let r={id:e,reason:t,rejectedAt:Date.now()},s=200,c=[...a.rejected,r];chunkGWWZXJOG_cjs.i(n.facts,{...a,pending:a.pending.filter(g=>g.id!==e),rejected:c.length>s?c.slice(-s):c});});},pause(){let e=chunkGWWZXJOG_cjs.f(n.facts);chunkGWWZXJOG_cjs.g(n.facts,{...e,status:"paused"});},resume(){let e=chunkGWWZXJOG_cjs.f(n.facts);e.status==="paused"&&chunkGWWZXJOG_cjs.g(n.facts,{...e,status:e.currentAgent?"running":"idle"});},reset(){n.batch(()=>{chunkGWWZXJOG_cjs.g(n.facts,{status:"idle",currentAgent:null,input:null,output:null,error:null,tokenUsage:0,turnCount:0,startedAt:null,completedAt:null}),chunkGWWZXJOG_cjs.i(n.facts,{pending:[],approved:[],rejected:[]}),chunkGWWZXJOG_cjs.k(n.facts,[]),chunkGWWZXJOG_cjs.m(n.facts,[]),chunkGWWZXJOG_cjs.o(n.facts,{pending:[],resolved:[],cancelled:[]}),adapterUtils.setBridgeFact(n.facts,"__budgetWarningFired",false);}),H.clear(),Q.clear();},async checkpoint(e){if(chunkGWWZXJOG_cjs.f(n.facts).status==="running")throw new Error("[Directive] Cannot checkpoint while agent is running");if(!n.history?.export)throw new Error("[Directive] Checkpointing requires history. Set `debug: true` in orchestrator options.");let a={version:1,id:chunkGWWZXJOG_cjs.w(),createdAt:new Date().toISOString(),label:e?.label,systemExport:n.history.export(),timelineExport:y?.export()??null,localState:{type:"single"},memoryExport:M?M.export?.()??null:null,orchestratorType:"single"};return Ce&&await Ce.save(a),a},restore(e,t){if(!chunkGWWZXJOG_cjs.x(e))throw new Error("[Directive] Invalid checkpoint data");if(e.orchestratorType!=="single")throw new Error("[Directive] Cannot restore multi-agent checkpoint in single-agent orchestrator");if(!n.history?.import)throw new Error("[Directive] Restoring a checkpoint requires history. Set `debug: true` in orchestrator options.");n.history.import(e.systemExport),t?.restoreTimeline!==false&&e.timelineExport&&y&&y.import(e.timelineExport),e.memoryExport!==null&&M&&M.import&&M.import(e.memoryExport);},resumeBreakpoint(e,t){t&&H.set(e,t),n.batch(()=>{let a=chunkGWWZXJOG_cjs.n(n.facts),r=[...a.resolved,e];chunkGWWZXJOG_cjs.o(n.facts,{...a,pending:a.pending.filter(s=>s.id!==e),resolved:r.length>chunkGWWZXJOG_cjs.s?r.slice(-chunkGWWZXJOG_cjs.s):r});});},cancelBreakpoint(e,t){t&&Q.set(e,t),n.batch(()=>{let a=chunkGWWZXJOG_cjs.n(n.facts),r=[...a.cancelled,e];chunkGWWZXJOG_cjs.o(n.facts,{...a,pending:a.pending.filter(s=>s.id!==e),cancelled:r.length>chunkGWWZXJOG_cjs.s?r.slice(-chunkGWWZXJOG_cjs.s):r});});},getPendingBreakpoints(){return [...chunkGWWZXJOG_cjs.n(n.facts).pending]},destroy(){n.destroy();}}}
|
|
15
|
+
exports.a=xt;//# sourceMappingURL=chunk-ESJQSOKJ.cjs.map
|
|
16
|
+
//# sourceMappingURL=chunk-ESJQSOKJ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent-orchestrator.ts"],"names":["MAX_CONVERSATION_MESSAGES","MAX_TOOL_CALLS","deprecatedModeWarned","createAgentOrchestrator","options","runner","factsSchema","init","constraints","resolvers","guardrails","onApprovalRequest","autoApproveToolCalls","maxTokenBudget","budgetWarningThreshold","onBudgetWarning","budgetEstimateTokens","retryInsideCircuit","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","inFlightReservation","resolveBudgetReservation","n","runAgentWithGuardrails","_currentFacts","callOptions","reserved","currentUsage","runAgentWithGuardrailsBody","withFallbackBudgetReservation","work","applySelfHealingFallback","error","fallbackRunner","rerouteEvent","fallbackAgent","runAgentWithGuardrailsInner","startTime","contextMessages","contextStr","m","metaStr","formatSystemMeta","bpContext","mods","handleBreakpoint","effectiveInputGuardrails","effectiveOutputGuardrails","inputGuardrailsList","g","normalizeGuardrail","guardrail","guardStartTime","result","executeGuardrailWithRetry","GuardrailError","effectiveSchema","effectiveRunner","withStructuredOutput","inner","a","i","o","executeAgentWithRetry","message","updated","getConversation","toolCall","toolCallGuardrails","guardResult","approvalId","approvalRequest","currentApproval","getApprovalState","waitForApproval","updatedToolCalls","getToolCalls","attempt","delayMs","outputGuardrailsList","shouldFireBudgetWarning","budgetPercentage","newTokenUsage","warningFired","getBridgeFact","callbackError","memoryError","outputStr","breakpointModifications","breakpointCancelReasons","waitForBreakpointResolution","bpId","signal","resolve","reject","settled","timeoutId","cleanupAll","onAbort","unsubscribe","BREAKPOINT_KEY","bpState","getBreakpointState","cancelReason","bpTimeout","type","match","matchBreakpoint","createBreakpointId","request","requestId","APPROVAL_KEY","approval","rejectedRequest","r","errorMsg","timeoutSeconds","getCombinedFacts","abortController","MAX_STREAM_BUFFER","chunks","waiters","closed","tokenCount","MAX_ACCUMULATED_OUTPUT","accumulatedOutput","abortHandler","cleanup","pushChunk","chunk","waiter","closeStream","liveContextUnsub","liveCfg","bridgeKeys","overlap","bk","notifyOn","interruptWhen","watched","store","lastSnapshot","current","changed","k","watchedChanged","shouldInterrupt","err","tearDownLiveContext","resultPromise","processedInput","inputGuardrails","currentConversation","newTokens","currentToolCalls","outputGuardrails","duration","stream","interruptInitiated","reason","timeoutMs","isIdle","start","MAX_APPROVAL_HISTORY","approved","MAX_REJECTION_HISTORY","rejected","cpOptions","cp","createCheckpointId","restoreOpts","validateCheckpoint","id","modifications","resolved","MAX_BREAKPOINT_HISTORY","cancelled"],"mappings":"uTA4GA,IAAMA,EAAAA,CAA4B,GAAA,CAE5BC,GAAiB,GAAA,CAcnBC,EAAAA,CAAuB,KAAA,CA8bpB,SAASC,EAAAA,CAEdC,EAAAA,CAAuD,CACvD,GAAM,CACJ,MAAA,CAAAC,EAAAA,CACA,WAAA,CAAAC,EAAAA,CAAc,EAAC,CACf,IAAA,CAAAC,EAAAA,CACA,YAAAC,EAAAA,CAAc,EAAC,CACf,SAAA,CAAAC,EAAAA,CAAY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,CAAS,MAAA,CAASC,mBAAAA,CACdD,EAAS,KAAA,CAAM,CAACC,mBAAsB,CAAA,CACtCD,CACR,CAAC,EACH,CAAC,EACH,CAAA,CAEA,gBAAA,CAAiBF,CAAAA,CAAYb,CAAAA,CAAuB,CAC9CA,CAAAA,EACFtE,CAAAA,CAAwB,GAAA,CAAImF,CAAAA,CAAIb,CAAM,CAAA,CAExC7K,CAAAA,CAAO,KAAA,CAAM,IAAM,CACjB,IAAMmH,CAAAA,CAAUC,mBAAAA,CAAmBpH,CAAAA,CAAO,KAAK,CAAA,CACzC8L,CAAAA,CAAY,CAAC,GAAG3E,CAAAA,CAAQ,SAAA,CAAWuE,CAAE,CAAA,CAC3ChK,mBAAAA,CAAmB1B,CAAAA,CAAO,KAAA,CAAO,CAC/B,GAAGmH,EACH,OAAA,CAASA,CAAAA,CAAQ,OAAA,CAAQ,MAAA,CAAQa,CAAAA,EAAMA,CAAAA,CAAE,EAAA,GAAO0D,CAAE,CAAA,CAClD,SAAA,CACEI,CAAAA,CAAU,MAAA,CAASD,mBAAAA,CACfC,CAAAA,CAAU,MAAM,CAACD,mBAAsB,CAAA,CACvCC,CACR,CAAC,EACH,CAAC,EACH,CAAA,CAEA,qBAAA,EAA6C,CAG3C,OAAO,CAAC,GAFQ1E,oBAAmBpH,CAAAA,CAAO,KAAK,CAAA,CAE5B,OAAO,CAC5B,CAAA,CAEA,OAAA,EAAgB,CACdA,CAAAA,CAAO,OAAA,GACT,CACF,CAGF","file":"chunk-ESJQSOKJ.cjs","sourcesContent":["/**\n * Agent Orchestrator — constraint-driven agent execution with guardrails.\n *\n * Single-agent orchestrator backed by a Directive System with reactive state,\n * constraints, guardrails, streaming, approval workflow, and lifecycle hooks.\n */\n\nimport type {\n ModuleSchema,\n Plugin,\n Requirement,\n SingleModuleSystem,\n System,\n} from \"@directive-run/core\";\nimport { createModule, t } from \"@directive-run/core\";\nimport { createSystem } from \"@directive-run/core\";\nimport {\n createCallbackPlugin,\n getBridgeFact,\n requirementGuard,\n setBridgeFact,\n} from \"@directive-run/core/adapter-utils\";\nimport type { CircuitBreaker } from \"@directive-run/core/plugins\";\nimport type { AgentMemory } from \"./memory.js\";\nimport { formatSystemMeta } from \"./meta-context.js\";\nimport type { StreamChunk as StreamChunkBase } from \"./streaming.js\";\n\nimport type {\n AgentLike,\n AgentRetryConfig,\n AgentRunner,\n ApprovalRequest,\n GuardrailFn,\n GuardrailsConfig,\n InputGuardrailData,\n NamedGuardrail,\n OrchestratorConstraint,\n OrchestratorLifecycleHooks,\n OrchestratorResolver,\n OrchestratorState,\n OutputGuardrailData,\n RejectedRequest,\n RerouteEvent,\n RunOptions,\n RunResult,\n SelfHealingConfig,\n} from \"./types.js\";\n\nimport {\n APPROVAL_KEY,\n BREAKPOINT_KEY,\n GuardrailError,\n orchestratorBridgeSchema,\n} from \"./types.js\";\n\nimport {\n type DebugTimeline,\n createDebugTimeline,\n createDebugTimelinePlugin,\n} from \"./debug-timeline.js\";\n\nimport {\n executeAgentWithRetry,\n executeGuardrailWithRetry,\n normalizeGuardrail,\n} from \"./guardrail-utils.js\";\n\nimport {\n convertOrchestratorConstraints,\n convertOrchestratorResolvers,\n getAgentState,\n getApprovalState,\n getBreakpointState,\n getConversation,\n getOrchestratorState,\n getToolCalls,\n setAgentState,\n setApprovalState,\n setBreakpointState,\n setConversation,\n setToolCalls,\n} from \"./orchestrator-bridge.js\";\n\nimport type {\n BreakpointConfig,\n BreakpointContext,\n BreakpointModifications,\n BreakpointRequest,\n} from \"./breakpoints.js\";\nimport {\n MAX_BREAKPOINT_HISTORY,\n createBreakpointId,\n matchBreakpoint,\n} from \"./breakpoints.js\";\nimport {\n type Checkpoint,\n type CheckpointStore,\n createCheckpointId,\n validateCheckpoint,\n} from \"./checkpoint.js\";\nimport {\n type SafeParseable,\n withStructuredOutput,\n} from \"./structured-output.js\";\n\n// Bridge accessors and constraint/resolver converters imported from orchestrator-bridge.ts\n\n/** Maximum conversation messages retained (FIFO eviction) */\nconst MAX_CONVERSATION_MESSAGES = 500;\n/** Maximum tool calls retained (FIFO eviction) */\nconst MAX_TOOL_CALLS = 200;\n\n/** Built-in pause requirement type */\ninterface PauseBudgetExceededReq extends Requirement {\n type: \"__PAUSE_BUDGET_EXCEEDED\";\n}\n\n// ============================================================================\n// Exported Types\n// ============================================================================\n\n// — one-shot deprecation warning for the v1.18.0 `mode` field\n// on `LiveContextOptions`. Module-scope so the warning fires once per\n// process, not per `runStream` call.\nlet deprecatedModeWarned = false;\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 = createAgentOrchestrator({\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 /**\n * Optional reservation hint for the budget pre-flight check. When set\n * (number or per-call callback), the orchestrator reserves that many\n * tokens for each in-flight call so concurrent runs cannot collectively\n * overshoot `maxTokenBudget`. Without this, the pre-flight only catches\n * the \"already over\" case — N concurrent runs can each individually\n * read `tokenUsage = 0` and overshoot together (TOCTOU).\n *\n * - `undefined` (default): pre-flight only checks the already-over\n * condition. Concurrent runs may still collectively overshoot.\n * - `number`: reserve this many tokens per call (typical small-agent\n * ceiling is 2000–8000).\n * - `(input, agent) => number`: per-call estimate.\n *\n * @example\n * ```ts\n * createAgentOrchestrator({\n * maxTokenBudget: 100_000,\n * budgetEstimateTokens: 5_000, // conservative reservation per call\n * });\n * ```\n */\n budgetEstimateTokens?: number | ((input: string, agent: AgentLike) => number);\n /**\n * Controls how `circuitBreaker` composes with `agentRetry`.\n *\n * Prior to v1.21, the orchestrator wrapped the entire retry loop in\n * one `circuitBreaker.execute(...)` call — `attempts: 3` +\n * `failureThreshold: 5` required 15 real upstream failures before the\n * breaker opened. That's the retry-storm anti-pattern: a transient\n * provider outage cost roughly `attempts × failureThreshold` calls\n * before any protection kicked in.\n *\n * The new default (`false`) routes each retry attempt through the\n * breaker individually. Each failed attempt counts toward\n * `failureThreshold`; if the breaker opens partway through retries,\n * the remaining attempts short-circuit and the orchestrator surfaces\n * the breaker's open-circuit error to the caller. This is the\n * correct semantic under sustained upstream failure.\n *\n * Set to `true` for the legacy behavior (one breaker call per\n * top-level run, retries hidden from the breaker).\n *\n * @default false\n */\n retryInsideCircuit?: boolean;\n /** Plugins */\n plugins?: Plugin[];\n /**\n * Enable debugging — `true` for default debug, or config object for advanced options\n * @default false\n */\n debug?: boolean | import(\"./types.js\").OrchestratorDebugConfig;\n /**\n * Approval timeout in milliseconds\n * @default 300000 (5 minutes)\n */\n approvalTimeoutMs?: number;\n /** Retry configuration for agent runs (no retries if not specified) */\n agentRetry?: AgentRetryConfig;\n /** Lifecycle hooks for observability */\n hooks?: OrchestratorLifecycleHooks;\n /**\n * Optional memory instance. When provided, context messages are auto-injected\n * into agent instructions before each run, and result messages are auto-stored.\n */\n memory?: AgentMemory;\n /**\n * Optional circuit breaker. Wraps every run() call.\n * When OPEN, throws CircuitBreakerOpenError instead of calling the agent.\n */\n circuitBreaker?: CircuitBreaker;\n /** Self-healing configuration for automatic fallback */\n selfHealing?: SelfHealingConfig;\n /**\n * Default schema for structured output. When set, agent output is parsed and\n * validated against this schema with automatic retry on failure.\n * Any Zod-compatible schema (anything with `safeParse`) works.\n */\n outputSchema?: SafeParseable<unknown>;\n /**\n * Max retries for structured output parsing.\n * @default 2\n */\n maxSchemaRetries?: number;\n /** Optional checkpoint store for save/restore workflow state. */\n checkpointStore?: CheckpointStore;\n /**\n * Breakpoint configurations for human-in-the-loop pause points.\n * Zero overhead when empty — guard checks at each insertion point.\n */\n breakpoints?: BreakpointConfig[];\n /** Callback fired when a breakpoint is hit and waiting for resolution. */\n onBreakpoint?: (request: BreakpointRequest) => void;\n /**\n * Timeout for breakpoint resolution in milliseconds.\n * @default 300000 (5 minutes)\n */\n breakpointTimeoutMs?: number;\n /**\n * Include system meta in agent instructions for structured LLM reasoning.\n * When true, constraint labels, resolver descriptions, fact annotations,\n * and module metadata are injected into the agent's system prompt.\n * @default false\n */\n metaContext?: boolean;\n}\n\n/** Streaming run result from orchestrator */\nexport interface OrchestratorStreamResult<T = unknown> {\n /** Async iterator for streaming chunks */\n stream: AsyncIterable<OrchestratorStreamChunk>;\n /** Promise that resolves to the final result */\n result: Promise<RunResult<T>>;\n /** Abort the stream */\n abort: () => void;\n /**\n * RFC 0005: cancel the in-flight generation but keep the\n * `liveContext` subscription attached. Distinct from `abort()`:\n * `abort` tears the AsyncIterable down AND detaches liveContext;\n * `interrupt` cancels the LLM run but leaves the orchestrator's\n * fact subscriptions alive so the next caller-driven prompt\n * continues against fresh facts. The optional `reason` lands on\n * the emitted `interrupted` chunk.\n */\n interrupt: (reason?: string) => void;\n}\n\n/** Stream chunk types for orchestrator — extends StreamChunk with approval events */\nexport type OrchestratorStreamChunk =\n | StreamChunkBase\n | { type: \"approval_required\"; requestId: string; toolName: string }\n | { type: \"approval_resolved\"; requestId: string; approved: boolean }\n /**\n * RFC 0005: a `liveContext`-watched fact changed. Carries the keys\n * whose values changed in this batch so the consumer can decide\n * whether to re-render the system prompt mid-stream. Always emitted\n * when `notifyOn: \"all-changes\"`; emitted only for keys whose\n * change `interruptWhen` returned `true` for when `notifyOn:\n * \"interrupt-only\"` (the default).\n */\n | { type: \"context_updated\"; changedKeys: readonly string[] }\n /**\n * RFC 0005: `liveContext.interruptWhen` returned `true` for at\n * least one changed key. The orchestrator aborted the in-flight\n * LLM run and emits this chunk with the partial output captured\n * up to the abort point. The consumer is responsible for\n * re-prompting via a fresh `runStream` call against the still-live\n * liveContext subscription (or for fully tearing the run down via\n * `result.abort()`). A follow-up RFC will add automatic re-invocation\n * once the design is settled.\n */\n | {\n type: \"interrupted\";\n reason: string;\n partialOutput: string;\n changedKeys: readonly string[];\n };\n\n/**\n * RFC 0005: live-context options for `runStream`. Wires a Directive\n * system's fact subscriptions into the in-flight LLM run so the\n * agent's view of the world stays in sync with reality.\n *\n * @example Market dashboard agent reacting to price ticks\n * ```ts\n * const result = orchestrator.runStream(agent, \"Summarize current state\", {\n * liveContext: {\n * system: marketSystem,\n * keys: [\"lastPrice\"],\n * interruptWhen: (facts) => Math.abs(facts.lastPrice - facts.openPrice) > 5,\n * },\n * });\n * ```\n */\nexport interface LiveContextOptions<\n F extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** The Directive system whose facts feed the agent. */\n system: System<any>;\n /**\n * Fact keys to watch. The orchestrator subscribes to fact-change\n * notifications keyed on these names. Other facts change without\n * notifying the agent — keep this list tight to bound work.\n */\n keys: readonly (keyof F & string)[];\n /**\n * Predicate run on every batch of fact changes that touches a\n * watched key. Return `true` to interrupt the in-flight LLM run.\n * Receives the FULL fact snapshot + the array of changed keys so\n * the predicate can look at correlations (price + volume, headSha +\n * prState, etc.). Optional — defaults to `() => true` (interrupt\n * on every watched-key change).\n */\n interruptWhen?: (facts: F, changedKeys: readonly string[]) => boolean;\n /**\n * @deprecated The `mode` field has no behavior in 1.x — the 1.18\n * landing ships a single behavior (abort the LLM run, emit an\n * `interrupted` chunk, hand control back to the caller; the caller\n * re-prompts via a fresh `runStream` or tears down via `abort()`).\n * The field was briefly added in 1.18.0 with two declared values\n * (`\"inject-system-message\"` and `\"restart\"`) but the orchestrator\n * never read it, so neither value did what its name implied.\n * Setting this field is a no-op at runtime and the orchestrator\n * emits a one-shot dev-mode warning when it's set to a non-default\n * value. The follow-up RFC for automatic re-prompt semantics will\n * re-introduce the field alongside an impl that actually reads it;\n * until then this slot is kept solely for source-compat with v1.18\n * call sites — pass nothing or remove the field for current\n * abort-and-emit behavior.\n */\n mode?: \"inject-system-message\" | \"restart\";\n /**\n * `\"all-changes\"` emits `context_updated` for every watched-key\n * batch (so the consumer can render a sidebar of fact deltas).\n * `\"interrupt-only\"` (default) emits only for changes that hit\n * `interruptWhen === true`. Choose the noisier variant when\n * you want a live view; choose the default when you only care\n * about the interruption moments.\n */\n notifyOn?: \"all-changes\" | \"interrupt-only\";\n /**\n * Optional hook fired on every watched-key change AFTER the\n * `interruptWhen` predicate runs but BEFORE the chunk emits.\n * Useful for logging / instrumentation that should fire regardless\n * of `notifyOn`.\n */\n onContextUpdate?: (changedKeys: readonly string[]) => void;\n}\n\n/** Per-call options for run() */\nexport interface RunCallOptions {\n /** Override output guardrails for this call only. Set to [] to skip. */\n outputGuardrails?: Array<\n GuardrailFn<OutputGuardrailData> | NamedGuardrail<OutputGuardrailData>\n >;\n /** Override input guardrails for this call only. Set to [] to skip. */\n inputGuardrails?: Array<\n GuardrailFn<InputGuardrailData> | NamedGuardrail<InputGuardrailData>\n >;\n /** Signal for abort */\n signal?: AbortSignal;\n /** Override structured output schema for this call. Set to `null` to opt out. */\n outputSchema?: SafeParseable<unknown> | null;\n /** Override max schema retries for this call. */\n maxSchemaRetries?: number;\n}\n\n/** Orchestrator instance */\nexport interface AgentOrchestrator<F extends Record<string, unknown>> {\n system: System<any>;\n facts: F & OrchestratorState;\n /** Run an agent with guardrails. Pass options to override guardrails per-call. */\n run<T>(\n agent: AgentLike,\n input: string,\n options?: RunCallOptions,\n ): Promise<RunResult<T>>;\n /**\n * Run an agent with streaming support.\n * Returns an async iterator for chunks and a promise for the final result.\n *\n * @example\n * ```typescript\n * const { stream, result, abort } = orchestrator.runStream(agent, input);\n *\n * for await (const chunk of stream) {\n * if (chunk.type === 'token') process.stdout.write(chunk.data);\n * if (chunk.type === 'approval_required') showApprovalDialog(chunk);\n * if (chunk.type === 'guardrail_triggered') handleGuardrail(chunk);\n * }\n *\n * const finalResult = await result;\n * ```\n */\n runStream<T>(\n agent: AgentLike,\n input: string,\n options?: {\n signal?: AbortSignal;\n /**\n * RFC 0005: bind the in-flight LLM run to a Directive system's\n * facts. When a watched fact changes, the orchestrator emits a\n * `context_updated` chunk; when `interruptWhen` returns `true`,\n * the LLM run is aborted and an `interrupted` chunk lands on\n * the stream. The companion `createFactPIIGuardrail` plugin\n * MUST be wired on the same system when watched facts may\n * carry PII — `liveContext` expands the source → fact → prompt\n * bypass surface into mid-stream context updates.\n */\n liveContext?: LiveContextOptions<F & OrchestratorState>;\n },\n ): OrchestratorStreamResult<T>;\n /** Approve a pending request */\n approve(requestId: string): void;\n /** Reject a pending request */\n reject(requestId: string, reason?: string): void;\n /** Pause all agents */\n pause(): void;\n /** Resume agents */\n resume(): void;\n /** Reset conversation state */\n reset(): void;\n /** Total tokens consumed across all agent runs */\n readonly totalTokens: number;\n /** Debug timeline (null when debug is false) */\n readonly timeline: DebugTimeline | null;\n /** Wait until agent is idle. Resolves immediately if already idle. */\n waitForIdle(timeoutMs?: number): Promise<void>;\n /** Create a checkpoint of the current orchestrator state. Only valid when agent is not running. */\n checkpoint(options?: { label?: string }): Promise<Checkpoint>;\n /** Restore orchestrator state from a checkpoint. */\n restore(\n checkpoint: Checkpoint,\n options?: { restoreTimeline?: boolean },\n ): void;\n /** Resume a pending breakpoint, optionally with input modifications. */\n resumeBreakpoint(id: string, modifications?: BreakpointModifications): void;\n /** Cancel a pending breakpoint with optional reason. */\n cancelBreakpoint(id: string, reason?: string): void;\n /** Get all currently pending breakpoint requests. */\n getPendingBreakpoints(): BreakpointRequest[];\n /** Destroy the orchestrator, releasing all resources. */\n destroy(): void;\n}\n\n// ============================================================================\n// Main Factory\n// ============================================================================\n\n/**\n * Create a constraint-driven agent orchestrator backed by a Directive System.\n *\n * Wraps a single agent runner with reactive state, guardrails, streaming,\n * approval workflows, breakpoints, structured output, and lifecycle hooks.\n * Constraints and resolvers let you declaratively control agent behavior\n * based on runtime facts.\n *\n * @param options - Orchestrator configuration including runner, guardrails, constraints, and plugins.\n * @returns An {@link AgentOrchestrator} instance with `run`, `runStream`, `approve`/`reject`, and checkpoint APIs.\n *\n * @example\n * ```typescript\n * import { run as runner } from '@openai/agents';\n *\n * const orchestrator = createAgentOrchestrator({\n * runner,\n * constraints: {\n * escalateToExpert: {\n * when: (facts) => facts.agent.output?.confidence < 0.7,\n * require: (facts) => ({\n * type: 'RUN_EXPERT_AGENT',\n * query: facts.agent.input,\n * }),\n * },\n * budgetExceeded: {\n * when: (facts) => facts.agent.tokenUsage > 10000,\n * require: { type: 'PAUSE_AGENTS' },\n * },\n * },\n * guardrails: {\n * input: [\n * async (data) => {\n * const hasPII = (await detectPII(data.input)).detected;\n * return { passed: !hasPII, reason: hasPII ? 'Contains PII' : undefined };\n * },\n * ],\n * output: [\n * async (data) => {\n * const isToxic = await checkToxicity(data.output);\n * return { passed: !isToxic, reason: isToxic ? 'Toxic content' : undefined };\n * },\n * ],\n * },\n * });\n *\n * // Run with guardrails and constraint-driven orchestration\n * const result = await orchestrator.run(myAgent, 'Hello, can you help me?');\n * ```\n *\n * @throws If autoApproveToolCalls is false but no onApprovalRequest callback is provided\n * @public\n */\nexport function createAgentOrchestrator<\n F extends Record<string, unknown> = Record<string, never>,\n>(options: OrchestratorOptions<F>): AgentOrchestrator<F> {\n const {\n runner,\n factsSchema = {},\n init,\n constraints = {},\n resolvers = {},\n guardrails = {},\n onApprovalRequest,\n autoApproveToolCalls = true,\n maxTokenBudget,\n budgetWarningThreshold = 0.8,\n onBudgetWarning,\n budgetEstimateTokens,\n retryInsideCircuit = false,\n plugins = [],\n debug: rawDebug = false,\n approvalTimeoutMs = 300000,\n agentRetry,\n hooks = {},\n memory,\n circuitBreaker,\n selfHealing,\n outputSchema,\n maxSchemaRetries,\n checkpointStore,\n breakpoints,\n onBreakpoint,\n breakpointTimeoutMs,\n } = options;\n\n // Normalize debug config\n const debug = typeof rawDebug === \"object\" ? true : !!rawDebug;\n const MAX_VERBOSE_LENGTH = 5000;\n\n // Warn if selfHealing is configured without circuitBreaker (selfHealing only triggers in CB error path)\n if (debug && selfHealing && !circuitBreaker) {\n console.warn(\n \"[Directive] selfHealing config has no effect without a circuitBreaker — \" +\n \"fallback behavior requires the circuit breaker to detect failures.\",\n );\n }\n\n // Validate budget warning threshold\n if (budgetWarningThreshold < 0 || budgetWarningThreshold > 1) {\n throw new Error(\n `[Directive Orchestrator] budgetWarningThreshold must be between 0 and 1, got ${budgetWarningThreshold}`,\n );\n }\n\n // Enforce approval workflow configuration - require either auto-approve or callback\n if (!autoApproveToolCalls && !onApprovalRequest) {\n throw new Error(\n \"[Directive] Invalid approval configuration: autoApproveToolCalls is false but no onApprovalRequest callback provided. \" +\n \"Tool calls would wait for approval indefinitely. Either:\\n\" +\n \" - Set autoApproveToolCalls: true to auto-approve all tool calls\\n\" +\n \" - Provide an onApprovalRequest callback to handle approvals programmatically\",\n );\n }\n\n /** Safe hook caller — user-provided hooks must never crash the orchestrator */\n function fireHook<K extends keyof OrchestratorLifecycleHooks>(\n name: K,\n event: Parameters<NonNullable<OrchestratorLifecycleHooks[K]>>[0],\n ): void {\n try {\n (hooks[name] as ((e: typeof event) => void) | undefined)?.(event);\n } catch (hookError) {\n if (debug) {\n console.debug(`[Directive] hooks.${name} threw:`, hookError);\n }\n }\n }\n\n // Dev-mode: validate that user-provided facts keys don't collide with bridge state keys\n const RESERVED_ORCHESTRATOR_KEYS = [\n \"agent\",\n \"approval\",\n \"conversation\",\n \"toolCalls\",\n ];\n for (const key of Object.keys(factsSchema)) {\n if (RESERVED_ORCHESTRATOR_KEYS.includes(key)) {\n throw new Error(\n `[Directive] Facts schema key \"${key}\" conflicts with orchestrator state. Reserved keys: ${RESERVED_ORCHESTRATOR_KEYS.join(\", \")}. Rename your fact to avoid the collision.`,\n );\n }\n }\n\n // Build schema by combining bridge schema with user-provided schema\n const combinedSchema = {\n facts: {\n ...orchestratorBridgeSchema.facts,\n ...factsSchema,\n __budgetWarningFired: t.boolean(),\n },\n derivations: {},\n events: {},\n requirements: {},\n } satisfies ModuleSchema;\n\n // Forward declaration for runAgentWithGuardrails (used in resolver converter)\n // biome-ignore lint/style/useConst: forward declaration, assigned later\n let runAgentWithGuardrailsFn: <T>(\n agent: AgentLike,\n input: string,\n currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions,\n ) => Promise<RunResult<T>>;\n\n // Forward declaration for system (used in resolver converter)\n // biome-ignore lint/style/useConst: forward declaration, assigned later\n let system: SingleModuleSystem<any>;\n\n // Convert user constraints\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 when: (facts: any) => getAgentState(facts).tokenUsage > maxTokenBudget,\n require: { type: \"__PAUSE_BUDGET_EXCEEDED\" } as PauseBudgetExceededReq,\n };\n }\n\n // Convert user resolvers\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 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 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 // ---- R1 C7 — Budget pre-flight + TOCTOU reservation ----\n //\n // The legacy budget constraint fires AFTER `tokenUsage` is updated,\n // so a single run can overshoot by the full call cost AND N\n // concurrent runs can each individually pass the post-call check\n // collectively overshooting by N * maxTokenBudget.\n //\n // `inFlightReservation` tracks tokens reserved for currently-running\n // calls. The pre-flight check at the top of `runAgentWithGuardrails`\n // rejects when current usage PLUS reservations PLUS this call's\n // estimate would exceed the cap. When `budgetEstimateTokens` is\n // undefined (default), the reservation stays 0 and the pre-flight\n // only catches the \"already over\" case — a strict back-compat\n // behavior for consumers that didn't ship the new option.\n const inFlightReservation = { count: 0 };\n\n function resolveBudgetReservation(agent: AgentLike, input: string): number {\n if (budgetEstimateTokens === undefined) return 0;\n if (typeof budgetEstimateTokens === \"number\") {\n return Math.max(0, Math.floor(budgetEstimateTokens));\n }\n try {\n const n = budgetEstimateTokens(input, agent);\n return Number.isFinite(n) ? Math.max(0, Math.floor(n)) : 0;\n } catch {\n return 0;\n }\n }\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 // ---- Budget pre-flight (R1 C7) ----\n //\n // Reject BEFORE the LLM call when current usage + in-flight\n // reservations + this call's estimated cost would exceed the cap.\n // This closes the post-call constraint's TOCTOU window: with the\n // old behavior N concurrent runs each saw `tokenUsage = 0 < cap`,\n // all proceeded, and total spend was N * maxTokenBudget.\n //\n // When `budgetEstimateTokens` is undefined (default), `reserved`\n // is 0 — the check then only rejects when usage is already at or\n // past the cap (back-compat for consumers that haven't adopted\n // the reservation hint).\n let reserved = 0;\n if (maxTokenBudget) {\n const currentUsage = getAgentState(system.facts).tokenUsage;\n reserved = resolveBudgetReservation(agent, input);\n const projected = currentUsage + inFlightReservation.count + reserved;\n if (projected > maxTokenBudget) {\n throw new Error(\n `[Directive] Agent budget would be exceeded by this call: current=${currentUsage} + in-flight=${inFlightReservation.count} + estimate=${reserved} > maxTokenBudget=${maxTokenBudget}. Raise \\`maxTokenBudget\\`, lower \\`budgetEstimateTokens\\`, or reset \\`tokenUsage\\`.`,\n );\n }\n inFlightReservation.count += reserved;\n }\n\n try {\n return await runAgentWithGuardrailsBody<T>(\n agent,\n input,\n _currentFacts,\n opts,\n callOptions,\n );\n } finally {\n if (maxTokenBudget && reserved > 0) {\n inFlightReservation.count = Math.max(\n 0,\n inFlightReservation.count - reserved,\n );\n }\n }\n }\n\n /**\n * Self-healing fallback chain shared by both CB composition strategies.\n * Tries `fallbackRunners` (in order), then `fallbackAgent`, then the\n * `fallback-response` degradation policy. Re-throws the original\n * error when no fallback succeeds (or `selfHealing` is not configured).\n */\n /**\n * Reserve tokens for a fallback call against the running budget,\n * invoke the work, and release the reservation in `finally`. Without\n * this, fallback runners and the fallback agent bypass the\n * pre-flight reservation that the primary path runs in\n * `runAgentWithGuardrails` — a primary failure caused by budget\n * pressure would then drive the fallback into the SAME overshoot\n * the pre-flight existed to prevent.\n *\n * When `budgetEstimateTokens` is undefined (default), `reserve()`\n * returns 0 and this is a no-op — the back-compat path.\n */\n async function withFallbackBudgetReservation<T>(\n agent: AgentLike,\n input: string,\n work: () => Promise<RunResult<T>>,\n ): Promise<RunResult<T>> {\n const reserved = resolveBudgetReservation(agent, input);\n if (reserved <= 0) {\n return await work();\n }\n inFlightReservation.count += reserved;\n try {\n return await work();\n } finally {\n inFlightReservation.count = Math.max(\n 0,\n inFlightReservation.count - reserved,\n );\n }\n }\n\n async function applySelfHealingFallback<T>(\n error: unknown,\n agent: AgentLike,\n input: string,\n opts?: RunOptions,\n ): Promise<RunResult<T>> {\n if (!selfHealing) throw error;\n\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: 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: error instanceof Error ? error.message : String(error),\n });\n }\n return await withFallbackBudgetReservation<T>(agent, input, () =>\n fallbackRunner<T>(agent, input, opts),\n );\n } catch {\n // Try next fallback\n }\n }\n }\n\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: error instanceof Error ? error.message : String(error),\n });\n }\n const fallbackAgent = selfHealing.fallbackAgent;\n return await withFallbackBudgetReservation<T>(\n fallbackAgent,\n input,\n () => runner<T>(fallbackAgent, input, opts),\n );\n } catch {\n // Fallback agent also failed\n }\n }\n\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 async function runAgentWithGuardrailsBody<T>(\n agent: AgentLike,\n input: string,\n _currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions,\n ): Promise<RunResult<T>> {\n // ---- Circuit-breaker composition (R1 Distrib C2) ----\n //\n // Two strategies, controlled by `retryInsideCircuit`:\n //\n // - `false` (default, the bug fix): the breaker wraps each retry\n // attempt INSIDE `executeAgentWithRetry` (see Inner). The outer\n // path here runs Inner directly. Self-healing fallback still\n // fires when the breaker open-circuits or every attempt fails.\n // - `true` (legacy): the breaker wraps the whole Inner call so\n // retries are hidden from the breaker.\n if (circuitBreaker && retryInsideCircuit) {\n // Legacy strategy: CB wraps the whole Inner (including its retry\n // loop). Hidden retries don't count toward `failureThreshold`.\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 return applySelfHealingFallback<T>(error, agent, input, opts);\n }\n }\n\n // New-default + no-CB strategy: Inner runs once. When CB is\n // configured, Inner wraps each retry attempt with CB internally\n // (see `effectiveRunner` setup in Inner). Self-healing still kicks\n // in if Inner ultimately throws.\n try {\n return await runAgentWithGuardrailsInner<T>(\n agent,\n input,\n _currentFacts,\n opts,\n callOptions,\n );\n } catch (error) {\n if (circuitBreaker || selfHealing) {\n return applySelfHealingFallback<T>(error, agent, input, opts);\n }\n throw error;\n }\n }\n\n async function runAgentWithGuardrailsInner<T>(\n agent: AgentLike,\n input: string,\n _currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions,\n ): Promise<RunResult<T>> {\n const startTime = Date.now();\n\n // Inject memory context into agent instructions if memory is configured\n if (memory) {\n const contextMessages = memory.getContextMessages();\n if (contextMessages.length > 0) {\n const contextStr = contextMessages\n .map((m) => `${m.role}: ${m.content}`)\n .join(\"\\n\");\n agent = {\n ...agent,\n instructions: `${agent.instructions ?? \"\"}\\n\\nConversation context:\\n${contextStr}`,\n };\n }\n }\n\n // Inject system meta context if enabled\n if (options.metaContext) {\n const metaStr = formatSystemMeta(system.inspect());\n if (metaStr) {\n agent = {\n ...agent,\n instructions: `${agent.instructions ?? \"\"}\\n\\n${metaStr}`,\n };\n }\n }\n\n // Breakpoint: pre_input_guardrails\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_input_guardrails\",\n };\n const mods = await handleBreakpoint(\n \"pre_input_guardrails\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n // Resolve which guardrails to use: per-call override > orchestrator defaults\n const effectiveInputGuardrails =\n callOptions?.inputGuardrails !== undefined\n ? callOptions.inputGuardrails\n : (guardrails.input ?? []);\n const effectiveOutputGuardrails =\n callOptions?.outputGuardrails !== undefined\n ? callOptions.outputGuardrails\n : (guardrails.output ?? []);\n\n // Run input guardrails BEFORE agent_start so timeline shows correct order\n const inputGuardrailsList = effectiveInputGuardrails.map((g, i) =>\n normalizeGuardrail(g, i, \"input\"),\n );\n for (const guardrail of inputGuardrailsList) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const result = await executeGuardrailWithRetry(\n guardrail,\n { input, agentName: agent.name },\n context,\n );\n // Call onGuardrailCheck hook\n fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\n guardrailName: name,\n guardrailType: \"input\",\n passed: result.passed,\n reason: result.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!result.passed) {\n throw new GuardrailError({\n code: \"INPUT_GUARDRAIL_FAILED\",\n message: `Input guardrail \"${name}\" failed: ${result.reason}`,\n guardrailName: name,\n guardrailType: \"input\",\n userMessage: result.reason ?? \"Input validation failed\",\n agentName: agent.name,\n input,\n });\n }\n if (result.transformed !== undefined) {\n input = result.transformed as string;\n }\n }\n\n // Call onAgentStart hook (after guardrails pass)\n fireHook(\"onAgentStart\", {\n agentName: agent.name,\n input,\n timestamp: startTime,\n });\n\n if (timeline) {\n timeline.record({\n type: \"agent_start\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n inputLength: input.length,\n modelId: agent.model ?? undefined,\n ...(agent.instructions\n ? { instructions: agent.instructions.slice(0, MAX_VERBOSE_LENGTH) }\n : {}),\n input: input.slice(0, MAX_VERBOSE_LENGTH),\n });\n }\n\n // Update state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"running\",\n currentAgent: agent.name,\n input,\n startedAt: Date.now(),\n });\n });\n\n // Breakpoint: pre_agent_run\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_agent_run\",\n };\n const mods = await handleBreakpoint(\n \"pre_agent_run\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n // Structured output wrapping\n const effectiveSchema =\n callOptions?.outputSchema !== undefined\n ? callOptions.outputSchema\n : outputSchema;\n\n let effectiveRunner = runner;\n if (effectiveSchema) {\n effectiveRunner = withStructuredOutput(runner, {\n schema: effectiveSchema,\n maxRetries: callOptions?.maxSchemaRetries ?? maxSchemaRetries ?? 2,\n });\n }\n\n // Circuit-breaker per attempt (R1 Distrib C2). When `circuitBreaker`\n // is configured and `retryInsideCircuit` is false (the new default),\n // wrap the runner so every retry attempt inside\n // `executeAgentWithRetry` is gated by the breaker. Each failure\n // counts toward `failureThreshold`; an open breaker short-circuits\n // remaining retries.\n if (circuitBreaker && !retryInsideCircuit) {\n const inner = effectiveRunner;\n effectiveRunner = (<U>(a: AgentLike, i: string, o?: RunOptions) =>\n circuitBreaker!.execute(() =>\n inner<U>(a, i, o),\n )) as typeof effectiveRunner;\n }\n\n // Run the agent with retry support\n const result = await executeAgentWithRetry<T>(\n effectiveRunner,\n agent,\n input,\n {\n ...opts,\n signal: opts?.signal,\n onMessage: (message) => {\n const currentConversation = getConversation(system.facts);\n const updated = [...currentConversation, message];\n setConversation(\n system.facts,\n updated.length > MAX_CONVERSATION_MESSAGES\n ? updated.slice(-MAX_CONVERSATION_MESSAGES)\n : updated,\n );\n opts?.onMessage?.(message);\n },\n onToolCall: async (toolCall) => {\n // Run tool call guardrails with retry support\n const toolCallGuardrails = (guardrails.toolCall ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"toolCall\"),\n );\n for (const guardrail of toolCallGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n { toolCall, agentName: agent.name, input },\n context,\n );\n fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\n guardrailName: name,\n guardrailType: \"toolCall\",\n passed: guardResult.passed,\n reason: guardResult.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!guardResult.passed) {\n throw new GuardrailError({\n code: \"TOOL_CALL_GUARDRAIL_FAILED\",\n message: `Tool call guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"toolCall\",\n userMessage: guardResult.reason ?? \"Tool call blocked\",\n data: { toolCall },\n agentName: agent.name,\n input,\n });\n }\n }\n\n // Check if approval is needed\n if (!autoApproveToolCalls) {\n const approvalId = `tool-${toolCall.id}`;\n const approvalRequest: ApprovalRequest = {\n id: approvalId,\n type: \"tool_call\",\n agentName: agent.name,\n description: `Tool call: ${toolCall.name}`,\n data: toolCall,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const currentApproval = getApprovalState(system.facts);\n setApprovalState(system.facts, {\n ...currentApproval,\n pending: [...currentApproval.pending, approvalRequest],\n });\n });\n\n onApprovalRequest?.(approvalRequest);\n\n // Wait for approval (pass signal so abort cancels the wait)\n await waitForApproval(\n approvalId,\n callOptions?.signal ?? opts?.signal,\n );\n }\n\n const currentToolCalls = getToolCalls(system.facts);\n const updatedToolCalls = [...currentToolCalls, toolCall];\n setToolCalls(\n system.facts,\n updatedToolCalls.length > MAX_TOOL_CALLS\n ? updatedToolCalls.slice(-MAX_TOOL_CALLS)\n : updatedToolCalls,\n );\n opts?.onToolCall?.(toolCall);\n },\n },\n agentRetry\n ? {\n ...agentRetry,\n onRetry: (attempt, error, delayMs) => {\n agentRetry.onRetry?.(attempt, error, delayMs);\n fireHook(\"onAgentRetry\", {\n agentName: agent.name,\n input,\n attempt,\n error,\n delayMs,\n timestamp: Date.now(),\n });\n },\n }\n : undefined,\n );\n\n // Breakpoint: pre_output_guardrails\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_output_guardrails\",\n };\n const mods = await handleBreakpoint(\n \"pre_output_guardrails\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n // Run output guardrails with retry support\n const outputGuardrailsList = effectiveOutputGuardrails.map((g, i) =>\n normalizeGuardrail(g, i, \"output\"),\n );\n for (const guardrail of outputGuardrailsList) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n {\n output: result.output,\n agentName: agent.name,\n input,\n messages: result.messages,\n },\n context,\n );\n fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\n guardrailName: name,\n guardrailType: \"output\",\n passed: guardResult.passed,\n reason: guardResult.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!guardResult.passed) {\n throw new GuardrailError({\n code: \"OUTPUT_GUARDRAIL_FAILED\",\n message: `Output guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"output\",\n userMessage: guardResult.reason ?? \"Output validation failed\",\n agentName: agent.name,\n input,\n });\n }\n if (guardResult.transformed !== undefined) {\n (result as { output: unknown }).output = guardResult.transformed;\n }\n }\n\n // Update state\n let shouldFireBudgetWarning = false;\n let budgetPercentage = 0;\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n const newTokenUsage = currentAgent.tokenUsage + result.totalTokens;\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"completed\",\n output: result.output,\n tokenUsage: newTokenUsage,\n turnCount: currentAgent.turnCount + result.messages.length,\n completedAt: Date.now(),\n });\n\n // Check budget warning threshold\n if (maxTokenBudget && onBudgetWarning) {\n budgetPercentage = newTokenUsage / maxTokenBudget;\n const warningFired = getBridgeFact<boolean>(\n system.facts,\n \"__budgetWarningFired\",\n );\n if (budgetPercentage >= budgetWarningThreshold && !warningFired) {\n setBridgeFact(system.facts, \"__budgetWarningFired\", true);\n shouldFireBudgetWarning = true;\n }\n }\n });\n\n // Fire budget warning callback outside of batch (callbacks shouldn't run inside batch)\n if (shouldFireBudgetWarning) {\n try {\n onBudgetWarning!({\n currentTokens: getAgentState(system.facts).tokenUsage,\n maxBudget: maxTokenBudget!,\n percentage: budgetPercentage,\n });\n } catch (callbackError) {\n if (debug) {\n console.debug(\n \"[Directive Orchestrator] onBudgetWarning threw:\",\n callbackError,\n );\n }\n }\n }\n\n // Store messages in memory if configured (best-effort)\n if (memory && result.messages.length > 0) {\n try {\n memory.addMessages(result.messages);\n } catch (memoryError) {\n if (debug) {\n console.debug(\"[Directive] Memory addMessages failed:\", memoryError);\n }\n }\n }\n\n // Call onAgentComplete hook\n fireHook(\"onAgentComplete\", {\n agentName: agent.name,\n input,\n output: result.output,\n tokenUsage: result.totalTokens,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n });\n\n if (timeline) {\n const outputStr =\n typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output);\n timeline.record({\n type: \"agent_complete\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n outputLength: outputStr?.length ?? 0,\n totalTokens: result.totalTokens,\n inputTokens: result.tokenUsage?.inputTokens ?? 0,\n outputTokens: result.tokenUsage?.outputTokens ?? 0,\n durationMs: Date.now() - startTime,\n modelId: agent.model ?? undefined,\n output: outputStr.slice(0, MAX_VERBOSE_LENGTH),\n });\n }\n\n // Breakpoint: post_run\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"post_run\",\n };\n const mods = await handleBreakpoint(\n \"post_run\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n return result;\n }\n\n // Assign the function to the forward-declared variable\n runAgentWithGuardrailsFn = runAgentWithGuardrails;\n\n // ---- Breakpoint infrastructure ----\n const breakpointModifications = new Map<string, BreakpointModifications>();\n const breakpointCancelReasons = new Map<string, string>();\n\n function waitForBreakpointResolution(\n bpId: string,\n signal?: AbortSignal,\n ): Promise<BreakpointModifications | null> {\n if (signal?.aborted) {\n return Promise.reject(\n signal.reason ?? new Error(\"Aborted while waiting for breakpoint\"),\n );\n }\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanupAll = () => {\n if (settled) {\n return;\n }\n\n settled = true;\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n unsubscribe();\n };\n\n const onAbort = () => {\n cleanupAll();\n reject(\n signal!.reason ?? new Error(`Breakpoint wait for ${bpId} aborted`),\n );\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const unsubscribe = system.facts.$store.subscribe(\n [BREAKPOINT_KEY],\n () => {\n if (settled) {\n return;\n }\n\n const bpState = getBreakpointState(system.facts);\n if (bpState.resolved.includes(bpId)) {\n cleanupAll();\n const mods = breakpointModifications.get(bpId) ?? null;\n breakpointModifications.delete(bpId);\n resolve(mods);\n } else if (bpState.cancelled.includes(bpId)) {\n cleanupAll();\n breakpointModifications.delete(bpId);\n const cancelReason = breakpointCancelReasons.get(bpId);\n breakpointCancelReasons.delete(bpId);\n reject(\n new Error(\n cancelReason\n ? `Breakpoint ${bpId} was cancelled: ${cancelReason}`\n : `Breakpoint ${bpId} was cancelled`,\n ),\n );\n }\n },\n );\n\n const bpTimeout = breakpointTimeoutMs ?? 300000;\n timeoutId = setTimeout(() => {\n if (settled) {\n return;\n }\n\n cleanupAll();\n breakpointModifications.delete(bpId);\n breakpointCancelReasons.delete(bpId);\n reject(\n new Error(\n `[Directive] Breakpoint timeout: ${bpId} not resolved within ${Math.round(bpTimeout / 1000)}s`,\n ),\n );\n }, bpTimeout);\n });\n }\n\n async function handleBreakpoint(\n type: string,\n context: BreakpointContext,\n signal?: AbortSignal,\n ): Promise<BreakpointModifications | null> {\n if (!breakpoints || breakpoints.length === 0) {\n return null;\n }\n\n const match = matchBreakpoint(\n breakpoints as BreakpointConfig<string>[],\n type,\n context,\n );\n if (!match) {\n return null;\n }\n\n const bpId = createBreakpointId();\n const request: BreakpointRequest = {\n id: bpId,\n type,\n agentId: context.agentId,\n input: context.input,\n label: match.label,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n setBreakpointState(system.facts, {\n ...bpState,\n pending: [...bpState.pending, request],\n });\n });\n\n try {\n onBreakpoint?.(request);\n } catch {\n /* non-fatal */\n }\n try {\n hooks.onBreakpoint?.(request);\n } catch {\n /* non-fatal */\n }\n\n if (timeline) {\n timeline.record({\n type: \"breakpoint_hit\",\n timestamp: Date.now(),\n snapshotId: null,\n agentId: context.agentId,\n breakpointId: bpId,\n breakpointType: type,\n label: match.label,\n });\n }\n\n const mods = await waitForBreakpointResolution(bpId, signal);\n\n if (timeline) {\n timeline.record({\n type: \"breakpoint_resumed\",\n timestamp: Date.now(),\n snapshotId: null,\n agentId: context.agentId,\n breakpointId: bpId,\n modified: !!mods?.input,\n skipped: !!mods?.skip,\n });\n }\n\n return mods;\n }\n\n // Wait for approval with configurable timeout and abort signal support\n function waitForApproval(\n requestId: string,\n signal?: AbortSignal,\n ): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(\n signal.reason ?? new Error(\"Aborted while waiting for approval\"),\n );\n }\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanupAll = () => {\n if (settled) {\n return;\n }\n\n settled = true;\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n unsubscribe();\n };\n\n const onAbort = () => {\n cleanupAll();\n reject(\n signal!.reason ?? new Error(`Approval wait for ${requestId} aborted`),\n );\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const unsubscribe = system.facts.$store.subscribe([APPROVAL_KEY], () => {\n if (settled) {\n return;\n }\n\n const approval = getApprovalState(system.facts);\n if (approval.approved.includes(requestId)) {\n cleanupAll();\n resolve();\n } else {\n const rejectedRequest = approval.rejected.find(\n (r) => r.id === requestId,\n );\n if (rejectedRequest) {\n cleanupAll();\n const errorMsg = rejectedRequest.reason\n ? `Request ${requestId} rejected: ${rejectedRequest.reason}`\n : `Request ${requestId} rejected`;\n reject(new Error(errorMsg));\n }\n }\n });\n\n // Set timeout to prevent indefinite hanging (uses configured approvalTimeoutMs)\n timeoutId = setTimeout(() => {\n if (settled) {\n return;\n }\n\n cleanupAll();\n const timeoutSeconds = Math.round(approvalTimeoutMs / 1000);\n reject(\n new Error(\n `[Directive] Approval timeout: Request ${requestId} not resolved within ${timeoutSeconds}s.\\nSolutions:\\n 1. Handle via onApprovalRequest callback and call orchestrator.approve()/reject()\\n 2. Set autoApproveToolCalls: true to auto-approve\\n 3. Increase approvalTimeoutMs (current: ${approvalTimeoutMs}ms)\\nSee: https://directive.run/docs/ai/running-agents`,\n ),\n );\n }, approvalTimeoutMs);\n });\n }\n\n /** Get facts as the combined type for external access */\n function getCombinedFacts(): F & OrchestratorState {\n const state = getOrchestratorState(system.facts);\n\n return { ...state } as unknown as F & OrchestratorState;\n }\n\n const orchestrator: AgentOrchestrator<F> = {\n system: system as unknown as System<any>,\n get facts() {\n return getCombinedFacts();\n },\n get totalTokens() {\n return getAgentState(system.facts).tokenUsage;\n },\n get timeline() {\n return timeline;\n },\n\n async run<T>(\n agent: AgentLike,\n input: string,\n options?: RunCallOptions,\n ): Promise<RunResult<T>> {\n return runAgentWithGuardrails<T>(\n agent,\n input,\n getCombinedFacts(),\n undefined,\n options,\n );\n },\n\n runStream<T>(\n agent: AgentLike,\n input: string,\n options: {\n signal?: AbortSignal;\n liveContext?: LiveContextOptions<F & OrchestratorState>;\n } = {},\n ): OrchestratorStreamResult<T> {\n const abortController = new AbortController();\n const MAX_STREAM_BUFFER = 10_000;\n const chunks: OrchestratorStreamChunk[] = [];\n const waiters: Array<(chunk: OrchestratorStreamChunk | null) => void> =\n [];\n let closed = false;\n const startTime = Date.now();\n let tokenCount = 0;\n const MAX_ACCUMULATED_OUTPUT = 100_000;\n let accumulatedOutput = \"\";\n\n // Combine external abort signal\n let abortHandler: (() => void) | undefined;\n if (options.signal) {\n abortHandler = () => abortController.abort();\n options.signal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n\n const cleanup = () => {\n if (abortHandler && options.signal) {\n options.signal.removeEventListener(\"abort\", abortHandler);\n }\n };\n\n // Push a chunk to the stream\n const pushChunk = (chunk: OrchestratorStreamChunk) => {\n if (closed) return;\n const waiter = waiters.shift();\n if (waiter) {\n waiter(chunk);\n } else {\n chunks.push(chunk);\n // FIFO eviction when buffer exceeds max\n if (chunks.length > MAX_STREAM_BUFFER) {\n chunks.shift();\n }\n }\n };\n\n // Close the stream\n const closeStream = () => {\n closed = true;\n cleanup();\n for (const waiter of waiters) {\n waiter(null);\n }\n waiters.length = 0;\n };\n\n // RFC 0005: wire liveContext subscriptions BEFORE the resultPromise\n // IIFE constructs (which starts running synchronously). Even though\n // the IIFE's sync prefix today does no fact-mutating work before\n // its first await, hoisting the subscription removes any latent\n // race where a future IIFE prefix change could synchronously\n // mutate facts before subscribe wires up. The subscription\n // callback closes over `closed`, `pushChunk`, `accumulatedOutput`,\n // and `abortController` — all declared above and live by the\n // time a fact change can fire (which requires the IIFE to yield).\n //\n // RFC 0005 dev-mode guard: warn when liveContext.system === the\n // orchestrator's own system AND watched keys overlap bridge-state\n // keys. Without this, the orchestrator's own setAgentState calls\n // could trigger interruptWhen → abort, self-looping the run.\n let liveContextUnsub: (() => void) | null = null;\n const liveCfg = options.liveContext;\n if (liveCfg) {\n // — `mode` was briefly part of `LiveContextOptions` in\n // v1.18.0, removed in v1.19.0, and re-added as @deprecated in\n // v1.19.1+ for source-compat with v1.18 call sites. The field\n // is intentionally a runtime no-op; emit a one-shot warning\n // when a consumer actually sets it so they know to drop it.\n if ((liveCfg as any).mode !== undefined && !deprecatedModeWarned) {\n deprecatedModeWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n \"[Directive] liveContext.mode is deprecated and has no runtime behavior — \" +\n \"the 1.x landing ships abort-and-emit only. Remove the field; \" +\n \"automatic re-prompt semantics will return in a follow-up RFC.\",\n );\n }\n if (debug && (liveCfg.system as unknown) === (system as unknown)) {\n const bridgeKeys = [\"agent\", \"conversation\", \"approvalState\"];\n const overlap = liveCfg.keys.filter((k) =>\n bridgeKeys.some((bk) => k.startsWith(bk)),\n );\n if (overlap.length > 0) {\n console.warn(\n `[Directive] liveContext watches bridge-state keys (${overlap.join(\", \")}) on the orchestrator's own system. The orchestrator's own setAgentState / setConversation / approvalState writes will trigger interruptWhen, self-looping the run. Use a separate system for liveContext, or scope \\`keys\\` to user-fact namespaces.`,\n );\n }\n }\n const notifyOn = liveCfg.notifyOn ?? \"interrupt-only\";\n const interruptWhen = liveCfg.interruptWhen ?? (() => true);\n const watched = new Set(liveCfg.keys);\n // The system's facts $store exposes a key-scoped subscribe via\n // the same shape the breakpoint + approval waiters elsewhere\n // in this file use. We re-use that surface without touching\n // the bridge primitive itself.\n const store = (\n liveCfg.system as unknown as {\n facts: {\n $store: {\n subscribe?: (\n keys: readonly string[],\n listener: () => void,\n ) => () => void;\n toObject?: () => Record<string, unknown>;\n };\n };\n }\n ).facts.$store;\n if (typeof store?.subscribe === \"function\") {\n let lastSnapshot: Record<string, unknown> = store.toObject?.() ?? {};\n liveContextUnsub = store.subscribe(liveCfg.keys, () => {\n if (closed) return;\n const current = store.toObject?.() ?? {};\n const changed: string[] = [];\n for (const k of liveCfg.keys) {\n if (current[k] !== lastSnapshot[k]) changed.push(k);\n }\n lastSnapshot = current;\n if (changed.length === 0) return;\n const watchedChanged = changed.filter((k) => watched.has(k));\n if (watchedChanged.length === 0) return;\n // — run `interruptWhen` FIRST so `onContextUpdate`\n // can observe the interruption decision before the chunk\n // emits — matches the documented contract on\n // `LiveContextOptions.onContextUpdate` (\"fired AFTER the\n // interruptWhen predicate runs but BEFORE the chunk\n // emits\"). The previous order let consumer-supplied\n // callbacks fire blindly.\n //\n // Both callbacks are wrapped in try/catch: a throw inside\n // `interruptWhen` or `onContextUpdate` used to propagate\n // back through `notifyKey` → `flush` → the source's\n // publish handler, killing the publisher entirely. The\n // try/catch confines the failure to a console.error and\n // continues the notify cycle so downstream listeners\n // (audit-ledger, logging) still fire.\n let shouldInterrupt = false;\n try {\n shouldInterrupt = interruptWhen(current as any, watchedChanged);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\n \"[Directive] liveContext.interruptWhen threw — treating as non-interrupt\",\n err,\n );\n shouldInterrupt = false;\n }\n try {\n liveCfg.onContextUpdate?.(watchedChanged);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\n \"[Directive] liveContext.onContextUpdate threw\",\n err,\n );\n }\n if (shouldInterrupt) {\n pushChunk({\n type: \"interrupted\",\n reason: \"liveContext.interruptWhen\",\n partialOutput: accumulatedOutput,\n changedKeys: watchedChanged,\n });\n abortController.abort();\n } else if (notifyOn === \"all-changes\") {\n pushChunk({\n type: \"context_updated\",\n changedKeys: watchedChanged,\n });\n }\n });\n }\n }\n\n const tearDownLiveContext = (): void => {\n if (liveContextUnsub) {\n liveContextUnsub();\n liveContextUnsub = null;\n }\n };\n\n // Run the agent with streaming callbacks\n const resultPromise = (async (): Promise<RunResult<T>> => {\n pushChunk({\n type: \"progress\",\n phase: \"starting\",\n message: \"Running input guardrails\",\n });\n\n try {\n // Run input guardrails first with retry support\n let processedInput = input;\n const inputGuardrails = (guardrails.input ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"input\"),\n );\n for (const guardrail of inputGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const result = await executeGuardrailWithRetry(\n guardrail,\n { input: processedInput, agentName: agent.name },\n context,\n );\n if (!result.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: result.reason ?? \"Input validation failed\",\n partialOutput: accumulatedOutput,\n stopped: true,\n });\n throw new GuardrailError({\n code: \"INPUT_GUARDRAIL_FAILED\",\n message: `Input guardrail \"${name}\" failed: ${result.reason}`,\n guardrailName: name,\n guardrailType: \"input\",\n userMessage: result.reason ?? \"Input validation failed\",\n agentName: agent.name,\n input: processedInput,\n });\n }\n if (result.transformed !== undefined) {\n processedInput = result.transformed as string;\n }\n }\n\n pushChunk({\n type: \"progress\",\n phase: \"generating\",\n message: \"Starting agent\",\n });\n\n // Update state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"running\",\n currentAgent: agent.name,\n input: processedInput,\n startedAt: Date.now(),\n });\n });\n\n // Run agent with streaming callbacks and retry support\n const result = await executeAgentWithRetry<T>(\n runner,\n agent,\n processedInput,\n {\n signal: abortController.signal,\n onMessage: (message) => {\n const currentConversation = getConversation(system.facts);\n setConversation(system.facts, [\n ...currentConversation,\n message,\n ]);\n pushChunk({ type: \"message\", message });\n\n // Approximate token counting from content\n if (message.role === \"assistant\" && message.content) {\n const newTokens = Math.ceil(message.content.length / 4);\n tokenCount += newTokens;\n accumulatedOutput += message.content;\n if (accumulatedOutput.length > MAX_ACCUMULATED_OUTPUT) {\n accumulatedOutput = accumulatedOutput.slice(\n -MAX_ACCUMULATED_OUTPUT,\n );\n }\n pushChunk({\n type: \"token\",\n data: message.content,\n tokenCount,\n });\n }\n },\n onToolCall: async (toolCall) => {\n pushChunk({\n type: \"tool_start\",\n tool: toolCall.name,\n toolCallId: toolCall.id,\n arguments: toolCall.arguments,\n });\n\n // Run tool call guardrails with retry support\n const toolCallGuardrails = (guardrails.toolCall ?? []).map(\n (g, i) => normalizeGuardrail(g, i, \"toolCall\"),\n );\n for (const guardrail of toolCallGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n { toolCall, agentName: agent.name, input: processedInput },\n context,\n );\n if (!guardResult.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: guardResult.reason ?? \"Tool call blocked\",\n partialOutput: accumulatedOutput,\n stopped: true,\n });\n throw new GuardrailError({\n code: \"TOOL_CALL_GUARDRAIL_FAILED\",\n message: `Tool call guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"toolCall\",\n userMessage: guardResult.reason ?? \"Tool call blocked\",\n data: { toolCall },\n agentName: agent.name,\n input: processedInput,\n });\n }\n }\n\n // Check if approval is needed\n if (!autoApproveToolCalls) {\n const approvalId = `tool-${toolCall.id}`;\n pushChunk({\n type: \"approval_required\",\n requestId: approvalId,\n toolName: toolCall.name,\n });\n\n const approvalRequest: ApprovalRequest = {\n id: approvalId,\n type: \"tool_call\",\n agentName: agent.name,\n description: `Tool call: ${toolCall.name}`,\n data: toolCall,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const currentApproval = getApprovalState(system.facts);\n setApprovalState(system.facts, {\n ...currentApproval,\n pending: [...currentApproval.pending, approvalRequest],\n });\n });\n\n onApprovalRequest?.(approvalRequest);\n await waitForApproval(approvalId, abortController.signal);\n pushChunk({\n type: \"approval_resolved\",\n requestId: approvalId,\n approved: true,\n });\n }\n\n const currentToolCalls = getToolCalls(system.facts);\n setToolCalls(system.facts, [...currentToolCalls, toolCall]);\n\n if (toolCall.result) {\n pushChunk({\n type: \"tool_end\",\n tool: toolCall.name,\n toolCallId: toolCall.id,\n result: toolCall.result,\n });\n }\n },\n },\n agentRetry,\n );\n\n // Run output guardrails\n pushChunk({\n type: \"progress\",\n phase: \"finishing\",\n message: \"Running output guardrails\",\n });\n\n const outputGuardrails = (guardrails.output ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"output\"),\n );\n for (const guardrail of outputGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n {\n output: result.output,\n agentName: agent.name,\n input: processedInput,\n messages: result.messages,\n },\n context,\n );\n if (!guardResult.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: guardResult.reason ?? \"Output validation failed\",\n partialOutput:\n typeof result.output === \"string\" ? result.output : \"\",\n stopped: true,\n });\n throw new GuardrailError({\n code: \"OUTPUT_GUARDRAIL_FAILED\",\n message: `Output guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"output\",\n userMessage: guardResult.reason ?? \"Output validation failed\",\n agentName: agent.name,\n input: processedInput,\n });\n }\n if (guardResult.transformed !== undefined) {\n (result as { output: unknown }).output = guardResult.transformed;\n }\n }\n\n // Update final state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"completed\",\n output: result.output,\n tokenUsage: currentAgent.tokenUsage + result.totalTokens,\n turnCount: currentAgent.turnCount + result.messages.length,\n completedAt: Date.now(),\n });\n });\n\n const duration = Date.now() - startTime;\n pushChunk({\n type: \"done\",\n totalTokens: result.totalTokens,\n duration,\n droppedTokens: 0,\n });\n closeStream();\n\n return result;\n } catch (error) {\n pushChunk({\n type: \"error\",\n error: error instanceof Error ? error : new Error(String(error)),\n });\n closeStream();\n throw error;\n }\n })();\n\n // Prevent unhandled rejection if caller only consumes stream (not .result)\n resultPromise.catch(() => {});\n\n // Create async iterator\n const stream: AsyncIterable<OrchestratorStreamChunk> = {\n [Symbol.asyncIterator](): AsyncIterator<OrchestratorStreamChunk> {\n return {\n async next(): Promise<IteratorResult<OrchestratorStreamChunk>> {\n if (chunks.length > 0) {\n return { done: false, value: chunks.shift()! };\n }\n if (closed) {\n return { done: true, value: undefined };\n }\n\n return new Promise<IteratorResult<OrchestratorStreamChunk>>(\n (resolve) => {\n waiters.push((chunk) => {\n if (chunk === null) {\n resolve({ done: true, value: undefined });\n } else {\n resolve({ done: false, value: chunk });\n }\n });\n },\n );\n },\n };\n },\n };\n\n // Track whether the abort came from interrupt() — if so, the\n // resultPromise.finally MUST NOT tear down the liveContext\n // subscription. The whole differentiator of interrupt vs abort\n // is that interrupt cancels the LLM run but keeps the\n // subscription alive so the next caller-driven prompt continues\n // against fresh facts. Without this flag the abort triggers the\n // resultPromise's catch path → reject → finally → tearDown, and\n // the subscription dies anyway (R11 found this).\n let interruptInitiated = false;\n\n // .finally returns a new promise that re-rejects when resultPromise\n // rejects; swallow with .catch so a rejected resultPromise (e.g. a\n // guardrail block) doesn't surface as an unhandled rejection when\n // the caller only consumes the stream side of the contract.\n resultPromise\n .finally(() => {\n if (!interruptInitiated) {\n tearDownLiveContext();\n }\n })\n .catch(() => {});\n\n return {\n stream,\n result: resultPromise,\n abort: () => {\n abortController.abort();\n tearDownLiveContext();\n closeStream();\n },\n interrupt: (reason?: string) => {\n // RFC 0005: distinct from `abort()` — cancel the in-flight\n // LLM run but leave `liveContext` subscriptions alive so\n // the next caller-driven prompt continues against fresh\n // facts. The interrupted chunk lands with the reason if\n // provided.\n //\n // Set the interrupt flag BEFORE aborting so the\n // resultPromise.finally above sees it and skips\n // tearDownLiveContext. The caller is responsible for\n // either kicking off a new runStream (against the live\n // subscription) or calling abort() to fully tear down.\n interruptInitiated = true;\n pushChunk({\n type: \"interrupted\",\n reason: reason ?? \"caller.interrupt\",\n partialOutput: accumulatedOutput,\n changedKeys: [],\n });\n abortController.abort();\n },\n };\n },\n\n async waitForIdle(timeoutMs?: number): Promise<void> {\n const isIdle = () => getAgentState(system.facts).status !== \"running\";\n if (isIdle()) {\n return;\n }\n\n const start = Date.now();\n while (!isIdle()) {\n if (timeoutMs !== undefined && Date.now() - start > timeoutMs) {\n throw new Error(\"[Directive Orchestrator] waitForIdle timed out\");\n }\n await new Promise((r) => setTimeout(r, 50));\n }\n },\n\n approve(requestId: string): void {\n system.batch(() => {\n const approval = getApprovalState(system.facts);\n if (!approval.pending.some((r) => r.id === requestId)) {\n if (debug)\n console.debug(\n `[Directive] approve() ignored: no pending request \"${requestId}\"`,\n );\n\n return;\n }\n const MAX_APPROVAL_HISTORY = 200;\n const approved = [...approval.approved, requestId];\n setApprovalState(system.facts, {\n ...approval,\n pending: approval.pending.filter((r) => r.id !== requestId),\n approved:\n approved.length > MAX_APPROVAL_HISTORY\n ? approved.slice(-MAX_APPROVAL_HISTORY)\n : approved,\n });\n });\n },\n\n reject(requestId: string, reason?: string): void {\n system.batch(() => {\n const approval = getApprovalState(system.facts);\n if (!approval.pending.some((r) => r.id === requestId)) {\n if (debug)\n console.debug(\n `[Directive] reject() ignored: no pending request \"${requestId}\"`,\n );\n\n return;\n }\n if (reason && debug) {\n console.debug(`[Directive] Request ${requestId} rejected: ${reason}`);\n }\n const rejectedRequest: RejectedRequest = {\n id: requestId,\n reason,\n rejectedAt: Date.now(),\n };\n const MAX_REJECTION_HISTORY = 200;\n const rejected = [...approval.rejected, rejectedRequest];\n setApprovalState(system.facts, {\n ...approval,\n pending: approval.pending.filter((r) => r.id !== requestId),\n rejected:\n rejected.length > MAX_REJECTION_HISTORY\n ? rejected.slice(-MAX_REJECTION_HISTORY)\n : rejected,\n });\n });\n },\n\n pause(): void {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"paused\",\n });\n },\n\n resume(): void {\n const agent = getAgentState(system.facts);\n if (agent.status === \"paused\") {\n setAgentState(system.facts, {\n ...agent,\n status: agent.currentAgent ? \"running\" : \"idle\",\n });\n }\n },\n\n reset(): void {\n system.batch(() => {\n setAgentState(system.facts, {\n status: \"idle\",\n currentAgent: null,\n input: null,\n output: null,\n error: null,\n tokenUsage: 0,\n turnCount: 0,\n startedAt: null,\n completedAt: null,\n });\n setApprovalState(system.facts, {\n pending: [],\n approved: [],\n rejected: [],\n });\n setConversation(system.facts, []);\n setToolCalls(system.facts, []);\n setBreakpointState(system.facts, {\n pending: [],\n resolved: [],\n cancelled: [],\n });\n setBridgeFact(system.facts, \"__budgetWarningFired\", false);\n });\n breakpointModifications.clear();\n breakpointCancelReasons.clear();\n },\n\n async checkpoint(cpOptions?: { label?: string }): Promise<Checkpoint> {\n const agentState = getAgentState(system.facts);\n if (agentState.status === \"running\") {\n throw new Error(\"[Directive] Cannot checkpoint while agent is running\");\n }\n if (!system.history?.export) {\n throw new Error(\n \"[Directive] Checkpointing requires history. Set `debug: true` in orchestrator options.\",\n );\n }\n\n const cp: Checkpoint = {\n version: 1,\n id: createCheckpointId(),\n createdAt: new Date().toISOString(),\n label: cpOptions?.label,\n systemExport: system.history.export(),\n timelineExport: timeline?.export() ?? null,\n localState: { type: \"single\" },\n memoryExport: memory ? ((memory as any).export?.() ?? null) : null,\n orchestratorType: \"single\",\n };\n\n if (checkpointStore) {\n await checkpointStore.save(cp);\n }\n\n return cp;\n },\n\n restore(cp: Checkpoint, restoreOpts?: { restoreTimeline?: boolean }): void {\n if (!validateCheckpoint(cp)) {\n throw new Error(\"[Directive] Invalid checkpoint data\");\n }\n if (cp.orchestratorType !== \"single\") {\n throw new Error(\n \"[Directive] Cannot restore multi-agent checkpoint in single-agent orchestrator\",\n );\n }\n if (!system.history?.import) {\n throw new Error(\n \"[Directive] Restoring a checkpoint requires history. Set `debug: true` in orchestrator options.\",\n );\n }\n\n system.history.import(cp.systemExport);\n\n if (\n restoreOpts?.restoreTimeline !== false &&\n cp.timelineExport &&\n timeline\n ) {\n timeline.import(cp.timelineExport);\n }\n\n if (cp.memoryExport !== null && memory && (memory as any).import) {\n (memory as any).import(cp.memoryExport);\n }\n },\n\n resumeBreakpoint(\n id: string,\n modifications?: BreakpointModifications,\n ): void {\n if (modifications) {\n breakpointModifications.set(id, modifications);\n }\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n const resolved = [...bpState.resolved, id];\n setBreakpointState(system.facts, {\n ...bpState,\n pending: bpState.pending.filter((r) => r.id !== id),\n resolved:\n resolved.length > MAX_BREAKPOINT_HISTORY\n ? resolved.slice(-MAX_BREAKPOINT_HISTORY)\n : resolved,\n });\n });\n },\n\n cancelBreakpoint(id: string, reason?: string): void {\n if (reason) {\n breakpointCancelReasons.set(id, reason);\n }\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n const cancelled = [...bpState.cancelled, id];\n setBreakpointState(system.facts, {\n ...bpState,\n pending: bpState.pending.filter((r) => r.id !== id),\n cancelled:\n cancelled.length > MAX_BREAKPOINT_HISTORY\n ? cancelled.slice(-MAX_BREAKPOINT_HISTORY)\n : cancelled,\n });\n });\n },\n\n getPendingBreakpoints(): BreakpointRequest[] {\n const bpState = getBreakpointState(system.facts);\n\n return [...bpState.pending];\n },\n\n destroy(): void {\n system.destroy();\n },\n };\n\n return orchestrator;\n}\n"]}
|