@directive-run/ai 1.3.0 → 1.5.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/anthropic.cjs +1 -1
- package/dist/anthropic.cjs.map +1 -1
- package/dist/anthropic.js +1 -1
- package/dist/anthropic.js.map +1 -1
- package/dist/{chunk-265ZKXYE.js → chunk-3PGRBK4E.js} +2 -2
- package/dist/chunk-3PGRBK4E.js.map +1 -0
- package/dist/{chunk-QXMXSHYS.cjs → chunk-KP3G32S7.cjs} +2 -2
- package/dist/chunk-KP3G32S7.cjs.map +1 -0
- package/dist/{chunk-5ERCL33C.js → chunk-Q3PQLWBR.js} +3 -3
- package/dist/chunk-Q3PQLWBR.js.map +1 -0
- package/dist/{chunk-K2LZMRLN.js → chunk-RW4R3O5P.js} +3 -3
- package/dist/{chunk-K2LZMRLN.js.map → chunk-RW4R3O5P.js.map} +1 -1
- package/dist/{chunk-KALRDVN5.cjs → chunk-X3VQ5F7D.cjs} +3 -3
- package/dist/{chunk-KALRDVN5.cjs.map → chunk-X3VQ5F7D.cjs.map} +1 -1
- package/dist/{chunk-L35IQAWD.cjs → chunk-XV2QSBBE.cjs} +7 -7
- package/dist/chunk-XV2QSBBE.cjs.map +1 -0
- package/dist/gemini.cjs +1 -1
- package/dist/gemini.cjs.map +1 -1
- package/dist/gemini.js +1 -1
- package/dist/gemini.js.map +1 -1
- package/dist/index.cjs +18 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +50 -6
- package/dist/index.d.ts +50 -6
- package/dist/index.js +18 -18
- package/dist/index.js.map +1 -1
- package/dist/{multi-agent-orchestrator-675FR2HF.js → multi-agent-orchestrator-4PXNYRHB.js} +2 -2
- package/dist/{multi-agent-orchestrator-675FR2HF.js.map → multi-agent-orchestrator-4PXNYRHB.js.map} +1 -1
- package/dist/multi-agent-orchestrator-KFGTEGE5.cjs +2 -0
- package/dist/{multi-agent-orchestrator-SH5TRRS3.cjs.map → multi-agent-orchestrator-KFGTEGE5.cjs.map} +1 -1
- package/dist/ollama.cjs +2 -2
- package/dist/ollama.cjs.map +1 -1
- package/dist/ollama.js +1 -1
- package/dist/ollama.js.map +1 -1
- package/dist/openai.cjs +1 -1
- package/dist/openai.cjs.map +1 -1
- package/dist/openai.js +1 -1
- package/dist/openai.js.map +1 -1
- package/dist/{orchestrator-types-BmvoZgfO.d.cts → orchestrator-types-Bh8r3_Sq.d.cts} +1 -1
- package/dist/{orchestrator-types-D6gzobwg.d.ts → orchestrator-types-CTfIKk0W.d.ts} +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-265ZKXYE.js.map +0 -1
- package/dist/chunk-5ERCL33C.js.map +0 -1
- package/dist/chunk-L35IQAWD.cjs.map +0 -1
- package/dist/chunk-QXMXSHYS.cjs.map +0 -1
- package/dist/multi-agent-orchestrator-SH5TRRS3.cjs +0 -2
package/dist/testing.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunkL35IQAWD_cjs=require('./chunk-L35IQAWD.cjs'),chunkKALRDVN5_cjs=require('./chunk-KALRDVN5.cjs');function b(r={}){let{defaultResponse:e={output:"mock response",totalTokens:10},responses:t={},recordCalls:n=true,onRun:o}=r,s=[],a=new Map(Object.entries(t)),i=e;return {run:async(l,c,g)=>{o?.(l,c),n&&s.push({agent:l,input:c,options:g,timestamp:Date.now()});let d=a.get(l.name)??i;if(d.generate){let p=d.generate(c,l);d={...d,...p};}if(d.error)throw d.error;d.delay&&d.delay>0&&await new Promise(p=>setTimeout(p,d.delay));let f=d.messages??[];for(let p of f)g?.onMessage?.(p);let m=d.toolCalls??[];for(let p of m)g?.onToolCall?.(p);return {output:d.output,messages:f,toolCalls:m,totalTokens:d.totalTokens??10}},getCalls:()=>[...s],getCallsFor:l=>s.filter(c=>c.agent.name===l),clearCalls:()=>s.length=0,setResponse:(l,c)=>a.set(l,c),setDefaultResponse:l=>i=l}}async function T(r,e,t){let n={agentName:"test-agent",input:"",...e},o={agentName:e.agentName??"test-agent",input:e.input??"",facts:t?.facts??{},...t},s=Date.now(),a=await r(n,o),i=Date.now()-s;return {...a,duration:i,testedData:n,assertPassed(){if(!a.passed)throw new Error(`Expected guardrail to pass, but it failed: ${a.reason}`)},assertFailed(u){if(a.passed)throw new Error("Expected guardrail to fail, but it passed");if(u!==void 0){if(typeof u=="string"&&!a.reason?.includes(u))throw new Error(`Expected failure reason to include "${u}", got: ${a.reason}`);if(u instanceof RegExp&&!u.test(a.reason??""))throw new Error(`Expected failure reason to match ${u}, got: ${a.reason}`)}},assertTransformed(u){if(a.transformed===void 0)throw new Error("Expected guardrail to transform input, but no transformation occurred");if(u!==void 0&&a.transformed!==u)throw new Error(`Expected transformation to be ${JSON.stringify(u)}, got: ${JSON.stringify(a.transformed)}`)}}}async function x(r,e){let t=[],n=[];for(let o=0;o<e.length;o++){let s=e[o],a=await T(r,s.input,s.context);t.push(a),(a.passed?a.transformed!==void 0?"transform":"pass":"fail")!==s.expect&&n.push({index:o,expected:s.expect,actual:a});}return {results:t,allPassed:()=>n.length===0,failures:()=>n}}function R(r={}){let{autoApprove:e,autoReject:t,delay:n=0,recordRequests:o=true}=r,s=[],a=new Map,i=[];return {async handle(u){o&&s.push(u);for(let l=i.length-1;l>=0;l--){let c=i[l];c.predicate(u)&&(i.splice(l,1),c.resolve(u));}return n>0&&await new Promise(l=>setTimeout(l,n)),t&&t(u)?"rejected":e?.(u)?"approved":new Promise(l=>{a.set(u.id,{request:u,resolve:l});})},getRequests:()=>[...s],clearRequests:()=>s.length=0,approve(u){let l=a.get(u);l&&(l.resolve("approved"),a.delete(u));},reject(u,l){let c=a.get(u);if(c){c.resolve("rejected"),a.delete(u);let g=s.find(d=>d.id===u);g&&(g.rejectionReason=l);}},waitForRequest(u,l=5e3){let c=s.find(u);return c?Promise.resolve(c):new Promise((g,d)=>{let f={predicate:u,resolve:p=>{clearTimeout(m),g(p);}},m=setTimeout(()=>{let p=i.indexOf(f);p>=0&&i.splice(p,1),d(new Error("Timeout waiting for approval request"));},l);i.push(f);})}}}function C(r={}){let{mockResponses:e,defaultMockResponse:t,...n}=r,o=b({responses:e,defaultResponse:t}),s=R(),a=chunkL35IQAWD_cjs.a({...n,runner:o.run,onApprovalRequest:u=>{s.handle(u),n.onApprovalRequest?.(u);}}),i=Object.create(a);return i.mockRunner=o,i.approvalSimulator=s,i.getCalls=()=>o.getCalls(),i.getApprovalRequests=()=>s.getRequests(),i.resetAll=()=>{a.reset(),o.clearCalls(),s.clearRequests();},i}function O(){let r=[];return {plugin:{name:"constraint-recorder",onRequirementCreated(e){r.push({constraintId:e.constraintId,triggered:true,requirement:e.requirement,facts:e.facts,timestamp:Date.now()});}},getSnapshots:()=>[...r],clearSnapshots:()=>r.length=0}}function M(r,e){let t=r.facts;if(e.agentStatus!==void 0&&t.agent.status!==e.agentStatus)throw new Error(`Expected agent status to be "${e.agentStatus}", got "${t.agent.status}"`);if(e.tokenUsage!==void 0){let{min:n,max:o,exact:s}=e.tokenUsage;if(s!==void 0&&t.agent.tokenUsage!==s)throw new Error(`Expected token usage to be exactly ${s}, got ${t.agent.tokenUsage}`);if(n!==void 0&&t.agent.tokenUsage<n)throw new Error(`Expected token usage to be at least ${n}, got ${t.agent.tokenUsage}`);if(o!==void 0&&t.agent.tokenUsage>o)throw new Error(`Expected token usage to be at most ${o}, got ${t.agent.tokenUsage}`)}if(e.pendingApprovals!==void 0&&t.approval.pending.length!==e.pendingApprovals)throw new Error(`Expected ${e.pendingApprovals} pending approvals, got ${t.approval.pending.length}`);if(e.conversationLength!==void 0){let{min:n,max:o,exact:s}=e.conversationLength,a=t.conversation.length;if(s!==void 0&&a!==s)throw new Error(`Expected conversation length to be exactly ${s}, got ${a}`);if(n!==void 0&&a<n)throw new Error(`Expected conversation length to be at least ${n}, got ${a}`);if(o!==void 0&&a>o)throw new Error(`Expected conversation length to be at most ${o}, got ${a}`)}}function q(r=Date.now()){let e=r,t=r;return {now:()=>e,advance:n=>{e+=n;},set:n=>{e=n;},reset:()=>{e=t;}}}function D(r){let{mockResponses:e={},defaultMockResponse:t,mockTasks:n,...o}=r;if(n){let c=o.tasks??{};for(let[g,d]of Object.entries(n))c[g]||(c[g]=y(d.output,{delay:d.delay,shouldError:d.shouldError}));o.tasks=c;}let s={};for(let[c,g]of Object.entries(e)){let d=o.agents[c];d&&(s[d.agent.name]=g);}let a=b({responses:s,defaultResponse:t}),i=R(),u=chunkKALRDVN5_cjs.Da({...o,runner:a.run,onApprovalRequest:c=>{i.handle(c),o.onApprovalRequest?.(c);}}),l=Object.create(u);return l.mockRunner=a,l.approvalSimulator=i,l.getCalls=()=>a.getCalls(),l.getApprovalRequests=()=>i.getRequests(),l.resetAll=()=>{u.reset(),a.clearCalls(),i.clearRequests();},l}function N(r,e){if(e.taskStatus)for(let[t,n]of Object.entries(e.taskStatus)){let o=r.getTaskState(t);if(!o)throw new Error(`Expected task "${t}" to exist, but it was not found`);if(o.status!==n)throw new Error(`Expected task "${t}" status to be "${n}", got "${o.status}"`)}if(e.agentStatus)for(let[t,n]of Object.entries(e.agentStatus)){let o=r.getAgentState(t);if(!o)throw new Error(`Expected agent "${t}" to exist, but it was not found`);if(o.status!==n)throw new Error(`Expected agent "${t}" status to be "${n}", got "${o.status}"`)}if(e.totalTokens){let{agentId:t,min:n,max:o}=e.totalTokens;if(t){let s=r.getAgentState(t);if(!s)throw new Error(`Expected agent "${t}" to exist, but it was not found`);if(n!==void 0&&s.totalTokens<n)throw new Error(`Expected agent "${t}" tokens to be at least ${n}, got ${s.totalTokens}`);if(o!==void 0&&s.totalTokens>o)throw new Error(`Expected agent "${t}" tokens to be at most ${o}, got ${s.totalTokens}`)}else {let s=r.getAllAgentStates(),a=Object.values(s).reduce((i,u)=>i+u.totalTokens,0);if(n!==void 0&&a<n)throw new Error(`Expected total tokens to be at least ${n}, got ${a}`);if(o!==void 0&&a>o)throw new Error(`Expected total tokens to be at most ${o}, got ${a}`)}}if(e.globalTokens){let{min:t,max:n}=e.globalTokens,o=r.totalTokens;if(t!==void 0&&o<t)throw new Error(`Expected global tokens to be at least ${t}, got ${o}`);if(n!==void 0&&o>n)throw new Error(`Expected global tokens to be at most ${n}, got ${o}`)}if(e.pendingHandoffs!==void 0){let t=r.getPendingHandoffs().length;if(t!==e.pendingHandoffs)throw new Error(`Expected ${e.pendingHandoffs} pending handoffs, got ${t}`)}}function y(r,e){return {run:async(t,n)=>{if(n.aborted)throw new Error("Task aborted");if(e?.delay&&e.delay>0&&await new Promise((o,s)=>{let a=setTimeout(o,e.delay);n.addEventListener("abort",()=>{clearTimeout(a),s(new Error("Task aborted"));},{once:true});}),e?.shouldError)throw new Error("Mock task error");return r},label:e?.label??"Mock Task",description:e?.description}}function P(r,e,t){return chunkKALRDVN5_cjs.ga(r,e??(o=>o.outputs),t)}function I(r,e){if(e.nodeStatuses)for(let[t,n]of Object.entries(e.nodeStatuses)){let o=r.statuses[t];if(o!==n)throw new Error(`Expected node "${t}" status to be "${n}", got "${o}"`)}if(e.completedNodes){for(let t of e.completedNodes)if(r.statuses[t]!=="completed")throw new Error(`Expected node "${t}" to be completed, got "${r.statuses[t]}"`)}if(e.skippedNodes){for(let t of e.skippedNodes)if(r.statuses[t]!=="skipped")throw new Error(`Expected node "${t}" to be skipped, got "${r.statuses[t]}"`)}if(e.errorNodes){for(let t of e.errorNodes)if(r.statuses[t]!=="error")throw new Error(`Expected node "${t}" to be error, got "${r.statuses[t]}"`)}if(e.outputContains)for(let[t,n]of Object.entries(e.outputContains)){let o=r.outputs[t];if(o!==n)throw new Error(`Expected node "${t}" output to be ${JSON.stringify(n)}, got ${JSON.stringify(o)}`)}}function B(r,e){let t=chunkKALRDVN5_cjs.i({maxEvents:e?.maxEvents??500});if(r)for(let n of r)t.record({timestamp:Date.now(),snapshotId:null,agentId:"",...n});return t}function F(r,e){let t=r.getEvents();if(e.totalEvents!==void 0&&t.length!==e.totalEvents)throw new Error(`Expected ${e.totalEvents} timeline events, got ${t.length}`);if(e.minEvents!==void 0&&t.length<e.minEvents)throw new Error(`Expected at least ${e.minEvents} timeline events, got ${t.length}`);if(e.maxEvents!==void 0&&t.length>e.maxEvents)throw new Error(`Expected at most ${e.maxEvents} timeline events, got ${t.length}`);if(e.eventTypes){for(let n of e.eventTypes)if(!t.some(s=>s.type===n))throw new Error(`Expected timeline to contain event of type "${n}", but none found`)}if(e.agentEvents)for(let[n,o]of Object.entries(e.agentEvents)){let s=r.getEventsForAgent(n).length;if(s!==o)throw new Error(`Expected ${o} events for agent "${n}", got ${s}`)}if(e.hasType&&!t.some(o=>o.type===e.hasType))throw new Error(`Expected timeline to contain event of type "${e.hasType}"`);if(e.doesNotHaveType&&t.some(o=>o.type===e.doesNotHaveType))throw new Error(`Expected timeline NOT to contain event of type "${e.doesNotHaveType}"`)}function H(r,e){let t=0,n=e?.failAfter??0;return async(o,s,a)=>{if(t++,n>0&&t<=n)return {output:"success",messages:[],toolCalls:[],totalTokens:10};throw e?.delay&&e.delay>0&&await new Promise(i=>setTimeout(i,e.delay)),r??new Error("Runner failed")}}function L(r,e){if(r.length===0)throw new Error("Expected at least one reroute event, but none occurred");if(e.minReroutes!==void 0&&r.length<e.minReroutes)throw new Error(`Expected at least ${e.minReroutes} reroute events, got ${r.length}`);if(e.fromAgent&&!r.some(n=>n.originalAgent===e.fromAgent))throw new Error(`Expected reroute from agent "${e.fromAgent}", but no matching event found`);if(e.toAgent&&!r.some(n=>n.reroutedTo===e.toAgent))throw new Error(`Expected reroute to agent "${e.toAgent}", but no matching event found`);if(e.reason&&!r.some(n=>typeof e.reason=="string"?n.reason.includes(e.reason):e.reason.test(n.reason)))throw new Error(`Expected reroute reason matching ${e.reason}, but no matching event found`)}function J(r,e,t){let n=r.getMetrics(e);if(t.minScore!==void 0&&n.healthScore<t.minScore)throw new Error(`Expected agent "${e}" health score to be at least ${t.minScore}, got ${n.healthScore}`);if(t.maxScore!==void 0&&n.healthScore>t.maxScore)throw new Error(`Expected agent "${e}" health score to be at most ${t.maxScore}, got ${n.healthScore}`);if(t.circuitState!==void 0&&n.circuitState!==t.circuitState)throw new Error(`Expected agent "${e}" circuit state to be "${t.circuitState}", got "${n.circuitState}"`);if(t.minSuccessRate!==void 0&&n.successRate<t.minSuccessRate)throw new Error(`Expected agent "${e}" success rate to be at least ${t.minSuccessRate}, got ${n.successRate}`)}function U(r=100){let e=new chunkKALRDVN5_cjs.G({maxCheckpoints:r}),t=[];return {inner:e,saved:t,getLatest:()=>t[t.length-1],async save(n){return t.push(n),e.save(n)},load:n=>e.load(n),list:()=>e.list(),delete:n=>e.delete(n),clear:()=>e.clear(),prune:()=>e.prune()}}function _(r,e){if(e.orchestratorType!==void 0&&r.orchestratorType!==e.orchestratorType)throw new Error(`Expected checkpoint orchestratorType "${e.orchestratorType}", got "${r.orchestratorType}"`);if(e.hasSystemExport===true&&(!r.systemExport||r.systemExport===""))throw new Error("Expected checkpoint to have non-empty systemExport, but it was empty");if(e.hasTimeline===true&&r.timelineExport===null)throw new Error("Expected checkpoint to have timeline export, but it was null");if(e.hasTimeline===false&&r.timelineExport!==null)throw new Error("Expected checkpoint to have no timeline export, but it was present");if(e.hasMemory===true&&r.memoryExport===null)throw new Error("Expected checkpoint to have memory export, but it was null");if(e.hasMemory===false&&r.memoryExport!==null)throw new Error("Expected checkpoint to have no memory export, but it was present");if(e.label!==void 0&&r.label!==e.label)throw new Error(`Expected checkpoint label "${e.label}", got "${r.label}"`)}function V(r={}){let e=[],t=null,n=false;return {handler:s=>{if(e.push(s),!n)throw new Error("[Directive] BreakpointSimulator: handler called but attachTo() was never called. Breakpoints will not be resolved. Call simulator.attachTo(orchestrator) after creation.");let a=r.autoResumeDelay??0,i=()=>{t&&(r.cancel?t.cancelBreakpoint(s.id,r.cancelReason):t.resumeBreakpoint(s.id,r.modifications));};a>0?setTimeout(i,a):queueMicrotask(i);},hits:e,attachTo:s=>{t=s,n=true;}}}function W(r,e){if(e.count!==void 0&&r.length!==e.count)throw new Error(`Expected ${e.count} breakpoint hits, got ${r.length}`);if(e.type&&!r.some(n=>n.type===e.type)){let n=r.map(o=>o.type).join(", ");throw new Error(`Expected breakpoint of type "${e.type}", found types: [${n}]`)}if(e.agentId&&!r.some(n=>n.agentId===e.agentId)){let n=r.map(o=>o.agentId).join(", ");throw new Error(`Expected breakpoint for agent "${e.agentId}", found agents: [${n}]`)}}function z(r,e){return {safeParse:t=>r(t)?{success:true,data:t}:{success:false,error:{message:"Validation failed"}},description:e}}async function K(r){let e=[];for await(let t of r)e.push(t);return e}function Q(r,e){if(e.minChunks!==void 0&&r.length<e.minChunks)throw new Error(`Expected at least ${e.minChunks} chunks, got ${r.length}`);if(e.agentIds){let t=new Set(r.map(n=>n.agentId));for(let n of e.agentIds)if(!t.has(n))throw new Error(`Expected chunks from agent "${n}", found agents: [${[...t].join(", ")}]`)}if(e.hasDone===true&&!r.some(n=>n.chunk.type==="done"))throw new Error("Expected at least one 'done' chunk, found none");if(e.hasErrors===true&&!r.some(n=>n.chunk.type==="error"))throw new Error("Expected at least one 'error' chunk, found none");if(e.hasErrors===false&&r.some(n=>n.chunk.type==="error"))throw new Error("Expected no 'error' chunks, but found some")}function X(r){let e=r?.passAfter??1,t=r?.feedback??"Needs improvement",n=r?.score,o=0;return (s,a)=>{o++;let i=o>=e;return {passed:i,feedback:i?void 0:t,score:n??(i?1:.5)}}}function Y(r,e){let t=r.getAll();for(let[n,o]of Object.entries(e)){let s=t[n];if(s!==o)throw new Error(`Expected scratchpad key "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}}function Z(r,e){let t=r.derived;for(let[n,o]of Object.entries(e)){let s=t[n];if(typeof o=="object"&&o!==null){let a=i=>JSON.stringify(i,Object.keys(i).sort());if(a(s)!==a(o))throw new Error(`Expected derived value "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}else if(s!==o)throw new Error(`Expected derived value "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}}exports.assertAgentHealth=J;exports.assertBreakpointHit=W;exports.assertCheckpoint=_;exports.assertDagExecution=I;exports.assertDerivedValues=Z;exports.assertMultiAgentState=N;exports.assertMultiplexedStream=Q;exports.assertOrchestratorState=M;exports.assertRerouted=L;exports.assertScratchpadState=Y;exports.assertTimelineEvents=F;exports.collectMultiplexedStream=K;exports.createApprovalSimulator=R;exports.createBreakpointSimulator=V;exports.createConstraintRecorder=O;exports.createFailingRunner=H;exports.createMockAgentRunner=b;exports.createMockSchema=z;exports.createMockTask=y;exports.createTestCheckpointStore=U;exports.createTestDag=P;exports.createTestMultiAgentOrchestrator=D;exports.createTestOrchestrator=C;exports.createTestReflectionEvaluator=X;exports.createTestTimeline=B;exports.createTimeController=q;exports.testGuardrail=T;exports.testGuardrailBatch=x;//# sourceMappingURL=testing.cjs.map
|
|
1
|
+
'use strict';var chunkXV2QSBBE_cjs=require('./chunk-XV2QSBBE.cjs'),chunkX3VQ5F7D_cjs=require('./chunk-X3VQ5F7D.cjs');function b(r={}){let{defaultResponse:e={output:"mock response",totalTokens:10},responses:t={},recordCalls:n=true,onRun:o}=r,s=[],a=new Map(Object.entries(t)),i=e;return {run:async(l,c,g)=>{o?.(l,c),n&&s.push({agent:l,input:c,options:g,timestamp:Date.now()});let d=a.get(l.name)??i;if(d.generate){let p=d.generate(c,l);d={...d,...p};}if(d.error)throw d.error;d.delay&&d.delay>0&&await new Promise(p=>setTimeout(p,d.delay));let f=d.messages??[];for(let p of f)g?.onMessage?.(p);let m=d.toolCalls??[];for(let p of m)g?.onToolCall?.(p);return {output:d.output,messages:f,toolCalls:m,totalTokens:d.totalTokens??10}},getCalls:()=>[...s],getCallsFor:l=>s.filter(c=>c.agent.name===l),clearCalls:()=>s.length=0,setResponse:(l,c)=>a.set(l,c),setDefaultResponse:l=>i=l}}async function T(r,e,t){let n={agentName:"test-agent",input:"",...e},o={agentName:e.agentName??"test-agent",input:e.input??"",facts:t?.facts??{},...t},s=Date.now(),a=await r(n,o),i=Date.now()-s;return {...a,duration:i,testedData:n,assertPassed(){if(!a.passed)throw new Error(`Expected guardrail to pass, but it failed: ${a.reason}`)},assertFailed(u){if(a.passed)throw new Error("Expected guardrail to fail, but it passed");if(u!==void 0){if(typeof u=="string"&&!a.reason?.includes(u))throw new Error(`Expected failure reason to include "${u}", got: ${a.reason}`);if(u instanceof RegExp&&!u.test(a.reason??""))throw new Error(`Expected failure reason to match ${u}, got: ${a.reason}`)}},assertTransformed(u){if(a.transformed===void 0)throw new Error("Expected guardrail to transform input, but no transformation occurred");if(u!==void 0&&a.transformed!==u)throw new Error(`Expected transformation to be ${JSON.stringify(u)}, got: ${JSON.stringify(a.transformed)}`)}}}async function x(r,e){let t=[],n=[];for(let o=0;o<e.length;o++){let s=e[o],a=await T(r,s.input,s.context);t.push(a),(a.passed?a.transformed!==void 0?"transform":"pass":"fail")!==s.expect&&n.push({index:o,expected:s.expect,actual:a});}return {results:t,allPassed:()=>n.length===0,failures:()=>n}}function R(r={}){let{autoApprove:e,autoReject:t,delay:n=0,recordRequests:o=true}=r,s=[],a=new Map,i=[];return {async handle(u){o&&s.push(u);for(let l=i.length-1;l>=0;l--){let c=i[l];c.predicate(u)&&(i.splice(l,1),c.resolve(u));}return n>0&&await new Promise(l=>setTimeout(l,n)),t&&t(u)?"rejected":e?.(u)?"approved":new Promise(l=>{a.set(u.id,{request:u,resolve:l});})},getRequests:()=>[...s],clearRequests:()=>s.length=0,approve(u){let l=a.get(u);l&&(l.resolve("approved"),a.delete(u));},reject(u,l){let c=a.get(u);if(c){c.resolve("rejected"),a.delete(u);let g=s.find(d=>d.id===u);g&&(g.rejectionReason=l);}},waitForRequest(u,l=5e3){let c=s.find(u);return c?Promise.resolve(c):new Promise((g,d)=>{let f={predicate:u,resolve:p=>{clearTimeout(m),g(p);}},m=setTimeout(()=>{let p=i.indexOf(f);p>=0&&i.splice(p,1),d(new Error("Timeout waiting for approval request"));},l);i.push(f);})}}}function C(r={}){let{mockResponses:e,defaultMockResponse:t,...n}=r,o=b({responses:e,defaultResponse:t}),s=R(),a=chunkXV2QSBBE_cjs.a({...n,runner:o.run,onApprovalRequest:u=>{s.handle(u),n.onApprovalRequest?.(u);}}),i=Object.create(a);return i.mockRunner=o,i.approvalSimulator=s,i.getCalls=()=>o.getCalls(),i.getApprovalRequests=()=>s.getRequests(),i.resetAll=()=>{a.reset(),o.clearCalls(),s.clearRequests();},i}function O(){let r=[];return {plugin:{name:"constraint-recorder",onRequirementCreated(e){r.push({constraintId:e.constraintId,triggered:true,requirement:e.requirement,facts:e.facts,timestamp:Date.now()});}},getSnapshots:()=>[...r],clearSnapshots:()=>r.length=0}}function M(r,e){let t=r.facts;if(e.agentStatus!==void 0&&t.agent.status!==e.agentStatus)throw new Error(`Expected agent status to be "${e.agentStatus}", got "${t.agent.status}"`);if(e.tokenUsage!==void 0){let{min:n,max:o,exact:s}=e.tokenUsage;if(s!==void 0&&t.agent.tokenUsage!==s)throw new Error(`Expected token usage to be exactly ${s}, got ${t.agent.tokenUsage}`);if(n!==void 0&&t.agent.tokenUsage<n)throw new Error(`Expected token usage to be at least ${n}, got ${t.agent.tokenUsage}`);if(o!==void 0&&t.agent.tokenUsage>o)throw new Error(`Expected token usage to be at most ${o}, got ${t.agent.tokenUsage}`)}if(e.pendingApprovals!==void 0&&t.approval.pending.length!==e.pendingApprovals)throw new Error(`Expected ${e.pendingApprovals} pending approvals, got ${t.approval.pending.length}`);if(e.conversationLength!==void 0){let{min:n,max:o,exact:s}=e.conversationLength,a=t.conversation.length;if(s!==void 0&&a!==s)throw new Error(`Expected conversation length to be exactly ${s}, got ${a}`);if(n!==void 0&&a<n)throw new Error(`Expected conversation length to be at least ${n}, got ${a}`);if(o!==void 0&&a>o)throw new Error(`Expected conversation length to be at most ${o}, got ${a}`)}}function q(r=Date.now()){let e=r,t=r;return {now:()=>e,advance:n=>{e+=n;},set:n=>{e=n;},reset:()=>{e=t;}}}function D(r){let{mockResponses:e={},defaultMockResponse:t,mockTasks:n,...o}=r;if(n){let c=o.tasks??{};for(let[g,d]of Object.entries(n))c[g]||(c[g]=y(d.output,{delay:d.delay,shouldError:d.shouldError}));o.tasks=c;}let s={};for(let[c,g]of Object.entries(e)){let d=o.agents[c];d&&(s[d.agent.name]=g);}let a=b({responses:s,defaultResponse:t}),i=R(),u=chunkX3VQ5F7D_cjs.Da({...o,runner:a.run,onApprovalRequest:c=>{i.handle(c),o.onApprovalRequest?.(c);}}),l=Object.create(u);return l.mockRunner=a,l.approvalSimulator=i,l.getCalls=()=>a.getCalls(),l.getApprovalRequests=()=>i.getRequests(),l.resetAll=()=>{u.reset(),a.clearCalls(),i.clearRequests();},l}function N(r,e){if(e.taskStatus)for(let[t,n]of Object.entries(e.taskStatus)){let o=r.getTaskState(t);if(!o)throw new Error(`Expected task "${t}" to exist, but it was not found`);if(o.status!==n)throw new Error(`Expected task "${t}" status to be "${n}", got "${o.status}"`)}if(e.agentStatus)for(let[t,n]of Object.entries(e.agentStatus)){let o=r.getAgentState(t);if(!o)throw new Error(`Expected agent "${t}" to exist, but it was not found`);if(o.status!==n)throw new Error(`Expected agent "${t}" status to be "${n}", got "${o.status}"`)}if(e.totalTokens){let{agentId:t,min:n,max:o}=e.totalTokens;if(t){let s=r.getAgentState(t);if(!s)throw new Error(`Expected agent "${t}" to exist, but it was not found`);if(n!==void 0&&s.totalTokens<n)throw new Error(`Expected agent "${t}" tokens to be at least ${n}, got ${s.totalTokens}`);if(o!==void 0&&s.totalTokens>o)throw new Error(`Expected agent "${t}" tokens to be at most ${o}, got ${s.totalTokens}`)}else {let s=r.getAllAgentStates(),a=Object.values(s).reduce((i,u)=>i+u.totalTokens,0);if(n!==void 0&&a<n)throw new Error(`Expected total tokens to be at least ${n}, got ${a}`);if(o!==void 0&&a>o)throw new Error(`Expected total tokens to be at most ${o}, got ${a}`)}}if(e.globalTokens){let{min:t,max:n}=e.globalTokens,o=r.totalTokens;if(t!==void 0&&o<t)throw new Error(`Expected global tokens to be at least ${t}, got ${o}`);if(n!==void 0&&o>n)throw new Error(`Expected global tokens to be at most ${n}, got ${o}`)}if(e.pendingHandoffs!==void 0){let t=r.getPendingHandoffs().length;if(t!==e.pendingHandoffs)throw new Error(`Expected ${e.pendingHandoffs} pending handoffs, got ${t}`)}}function y(r,e){return {run:async(t,n)=>{if(n.aborted)throw new Error("Task aborted");if(e?.delay&&e.delay>0&&await new Promise((o,s)=>{let a=setTimeout(o,e.delay);n.addEventListener("abort",()=>{clearTimeout(a),s(new Error("Task aborted"));},{once:true});}),e?.shouldError)throw new Error("Mock task error");return r},label:e?.label??"Mock Task",description:e?.description}}function P(r,e,t){return chunkX3VQ5F7D_cjs.ga(r,e??(o=>o.outputs),t)}function I(r,e){if(e.nodeStatuses)for(let[t,n]of Object.entries(e.nodeStatuses)){let o=r.statuses[t];if(o!==n)throw new Error(`Expected node "${t}" status to be "${n}", got "${o}"`)}if(e.completedNodes){for(let t of e.completedNodes)if(r.statuses[t]!=="completed")throw new Error(`Expected node "${t}" to be completed, got "${r.statuses[t]}"`)}if(e.skippedNodes){for(let t of e.skippedNodes)if(r.statuses[t]!=="skipped")throw new Error(`Expected node "${t}" to be skipped, got "${r.statuses[t]}"`)}if(e.errorNodes){for(let t of e.errorNodes)if(r.statuses[t]!=="error")throw new Error(`Expected node "${t}" to be error, got "${r.statuses[t]}"`)}if(e.outputContains)for(let[t,n]of Object.entries(e.outputContains)){let o=r.outputs[t];if(o!==n)throw new Error(`Expected node "${t}" output to be ${JSON.stringify(n)}, got ${JSON.stringify(o)}`)}}function B(r,e){let t=chunkX3VQ5F7D_cjs.i({maxEvents:e?.maxEvents??500});if(r)for(let n of r)t.record({timestamp:Date.now(),snapshotId:null,agentId:"",...n});return t}function F(r,e){let t=r.getEvents();if(e.totalEvents!==void 0&&t.length!==e.totalEvents)throw new Error(`Expected ${e.totalEvents} timeline events, got ${t.length}`);if(e.minEvents!==void 0&&t.length<e.minEvents)throw new Error(`Expected at least ${e.minEvents} timeline events, got ${t.length}`);if(e.maxEvents!==void 0&&t.length>e.maxEvents)throw new Error(`Expected at most ${e.maxEvents} timeline events, got ${t.length}`);if(e.eventTypes){for(let n of e.eventTypes)if(!t.some(s=>s.type===n))throw new Error(`Expected timeline to contain event of type "${n}", but none found`)}if(e.agentEvents)for(let[n,o]of Object.entries(e.agentEvents)){let s=r.getEventsForAgent(n).length;if(s!==o)throw new Error(`Expected ${o} events for agent "${n}", got ${s}`)}if(e.hasType&&!t.some(o=>o.type===e.hasType))throw new Error(`Expected timeline to contain event of type "${e.hasType}"`);if(e.doesNotHaveType&&t.some(o=>o.type===e.doesNotHaveType))throw new Error(`Expected timeline NOT to contain event of type "${e.doesNotHaveType}"`)}function H(r,e){let t=0,n=e?.failAfter??0;return async(o,s,a)=>{if(t++,n>0&&t<=n)return {output:"success",messages:[],toolCalls:[],totalTokens:10};throw e?.delay&&e.delay>0&&await new Promise(i=>setTimeout(i,e.delay)),r??new Error("Runner failed")}}function L(r,e){if(r.length===0)throw new Error("Expected at least one reroute event, but none occurred");if(e.minReroutes!==void 0&&r.length<e.minReroutes)throw new Error(`Expected at least ${e.minReroutes} reroute events, got ${r.length}`);if(e.fromAgent&&!r.some(n=>n.originalAgent===e.fromAgent))throw new Error(`Expected reroute from agent "${e.fromAgent}", but no matching event found`);if(e.toAgent&&!r.some(n=>n.reroutedTo===e.toAgent))throw new Error(`Expected reroute to agent "${e.toAgent}", but no matching event found`);if(e.reason&&!r.some(n=>typeof e.reason=="string"?n.reason.includes(e.reason):e.reason.test(n.reason)))throw new Error(`Expected reroute reason matching ${e.reason}, but no matching event found`)}function J(r,e,t){let n=r.getMetrics(e);if(t.minScore!==void 0&&n.healthScore<t.minScore)throw new Error(`Expected agent "${e}" health score to be at least ${t.minScore}, got ${n.healthScore}`);if(t.maxScore!==void 0&&n.healthScore>t.maxScore)throw new Error(`Expected agent "${e}" health score to be at most ${t.maxScore}, got ${n.healthScore}`);if(t.circuitState!==void 0&&n.circuitState!==t.circuitState)throw new Error(`Expected agent "${e}" circuit state to be "${t.circuitState}", got "${n.circuitState}"`);if(t.minSuccessRate!==void 0&&n.successRate<t.minSuccessRate)throw new Error(`Expected agent "${e}" success rate to be at least ${t.minSuccessRate}, got ${n.successRate}`)}function U(r=100){let e=new chunkX3VQ5F7D_cjs.G({maxCheckpoints:r}),t=[];return {inner:e,saved:t,getLatest:()=>t[t.length-1],async save(n){return t.push(n),e.save(n)},load:n=>e.load(n),list:()=>e.list(),delete:n=>e.delete(n),clear:()=>e.clear(),prune:()=>e.prune()}}function _(r,e){if(e.orchestratorType!==void 0&&r.orchestratorType!==e.orchestratorType)throw new Error(`Expected checkpoint orchestratorType "${e.orchestratorType}", got "${r.orchestratorType}"`);if(e.hasSystemExport===true&&(!r.systemExport||r.systemExport===""))throw new Error("Expected checkpoint to have non-empty systemExport, but it was empty");if(e.hasTimeline===true&&r.timelineExport===null)throw new Error("Expected checkpoint to have timeline export, but it was null");if(e.hasTimeline===false&&r.timelineExport!==null)throw new Error("Expected checkpoint to have no timeline export, but it was present");if(e.hasMemory===true&&r.memoryExport===null)throw new Error("Expected checkpoint to have memory export, but it was null");if(e.hasMemory===false&&r.memoryExport!==null)throw new Error("Expected checkpoint to have no memory export, but it was present");if(e.label!==void 0&&r.label!==e.label)throw new Error(`Expected checkpoint label "${e.label}", got "${r.label}"`)}function V(r={}){let e=[],t=null,n=false;return {handler:s=>{if(e.push(s),!n)throw new Error("[Directive] BreakpointSimulator: handler called but attachTo() was never called. Breakpoints will not be resolved. Call simulator.attachTo(orchestrator) after creation.");let a=r.autoResumeDelay??0,i=()=>{t&&(r.cancel?t.cancelBreakpoint(s.id,r.cancelReason):t.resumeBreakpoint(s.id,r.modifications));};a>0?setTimeout(i,a):queueMicrotask(i);},hits:e,attachTo:s=>{t=s,n=true;}}}function W(r,e){if(e.count!==void 0&&r.length!==e.count)throw new Error(`Expected ${e.count} breakpoint hits, got ${r.length}`);if(e.type&&!r.some(n=>n.type===e.type)){let n=r.map(o=>o.type).join(", ");throw new Error(`Expected breakpoint of type "${e.type}", found types: [${n}]`)}if(e.agentId&&!r.some(n=>n.agentId===e.agentId)){let n=r.map(o=>o.agentId).join(", ");throw new Error(`Expected breakpoint for agent "${e.agentId}", found agents: [${n}]`)}}function z(r,e){return {safeParse:t=>r(t)?{success:true,data:t}:{success:false,error:{message:"Validation failed"}},description:e}}async function K(r){let e=[];for await(let t of r)e.push(t);return e}function Q(r,e){if(e.minChunks!==void 0&&r.length<e.minChunks)throw new Error(`Expected at least ${e.minChunks} chunks, got ${r.length}`);if(e.agentIds){let t=new Set(r.map(n=>n.agentId));for(let n of e.agentIds)if(!t.has(n))throw new Error(`Expected chunks from agent "${n}", found agents: [${[...t].join(", ")}]`)}if(e.hasDone===true&&!r.some(n=>n.chunk.type==="done"))throw new Error("Expected at least one 'done' chunk, found none");if(e.hasErrors===true&&!r.some(n=>n.chunk.type==="error"))throw new Error("Expected at least one 'error' chunk, found none");if(e.hasErrors===false&&r.some(n=>n.chunk.type==="error"))throw new Error("Expected no 'error' chunks, but found some")}function X(r){let e=r?.passAfter??1,t=r?.feedback??"Needs improvement",n=r?.score,o=0;return (s,a)=>{o++;let i=o>=e;return {passed:i,feedback:i?void 0:t,score:n??(i?1:.5)}}}function Y(r,e){let t=r.getAll();for(let[n,o]of Object.entries(e)){let s=t[n];if(s!==o)throw new Error(`Expected scratchpad key "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}}function Z(r,e){let t=r.derived;for(let[n,o]of Object.entries(e)){let s=t[n];if(typeof o=="object"&&o!==null){let a=i=>JSON.stringify(i,Object.keys(i).sort());if(a(s)!==a(o))throw new Error(`Expected derived value "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}else if(s!==o)throw new Error(`Expected derived value "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}}exports.assertAgentHealth=J;exports.assertBreakpointHit=W;exports.assertCheckpoint=_;exports.assertDagExecution=I;exports.assertDerivedValues=Z;exports.assertMultiAgentState=N;exports.assertMultiplexedStream=Q;exports.assertOrchestratorState=M;exports.assertRerouted=L;exports.assertScratchpadState=Y;exports.assertTimelineEvents=F;exports.collectMultiplexedStream=K;exports.createApprovalSimulator=R;exports.createBreakpointSimulator=V;exports.createConstraintRecorder=O;exports.createFailingRunner=H;exports.createMockAgentRunner=b;exports.createMockSchema=z;exports.createMockTask=y;exports.createTestCheckpointStore=U;exports.createTestDag=P;exports.createTestMultiAgentOrchestrator=D;exports.createTestOrchestrator=C;exports.createTestReflectionEvaluator=X;exports.createTestTimeline=B;exports.createTimeController=q;exports.testGuardrail=T;exports.testGuardrailBatch=x;//# sourceMappingURL=testing.cjs.map
|
|
2
2
|
//# sourceMappingURL=testing.cjs.map
|
package/dist/testing.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as MultiAgentOrchestrator, M as MultiAgentOrchestratorOptions, l as AgentOrchestrator, O as OrchestratorOptions, H as HealthMonitor, K as MultiplexedStreamChunk, i as DebugTimeline, aa as TaskRegistration, Y as ReflectionEvaluator } from './orchestrator-types-
|
|
1
|
+
import { a as MultiAgentOrchestrator, M as MultiAgentOrchestratorOptions, l as AgentOrchestrator, O as OrchestratorOptions, H as HealthMonitor, K as MultiplexedStreamChunk, i as DebugTimeline, aa as TaskRegistration, Y as ReflectionEvaluator } from './orchestrator-types-Bh8r3_Sq.cjs';
|
|
2
2
|
import { z as ApprovalRequest, L as BreakpointModifications, I as InputGuardrailData, O as OutputGuardrailData, M as Message, T as ToolCallGuardrailData, b2 as ToolCall, ah as GuardrailResult, A as AgentLike, b as AgentRunner, p as RunOptions, N as BreakpointRequest, W as Checkpoint, h as DagExecutionContext, a3 as DagNodeStatus, aN as RerouteEvent, aS as Scratchpad, a8 as DebugEventType, e as CheckpointStore, an as InMemoryCheckpointStore, D as DagNode, i as DagPattern, q as DebugEvent, G as GuardrailFn, ae as GuardrailContext } from './types-CRmwFnVk.cjs';
|
|
3
3
|
import '@directive-run/core';
|
|
4
4
|
import '@directive-run/core/plugins';
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as MultiAgentOrchestrator, M as MultiAgentOrchestratorOptions, l as AgentOrchestrator, O as OrchestratorOptions, H as HealthMonitor, K as MultiplexedStreamChunk, i as DebugTimeline, aa as TaskRegistration, Y as ReflectionEvaluator } from './orchestrator-types-
|
|
1
|
+
import { a as MultiAgentOrchestrator, M as MultiAgentOrchestratorOptions, l as AgentOrchestrator, O as OrchestratorOptions, H as HealthMonitor, K as MultiplexedStreamChunk, i as DebugTimeline, aa as TaskRegistration, Y as ReflectionEvaluator } from './orchestrator-types-CTfIKk0W.js';
|
|
2
2
|
import { z as ApprovalRequest, L as BreakpointModifications, I as InputGuardrailData, O as OutputGuardrailData, M as Message, T as ToolCallGuardrailData, b2 as ToolCall, ah as GuardrailResult, A as AgentLike, b as AgentRunner, p as RunOptions, N as BreakpointRequest, W as Checkpoint, h as DagExecutionContext, a3 as DagNodeStatus, aN as RerouteEvent, aS as Scratchpad, a8 as DebugEventType, e as CheckpointStore, an as InMemoryCheckpointStore, D as DagNode, i as DagPattern, q as DebugEvent, G as GuardrailFn, ae as GuardrailContext } from './types-CRmwFnVk.js';
|
|
3
3
|
import '@directive-run/core';
|
|
4
4
|
import '@directive-run/core/plugins';
|
package/dist/testing.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-5ERCL33C.js';import {Da,ga,i,G}from'./chunk-K2LZMRLN.js';function b(r={}){let{defaultResponse:e={output:"mock response",totalTokens:10},responses:t={},recordCalls:n=true,onRun:o}=r,s=[],a=new Map(Object.entries(t)),i=e;return {run:async(l,c,g)=>{o?.(l,c),n&&s.push({agent:l,input:c,options:g,timestamp:Date.now()});let d=a.get(l.name)??i;if(d.generate){let p=d.generate(c,l);d={...d,...p};}if(d.error)throw d.error;d.delay&&d.delay>0&&await new Promise(p=>setTimeout(p,d.delay));let f=d.messages??[];for(let p of f)g?.onMessage?.(p);let m=d.toolCalls??[];for(let p of m)g?.onToolCall?.(p);return {output:d.output,messages:f,toolCalls:m,totalTokens:d.totalTokens??10}},getCalls:()=>[...s],getCallsFor:l=>s.filter(c=>c.agent.name===l),clearCalls:()=>s.length=0,setResponse:(l,c)=>a.set(l,c),setDefaultResponse:l=>i=l}}async function T(r,e,t){let n={agentName:"test-agent",input:"",...e},o={agentName:e.agentName??"test-agent",input:e.input??"",facts:t?.facts??{},...t},s=Date.now(),a=await r(n,o),i=Date.now()-s;return {...a,duration:i,testedData:n,assertPassed(){if(!a.passed)throw new Error(`Expected guardrail to pass, but it failed: ${a.reason}`)},assertFailed(u){if(a.passed)throw new Error("Expected guardrail to fail, but it passed");if(u!==void 0){if(typeof u=="string"&&!a.reason?.includes(u))throw new Error(`Expected failure reason to include "${u}", got: ${a.reason}`);if(u instanceof RegExp&&!u.test(a.reason??""))throw new Error(`Expected failure reason to match ${u}, got: ${a.reason}`)}},assertTransformed(u){if(a.transformed===void 0)throw new Error("Expected guardrail to transform input, but no transformation occurred");if(u!==void 0&&a.transformed!==u)throw new Error(`Expected transformation to be ${JSON.stringify(u)}, got: ${JSON.stringify(a.transformed)}`)}}}async function x(r,e){let t=[],n=[];for(let o=0;o<e.length;o++){let s=e[o],a=await T(r,s.input,s.context);t.push(a),(a.passed?a.transformed!==void 0?"transform":"pass":"fail")!==s.expect&&n.push({index:o,expected:s.expect,actual:a});}return {results:t,allPassed:()=>n.length===0,failures:()=>n}}function R(r={}){let{autoApprove:e,autoReject:t,delay:n=0,recordRequests:o=true}=r,s=[],a=new Map,i=[];return {async handle(u){o&&s.push(u);for(let l=i.length-1;l>=0;l--){let c=i[l];c.predicate(u)&&(i.splice(l,1),c.resolve(u));}return n>0&&await new Promise(l=>setTimeout(l,n)),t&&t(u)?"rejected":e?.(u)?"approved":new Promise(l=>{a.set(u.id,{request:u,resolve:l});})},getRequests:()=>[...s],clearRequests:()=>s.length=0,approve(u){let l=a.get(u);l&&(l.resolve("approved"),a.delete(u));},reject(u,l){let c=a.get(u);if(c){c.resolve("rejected"),a.delete(u);let g=s.find(d=>d.id===u);g&&(g.rejectionReason=l);}},waitForRequest(u,l=5e3){let c=s.find(u);return c?Promise.resolve(c):new Promise((g,d)=>{let f={predicate:u,resolve:p=>{clearTimeout(m),g(p);}},m=setTimeout(()=>{let p=i.indexOf(f);p>=0&&i.splice(p,1),d(new Error("Timeout waiting for approval request"));},l);i.push(f);})}}}function C(r={}){let{mockResponses:e,defaultMockResponse:t,...n}=r,o=b({responses:e,defaultResponse:t}),s=R(),a$1=a({...n,runner:o.run,onApprovalRequest:u=>{s.handle(u),n.onApprovalRequest?.(u);}}),i=Object.create(a$1);return i.mockRunner=o,i.approvalSimulator=s,i.getCalls=()=>o.getCalls(),i.getApprovalRequests=()=>s.getRequests(),i.resetAll=()=>{a$1.reset(),o.clearCalls(),s.clearRequests();},i}function O(){let r=[];return {plugin:{name:"constraint-recorder",onRequirementCreated(e){r.push({constraintId:e.constraintId,triggered:true,requirement:e.requirement,facts:e.facts,timestamp:Date.now()});}},getSnapshots:()=>[...r],clearSnapshots:()=>r.length=0}}function M(r,e){let t=r.facts;if(e.agentStatus!==void 0&&t.agent.status!==e.agentStatus)throw new Error(`Expected agent status to be "${e.agentStatus}", got "${t.agent.status}"`);if(e.tokenUsage!==void 0){let{min:n,max:o,exact:s}=e.tokenUsage;if(s!==void 0&&t.agent.tokenUsage!==s)throw new Error(`Expected token usage to be exactly ${s}, got ${t.agent.tokenUsage}`);if(n!==void 0&&t.agent.tokenUsage<n)throw new Error(`Expected token usage to be at least ${n}, got ${t.agent.tokenUsage}`);if(o!==void 0&&t.agent.tokenUsage>o)throw new Error(`Expected token usage to be at most ${o}, got ${t.agent.tokenUsage}`)}if(e.pendingApprovals!==void 0&&t.approval.pending.length!==e.pendingApprovals)throw new Error(`Expected ${e.pendingApprovals} pending approvals, got ${t.approval.pending.length}`);if(e.conversationLength!==void 0){let{min:n,max:o,exact:s}=e.conversationLength,a=t.conversation.length;if(s!==void 0&&a!==s)throw new Error(`Expected conversation length to be exactly ${s}, got ${a}`);if(n!==void 0&&a<n)throw new Error(`Expected conversation length to be at least ${n}, got ${a}`);if(o!==void 0&&a>o)throw new Error(`Expected conversation length to be at most ${o}, got ${a}`)}}function q(r=Date.now()){let e=r,t=r;return {now:()=>e,advance:n=>{e+=n;},set:n=>{e=n;},reset:()=>{e=t;}}}function D(r){let{mockResponses:e={},defaultMockResponse:t,mockTasks:n,...o}=r;if(n){let c=o.tasks??{};for(let[g,d]of Object.entries(n))c[g]||(c[g]=y(d.output,{delay:d.delay,shouldError:d.shouldError}));o.tasks=c;}let s={};for(let[c,g]of Object.entries(e)){let d=o.agents[c];d&&(s[d.agent.name]=g);}let a=b({responses:s,defaultResponse:t}),i=R(),u=Da({...o,runner:a.run,onApprovalRequest:c=>{i.handle(c),o.onApprovalRequest?.(c);}}),l=Object.create(u);return l.mockRunner=a,l.approvalSimulator=i,l.getCalls=()=>a.getCalls(),l.getApprovalRequests=()=>i.getRequests(),l.resetAll=()=>{u.reset(),a.clearCalls(),i.clearRequests();},l}function N(r,e){if(e.taskStatus)for(let[t,n]of Object.entries(e.taskStatus)){let o=r.getTaskState(t);if(!o)throw new Error(`Expected task "${t}" to exist, but it was not found`);if(o.status!==n)throw new Error(`Expected task "${t}" status to be "${n}", got "${o.status}"`)}if(e.agentStatus)for(let[t,n]of Object.entries(e.agentStatus)){let o=r.getAgentState(t);if(!o)throw new Error(`Expected agent "${t}" to exist, but it was not found`);if(o.status!==n)throw new Error(`Expected agent "${t}" status to be "${n}", got "${o.status}"`)}if(e.totalTokens){let{agentId:t,min:n,max:o}=e.totalTokens;if(t){let s=r.getAgentState(t);if(!s)throw new Error(`Expected agent "${t}" to exist, but it was not found`);if(n!==void 0&&s.totalTokens<n)throw new Error(`Expected agent "${t}" tokens to be at least ${n}, got ${s.totalTokens}`);if(o!==void 0&&s.totalTokens>o)throw new Error(`Expected agent "${t}" tokens to be at most ${o}, got ${s.totalTokens}`)}else {let s=r.getAllAgentStates(),a=Object.values(s).reduce((i,u)=>i+u.totalTokens,0);if(n!==void 0&&a<n)throw new Error(`Expected total tokens to be at least ${n}, got ${a}`);if(o!==void 0&&a>o)throw new Error(`Expected total tokens to be at most ${o}, got ${a}`)}}if(e.globalTokens){let{min:t,max:n}=e.globalTokens,o=r.totalTokens;if(t!==void 0&&o<t)throw new Error(`Expected global tokens to be at least ${t}, got ${o}`);if(n!==void 0&&o>n)throw new Error(`Expected global tokens to be at most ${n}, got ${o}`)}if(e.pendingHandoffs!==void 0){let t=r.getPendingHandoffs().length;if(t!==e.pendingHandoffs)throw new Error(`Expected ${e.pendingHandoffs} pending handoffs, got ${t}`)}}function y(r,e){return {run:async(t,n)=>{if(n.aborted)throw new Error("Task aborted");if(e?.delay&&e.delay>0&&await new Promise((o,s)=>{let a=setTimeout(o,e.delay);n.addEventListener("abort",()=>{clearTimeout(a),s(new Error("Task aborted"));},{once:true});}),e?.shouldError)throw new Error("Mock task error");return r},label:e?.label??"Mock Task",description:e?.description}}function P(r,e,t){return ga(r,e??(o=>o.outputs),t)}function I(r,e){if(e.nodeStatuses)for(let[t,n]of Object.entries(e.nodeStatuses)){let o=r.statuses[t];if(o!==n)throw new Error(`Expected node "${t}" status to be "${n}", got "${o}"`)}if(e.completedNodes){for(let t of e.completedNodes)if(r.statuses[t]!=="completed")throw new Error(`Expected node "${t}" to be completed, got "${r.statuses[t]}"`)}if(e.skippedNodes){for(let t of e.skippedNodes)if(r.statuses[t]!=="skipped")throw new Error(`Expected node "${t}" to be skipped, got "${r.statuses[t]}"`)}if(e.errorNodes){for(let t of e.errorNodes)if(r.statuses[t]!=="error")throw new Error(`Expected node "${t}" to be error, got "${r.statuses[t]}"`)}if(e.outputContains)for(let[t,n]of Object.entries(e.outputContains)){let o=r.outputs[t];if(o!==n)throw new Error(`Expected node "${t}" output to be ${JSON.stringify(n)}, got ${JSON.stringify(o)}`)}}function B(r,e){let t=i({maxEvents:e?.maxEvents??500});if(r)for(let n of r)t.record({timestamp:Date.now(),snapshotId:null,agentId:"",...n});return t}function F(r,e){let t=r.getEvents();if(e.totalEvents!==void 0&&t.length!==e.totalEvents)throw new Error(`Expected ${e.totalEvents} timeline events, got ${t.length}`);if(e.minEvents!==void 0&&t.length<e.minEvents)throw new Error(`Expected at least ${e.minEvents} timeline events, got ${t.length}`);if(e.maxEvents!==void 0&&t.length>e.maxEvents)throw new Error(`Expected at most ${e.maxEvents} timeline events, got ${t.length}`);if(e.eventTypes){for(let n of e.eventTypes)if(!t.some(s=>s.type===n))throw new Error(`Expected timeline to contain event of type "${n}", but none found`)}if(e.agentEvents)for(let[n,o]of Object.entries(e.agentEvents)){let s=r.getEventsForAgent(n).length;if(s!==o)throw new Error(`Expected ${o} events for agent "${n}", got ${s}`)}if(e.hasType&&!t.some(o=>o.type===e.hasType))throw new Error(`Expected timeline to contain event of type "${e.hasType}"`);if(e.doesNotHaveType&&t.some(o=>o.type===e.doesNotHaveType))throw new Error(`Expected timeline NOT to contain event of type "${e.doesNotHaveType}"`)}function H(r,e){let t=0,n=e?.failAfter??0;return async(o,s,a)=>{if(t++,n>0&&t<=n)return {output:"success",messages:[],toolCalls:[],totalTokens:10};throw e?.delay&&e.delay>0&&await new Promise(i=>setTimeout(i,e.delay)),r??new Error("Runner failed")}}function L(r,e){if(r.length===0)throw new Error("Expected at least one reroute event, but none occurred");if(e.minReroutes!==void 0&&r.length<e.minReroutes)throw new Error(`Expected at least ${e.minReroutes} reroute events, got ${r.length}`);if(e.fromAgent&&!r.some(n=>n.originalAgent===e.fromAgent))throw new Error(`Expected reroute from agent "${e.fromAgent}", but no matching event found`);if(e.toAgent&&!r.some(n=>n.reroutedTo===e.toAgent))throw new Error(`Expected reroute to agent "${e.toAgent}", but no matching event found`);if(e.reason&&!r.some(n=>typeof e.reason=="string"?n.reason.includes(e.reason):e.reason.test(n.reason)))throw new Error(`Expected reroute reason matching ${e.reason}, but no matching event found`)}function J(r,e,t){let n=r.getMetrics(e);if(t.minScore!==void 0&&n.healthScore<t.minScore)throw new Error(`Expected agent "${e}" health score to be at least ${t.minScore}, got ${n.healthScore}`);if(t.maxScore!==void 0&&n.healthScore>t.maxScore)throw new Error(`Expected agent "${e}" health score to be at most ${t.maxScore}, got ${n.healthScore}`);if(t.circuitState!==void 0&&n.circuitState!==t.circuitState)throw new Error(`Expected agent "${e}" circuit state to be "${t.circuitState}", got "${n.circuitState}"`);if(t.minSuccessRate!==void 0&&n.successRate<t.minSuccessRate)throw new Error(`Expected agent "${e}" success rate to be at least ${t.minSuccessRate}, got ${n.successRate}`)}function U(r=100){let e=new G({maxCheckpoints:r}),t=[];return {inner:e,saved:t,getLatest:()=>t[t.length-1],async save(n){return t.push(n),e.save(n)},load:n=>e.load(n),list:()=>e.list(),delete:n=>e.delete(n),clear:()=>e.clear(),prune:()=>e.prune()}}function _(r,e){if(e.orchestratorType!==void 0&&r.orchestratorType!==e.orchestratorType)throw new Error(`Expected checkpoint orchestratorType "${e.orchestratorType}", got "${r.orchestratorType}"`);if(e.hasSystemExport===true&&(!r.systemExport||r.systemExport===""))throw new Error("Expected checkpoint to have non-empty systemExport, but it was empty");if(e.hasTimeline===true&&r.timelineExport===null)throw new Error("Expected checkpoint to have timeline export, but it was null");if(e.hasTimeline===false&&r.timelineExport!==null)throw new Error("Expected checkpoint to have no timeline export, but it was present");if(e.hasMemory===true&&r.memoryExport===null)throw new Error("Expected checkpoint to have memory export, but it was null");if(e.hasMemory===false&&r.memoryExport!==null)throw new Error("Expected checkpoint to have no memory export, but it was present");if(e.label!==void 0&&r.label!==e.label)throw new Error(`Expected checkpoint label "${e.label}", got "${r.label}"`)}function V(r={}){let e=[],t=null,n=false;return {handler:s=>{if(e.push(s),!n)throw new Error("[Directive] BreakpointSimulator: handler called but attachTo() was never called. Breakpoints will not be resolved. Call simulator.attachTo(orchestrator) after creation.");let a=r.autoResumeDelay??0,i=()=>{t&&(r.cancel?t.cancelBreakpoint(s.id,r.cancelReason):t.resumeBreakpoint(s.id,r.modifications));};a>0?setTimeout(i,a):queueMicrotask(i);},hits:e,attachTo:s=>{t=s,n=true;}}}function W(r,e){if(e.count!==void 0&&r.length!==e.count)throw new Error(`Expected ${e.count} breakpoint hits, got ${r.length}`);if(e.type&&!r.some(n=>n.type===e.type)){let n=r.map(o=>o.type).join(", ");throw new Error(`Expected breakpoint of type "${e.type}", found types: [${n}]`)}if(e.agentId&&!r.some(n=>n.agentId===e.agentId)){let n=r.map(o=>o.agentId).join(", ");throw new Error(`Expected breakpoint for agent "${e.agentId}", found agents: [${n}]`)}}function z(r,e){return {safeParse:t=>r(t)?{success:true,data:t}:{success:false,error:{message:"Validation failed"}},description:e}}async function K(r){let e=[];for await(let t of r)e.push(t);return e}function Q(r,e){if(e.minChunks!==void 0&&r.length<e.minChunks)throw new Error(`Expected at least ${e.minChunks} chunks, got ${r.length}`);if(e.agentIds){let t=new Set(r.map(n=>n.agentId));for(let n of e.agentIds)if(!t.has(n))throw new Error(`Expected chunks from agent "${n}", found agents: [${[...t].join(", ")}]`)}if(e.hasDone===true&&!r.some(n=>n.chunk.type==="done"))throw new Error("Expected at least one 'done' chunk, found none");if(e.hasErrors===true&&!r.some(n=>n.chunk.type==="error"))throw new Error("Expected at least one 'error' chunk, found none");if(e.hasErrors===false&&r.some(n=>n.chunk.type==="error"))throw new Error("Expected no 'error' chunks, but found some")}function X(r){let e=r?.passAfter??1,t=r?.feedback??"Needs improvement",n=r?.score,o=0;return (s,a)=>{o++;let i=o>=e;return {passed:i,feedback:i?void 0:t,score:n??(i?1:.5)}}}function Y(r,e){let t=r.getAll();for(let[n,o]of Object.entries(e)){let s=t[n];if(s!==o)throw new Error(`Expected scratchpad key "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}}function Z(r,e){let t=r.derived;for(let[n,o]of Object.entries(e)){let s=t[n];if(typeof o=="object"&&o!==null){let a=i=>JSON.stringify(i,Object.keys(i).sort());if(a(s)!==a(o))throw new Error(`Expected derived value "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}else if(s!==o)throw new Error(`Expected derived value "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}}export{J as assertAgentHealth,W as assertBreakpointHit,_ as assertCheckpoint,I as assertDagExecution,Z as assertDerivedValues,N as assertMultiAgentState,Q as assertMultiplexedStream,M as assertOrchestratorState,L as assertRerouted,Y as assertScratchpadState,F as assertTimelineEvents,K as collectMultiplexedStream,R as createApprovalSimulator,V as createBreakpointSimulator,O as createConstraintRecorder,H as createFailingRunner,b as createMockAgentRunner,z as createMockSchema,y as createMockTask,U as createTestCheckpointStore,P as createTestDag,D as createTestMultiAgentOrchestrator,C as createTestOrchestrator,X as createTestReflectionEvaluator,B as createTestTimeline,q as createTimeController,T as testGuardrail,x as testGuardrailBatch};//# sourceMappingURL=testing.js.map
|
|
1
|
+
import {a}from'./chunk-Q3PQLWBR.js';import {Da,ga,i,G}from'./chunk-RW4R3O5P.js';function b(r={}){let{defaultResponse:e={output:"mock response",totalTokens:10},responses:t={},recordCalls:n=true,onRun:o}=r,s=[],a=new Map(Object.entries(t)),i=e;return {run:async(l,c,g)=>{o?.(l,c),n&&s.push({agent:l,input:c,options:g,timestamp:Date.now()});let d=a.get(l.name)??i;if(d.generate){let p=d.generate(c,l);d={...d,...p};}if(d.error)throw d.error;d.delay&&d.delay>0&&await new Promise(p=>setTimeout(p,d.delay));let f=d.messages??[];for(let p of f)g?.onMessage?.(p);let m=d.toolCalls??[];for(let p of m)g?.onToolCall?.(p);return {output:d.output,messages:f,toolCalls:m,totalTokens:d.totalTokens??10}},getCalls:()=>[...s],getCallsFor:l=>s.filter(c=>c.agent.name===l),clearCalls:()=>s.length=0,setResponse:(l,c)=>a.set(l,c),setDefaultResponse:l=>i=l}}async function T(r,e,t){let n={agentName:"test-agent",input:"",...e},o={agentName:e.agentName??"test-agent",input:e.input??"",facts:t?.facts??{},...t},s=Date.now(),a=await r(n,o),i=Date.now()-s;return {...a,duration:i,testedData:n,assertPassed(){if(!a.passed)throw new Error(`Expected guardrail to pass, but it failed: ${a.reason}`)},assertFailed(u){if(a.passed)throw new Error("Expected guardrail to fail, but it passed");if(u!==void 0){if(typeof u=="string"&&!a.reason?.includes(u))throw new Error(`Expected failure reason to include "${u}", got: ${a.reason}`);if(u instanceof RegExp&&!u.test(a.reason??""))throw new Error(`Expected failure reason to match ${u}, got: ${a.reason}`)}},assertTransformed(u){if(a.transformed===void 0)throw new Error("Expected guardrail to transform input, but no transformation occurred");if(u!==void 0&&a.transformed!==u)throw new Error(`Expected transformation to be ${JSON.stringify(u)}, got: ${JSON.stringify(a.transformed)}`)}}}async function x(r,e){let t=[],n=[];for(let o=0;o<e.length;o++){let s=e[o],a=await T(r,s.input,s.context);t.push(a),(a.passed?a.transformed!==void 0?"transform":"pass":"fail")!==s.expect&&n.push({index:o,expected:s.expect,actual:a});}return {results:t,allPassed:()=>n.length===0,failures:()=>n}}function R(r={}){let{autoApprove:e,autoReject:t,delay:n=0,recordRequests:o=true}=r,s=[],a=new Map,i=[];return {async handle(u){o&&s.push(u);for(let l=i.length-1;l>=0;l--){let c=i[l];c.predicate(u)&&(i.splice(l,1),c.resolve(u));}return n>0&&await new Promise(l=>setTimeout(l,n)),t&&t(u)?"rejected":e?.(u)?"approved":new Promise(l=>{a.set(u.id,{request:u,resolve:l});})},getRequests:()=>[...s],clearRequests:()=>s.length=0,approve(u){let l=a.get(u);l&&(l.resolve("approved"),a.delete(u));},reject(u,l){let c=a.get(u);if(c){c.resolve("rejected"),a.delete(u);let g=s.find(d=>d.id===u);g&&(g.rejectionReason=l);}},waitForRequest(u,l=5e3){let c=s.find(u);return c?Promise.resolve(c):new Promise((g,d)=>{let f={predicate:u,resolve:p=>{clearTimeout(m),g(p);}},m=setTimeout(()=>{let p=i.indexOf(f);p>=0&&i.splice(p,1),d(new Error("Timeout waiting for approval request"));},l);i.push(f);})}}}function C(r={}){let{mockResponses:e,defaultMockResponse:t,...n}=r,o=b({responses:e,defaultResponse:t}),s=R(),a$1=a({...n,runner:o.run,onApprovalRequest:u=>{s.handle(u),n.onApprovalRequest?.(u);}}),i=Object.create(a$1);return i.mockRunner=o,i.approvalSimulator=s,i.getCalls=()=>o.getCalls(),i.getApprovalRequests=()=>s.getRequests(),i.resetAll=()=>{a$1.reset(),o.clearCalls(),s.clearRequests();},i}function O(){let r=[];return {plugin:{name:"constraint-recorder",onRequirementCreated(e){r.push({constraintId:e.constraintId,triggered:true,requirement:e.requirement,facts:e.facts,timestamp:Date.now()});}},getSnapshots:()=>[...r],clearSnapshots:()=>r.length=0}}function M(r,e){let t=r.facts;if(e.agentStatus!==void 0&&t.agent.status!==e.agentStatus)throw new Error(`Expected agent status to be "${e.agentStatus}", got "${t.agent.status}"`);if(e.tokenUsage!==void 0){let{min:n,max:o,exact:s}=e.tokenUsage;if(s!==void 0&&t.agent.tokenUsage!==s)throw new Error(`Expected token usage to be exactly ${s}, got ${t.agent.tokenUsage}`);if(n!==void 0&&t.agent.tokenUsage<n)throw new Error(`Expected token usage to be at least ${n}, got ${t.agent.tokenUsage}`);if(o!==void 0&&t.agent.tokenUsage>o)throw new Error(`Expected token usage to be at most ${o}, got ${t.agent.tokenUsage}`)}if(e.pendingApprovals!==void 0&&t.approval.pending.length!==e.pendingApprovals)throw new Error(`Expected ${e.pendingApprovals} pending approvals, got ${t.approval.pending.length}`);if(e.conversationLength!==void 0){let{min:n,max:o,exact:s}=e.conversationLength,a=t.conversation.length;if(s!==void 0&&a!==s)throw new Error(`Expected conversation length to be exactly ${s}, got ${a}`);if(n!==void 0&&a<n)throw new Error(`Expected conversation length to be at least ${n}, got ${a}`);if(o!==void 0&&a>o)throw new Error(`Expected conversation length to be at most ${o}, got ${a}`)}}function q(r=Date.now()){let e=r,t=r;return {now:()=>e,advance:n=>{e+=n;},set:n=>{e=n;},reset:()=>{e=t;}}}function D(r){let{mockResponses:e={},defaultMockResponse:t,mockTasks:n,...o}=r;if(n){let c=o.tasks??{};for(let[g,d]of Object.entries(n))c[g]||(c[g]=y(d.output,{delay:d.delay,shouldError:d.shouldError}));o.tasks=c;}let s={};for(let[c,g]of Object.entries(e)){let d=o.agents[c];d&&(s[d.agent.name]=g);}let a=b({responses:s,defaultResponse:t}),i=R(),u=Da({...o,runner:a.run,onApprovalRequest:c=>{i.handle(c),o.onApprovalRequest?.(c);}}),l=Object.create(u);return l.mockRunner=a,l.approvalSimulator=i,l.getCalls=()=>a.getCalls(),l.getApprovalRequests=()=>i.getRequests(),l.resetAll=()=>{u.reset(),a.clearCalls(),i.clearRequests();},l}function N(r,e){if(e.taskStatus)for(let[t,n]of Object.entries(e.taskStatus)){let o=r.getTaskState(t);if(!o)throw new Error(`Expected task "${t}" to exist, but it was not found`);if(o.status!==n)throw new Error(`Expected task "${t}" status to be "${n}", got "${o.status}"`)}if(e.agentStatus)for(let[t,n]of Object.entries(e.agentStatus)){let o=r.getAgentState(t);if(!o)throw new Error(`Expected agent "${t}" to exist, but it was not found`);if(o.status!==n)throw new Error(`Expected agent "${t}" status to be "${n}", got "${o.status}"`)}if(e.totalTokens){let{agentId:t,min:n,max:o}=e.totalTokens;if(t){let s=r.getAgentState(t);if(!s)throw new Error(`Expected agent "${t}" to exist, but it was not found`);if(n!==void 0&&s.totalTokens<n)throw new Error(`Expected agent "${t}" tokens to be at least ${n}, got ${s.totalTokens}`);if(o!==void 0&&s.totalTokens>o)throw new Error(`Expected agent "${t}" tokens to be at most ${o}, got ${s.totalTokens}`)}else {let s=r.getAllAgentStates(),a=Object.values(s).reduce((i,u)=>i+u.totalTokens,0);if(n!==void 0&&a<n)throw new Error(`Expected total tokens to be at least ${n}, got ${a}`);if(o!==void 0&&a>o)throw new Error(`Expected total tokens to be at most ${o}, got ${a}`)}}if(e.globalTokens){let{min:t,max:n}=e.globalTokens,o=r.totalTokens;if(t!==void 0&&o<t)throw new Error(`Expected global tokens to be at least ${t}, got ${o}`);if(n!==void 0&&o>n)throw new Error(`Expected global tokens to be at most ${n}, got ${o}`)}if(e.pendingHandoffs!==void 0){let t=r.getPendingHandoffs().length;if(t!==e.pendingHandoffs)throw new Error(`Expected ${e.pendingHandoffs} pending handoffs, got ${t}`)}}function y(r,e){return {run:async(t,n)=>{if(n.aborted)throw new Error("Task aborted");if(e?.delay&&e.delay>0&&await new Promise((o,s)=>{let a=setTimeout(o,e.delay);n.addEventListener("abort",()=>{clearTimeout(a),s(new Error("Task aborted"));},{once:true});}),e?.shouldError)throw new Error("Mock task error");return r},label:e?.label??"Mock Task",description:e?.description}}function P(r,e,t){return ga(r,e??(o=>o.outputs),t)}function I(r,e){if(e.nodeStatuses)for(let[t,n]of Object.entries(e.nodeStatuses)){let o=r.statuses[t];if(o!==n)throw new Error(`Expected node "${t}" status to be "${n}", got "${o}"`)}if(e.completedNodes){for(let t of e.completedNodes)if(r.statuses[t]!=="completed")throw new Error(`Expected node "${t}" to be completed, got "${r.statuses[t]}"`)}if(e.skippedNodes){for(let t of e.skippedNodes)if(r.statuses[t]!=="skipped")throw new Error(`Expected node "${t}" to be skipped, got "${r.statuses[t]}"`)}if(e.errorNodes){for(let t of e.errorNodes)if(r.statuses[t]!=="error")throw new Error(`Expected node "${t}" to be error, got "${r.statuses[t]}"`)}if(e.outputContains)for(let[t,n]of Object.entries(e.outputContains)){let o=r.outputs[t];if(o!==n)throw new Error(`Expected node "${t}" output to be ${JSON.stringify(n)}, got ${JSON.stringify(o)}`)}}function B(r,e){let t=i({maxEvents:e?.maxEvents??500});if(r)for(let n of r)t.record({timestamp:Date.now(),snapshotId:null,agentId:"",...n});return t}function F(r,e){let t=r.getEvents();if(e.totalEvents!==void 0&&t.length!==e.totalEvents)throw new Error(`Expected ${e.totalEvents} timeline events, got ${t.length}`);if(e.minEvents!==void 0&&t.length<e.minEvents)throw new Error(`Expected at least ${e.minEvents} timeline events, got ${t.length}`);if(e.maxEvents!==void 0&&t.length>e.maxEvents)throw new Error(`Expected at most ${e.maxEvents} timeline events, got ${t.length}`);if(e.eventTypes){for(let n of e.eventTypes)if(!t.some(s=>s.type===n))throw new Error(`Expected timeline to contain event of type "${n}", but none found`)}if(e.agentEvents)for(let[n,o]of Object.entries(e.agentEvents)){let s=r.getEventsForAgent(n).length;if(s!==o)throw new Error(`Expected ${o} events for agent "${n}", got ${s}`)}if(e.hasType&&!t.some(o=>o.type===e.hasType))throw new Error(`Expected timeline to contain event of type "${e.hasType}"`);if(e.doesNotHaveType&&t.some(o=>o.type===e.doesNotHaveType))throw new Error(`Expected timeline NOT to contain event of type "${e.doesNotHaveType}"`)}function H(r,e){let t=0,n=e?.failAfter??0;return async(o,s,a)=>{if(t++,n>0&&t<=n)return {output:"success",messages:[],toolCalls:[],totalTokens:10};throw e?.delay&&e.delay>0&&await new Promise(i=>setTimeout(i,e.delay)),r??new Error("Runner failed")}}function L(r,e){if(r.length===0)throw new Error("Expected at least one reroute event, but none occurred");if(e.minReroutes!==void 0&&r.length<e.minReroutes)throw new Error(`Expected at least ${e.minReroutes} reroute events, got ${r.length}`);if(e.fromAgent&&!r.some(n=>n.originalAgent===e.fromAgent))throw new Error(`Expected reroute from agent "${e.fromAgent}", but no matching event found`);if(e.toAgent&&!r.some(n=>n.reroutedTo===e.toAgent))throw new Error(`Expected reroute to agent "${e.toAgent}", but no matching event found`);if(e.reason&&!r.some(n=>typeof e.reason=="string"?n.reason.includes(e.reason):e.reason.test(n.reason)))throw new Error(`Expected reroute reason matching ${e.reason}, but no matching event found`)}function J(r,e,t){let n=r.getMetrics(e);if(t.minScore!==void 0&&n.healthScore<t.minScore)throw new Error(`Expected agent "${e}" health score to be at least ${t.minScore}, got ${n.healthScore}`);if(t.maxScore!==void 0&&n.healthScore>t.maxScore)throw new Error(`Expected agent "${e}" health score to be at most ${t.maxScore}, got ${n.healthScore}`);if(t.circuitState!==void 0&&n.circuitState!==t.circuitState)throw new Error(`Expected agent "${e}" circuit state to be "${t.circuitState}", got "${n.circuitState}"`);if(t.minSuccessRate!==void 0&&n.successRate<t.minSuccessRate)throw new Error(`Expected agent "${e}" success rate to be at least ${t.minSuccessRate}, got ${n.successRate}`)}function U(r=100){let e=new G({maxCheckpoints:r}),t=[];return {inner:e,saved:t,getLatest:()=>t[t.length-1],async save(n){return t.push(n),e.save(n)},load:n=>e.load(n),list:()=>e.list(),delete:n=>e.delete(n),clear:()=>e.clear(),prune:()=>e.prune()}}function _(r,e){if(e.orchestratorType!==void 0&&r.orchestratorType!==e.orchestratorType)throw new Error(`Expected checkpoint orchestratorType "${e.orchestratorType}", got "${r.orchestratorType}"`);if(e.hasSystemExport===true&&(!r.systemExport||r.systemExport===""))throw new Error("Expected checkpoint to have non-empty systemExport, but it was empty");if(e.hasTimeline===true&&r.timelineExport===null)throw new Error("Expected checkpoint to have timeline export, but it was null");if(e.hasTimeline===false&&r.timelineExport!==null)throw new Error("Expected checkpoint to have no timeline export, but it was present");if(e.hasMemory===true&&r.memoryExport===null)throw new Error("Expected checkpoint to have memory export, but it was null");if(e.hasMemory===false&&r.memoryExport!==null)throw new Error("Expected checkpoint to have no memory export, but it was present");if(e.label!==void 0&&r.label!==e.label)throw new Error(`Expected checkpoint label "${e.label}", got "${r.label}"`)}function V(r={}){let e=[],t=null,n=false;return {handler:s=>{if(e.push(s),!n)throw new Error("[Directive] BreakpointSimulator: handler called but attachTo() was never called. Breakpoints will not be resolved. Call simulator.attachTo(orchestrator) after creation.");let a=r.autoResumeDelay??0,i=()=>{t&&(r.cancel?t.cancelBreakpoint(s.id,r.cancelReason):t.resumeBreakpoint(s.id,r.modifications));};a>0?setTimeout(i,a):queueMicrotask(i);},hits:e,attachTo:s=>{t=s,n=true;}}}function W(r,e){if(e.count!==void 0&&r.length!==e.count)throw new Error(`Expected ${e.count} breakpoint hits, got ${r.length}`);if(e.type&&!r.some(n=>n.type===e.type)){let n=r.map(o=>o.type).join(", ");throw new Error(`Expected breakpoint of type "${e.type}", found types: [${n}]`)}if(e.agentId&&!r.some(n=>n.agentId===e.agentId)){let n=r.map(o=>o.agentId).join(", ");throw new Error(`Expected breakpoint for agent "${e.agentId}", found agents: [${n}]`)}}function z(r,e){return {safeParse:t=>r(t)?{success:true,data:t}:{success:false,error:{message:"Validation failed"}},description:e}}async function K(r){let e=[];for await(let t of r)e.push(t);return e}function Q(r,e){if(e.minChunks!==void 0&&r.length<e.minChunks)throw new Error(`Expected at least ${e.minChunks} chunks, got ${r.length}`);if(e.agentIds){let t=new Set(r.map(n=>n.agentId));for(let n of e.agentIds)if(!t.has(n))throw new Error(`Expected chunks from agent "${n}", found agents: [${[...t].join(", ")}]`)}if(e.hasDone===true&&!r.some(n=>n.chunk.type==="done"))throw new Error("Expected at least one 'done' chunk, found none");if(e.hasErrors===true&&!r.some(n=>n.chunk.type==="error"))throw new Error("Expected at least one 'error' chunk, found none");if(e.hasErrors===false&&r.some(n=>n.chunk.type==="error"))throw new Error("Expected no 'error' chunks, but found some")}function X(r){let e=r?.passAfter??1,t=r?.feedback??"Needs improvement",n=r?.score,o=0;return (s,a)=>{o++;let i=o>=e;return {passed:i,feedback:i?void 0:t,score:n??(i?1:.5)}}}function Y(r,e){let t=r.getAll();for(let[n,o]of Object.entries(e)){let s=t[n];if(s!==o)throw new Error(`Expected scratchpad key "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}}function Z(r,e){let t=r.derived;for(let[n,o]of Object.entries(e)){let s=t[n];if(typeof o=="object"&&o!==null){let a=i=>JSON.stringify(i,Object.keys(i).sort());if(a(s)!==a(o))throw new Error(`Expected derived value "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}else if(s!==o)throw new Error(`Expected derived value "${n}" to be ${JSON.stringify(o)}, got ${JSON.stringify(s)}`)}}export{J as assertAgentHealth,W as assertBreakpointHit,_ as assertCheckpoint,I as assertDagExecution,Z as assertDerivedValues,N as assertMultiAgentState,Q as assertMultiplexedStream,M as assertOrchestratorState,L as assertRerouted,Y as assertScratchpadState,F as assertTimelineEvents,K as collectMultiplexedStream,R as createApprovalSimulator,V as createBreakpointSimulator,O as createConstraintRecorder,H as createFailingRunner,b as createMockAgentRunner,z as createMockSchema,y as createMockTask,U as createTestCheckpointStore,P as createTestDag,D as createTestMultiAgentOrchestrator,C as createTestOrchestrator,X as createTestReflectionEvaluator,B as createTestTimeline,q as createTimeController,T as testGuardrail,x as testGuardrailBatch};//# sourceMappingURL=testing.js.map
|
|
2
2
|
//# sourceMappingURL=testing.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@directive-run/ai",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "AI guardrails and orchestration for Directive. Prompt injection, PII detection, cost tracking, multi-agent patterns.",
|
|
5
5
|
"license": "(MIT OR Apache-2.0)",
|
|
6
6
|
"author": "Jason Comes",
|
|
@@ -85,7 +85,7 @@
|
|
|
85
85
|
"@types/node": "^25.2.0",
|
|
86
86
|
"tsup": "^8.3.5",
|
|
87
87
|
"typescript": "^5.7.2",
|
|
88
|
-
"@directive-run/core": "1.
|
|
88
|
+
"@directive-run/core": "1.5.0"
|
|
89
89
|
},
|
|
90
90
|
"scripts": {
|
|
91
91
|
"build": "tsup",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/shared.ts"],"names":["throwStreamingHTTPError","response","adapterName","errBody","getSSEReader","reader","warnIfMissingApiKey","apiKey","functionName","parseSSEStream","onToken","parseEvent","decoder","buf","fullText","inputTokens","outputTokens","done","value","lines","line","data","event","result","parseErr","fireBeforeCallHook","hooks","agent","input","startTime","fireAfterCallHook","output","totalTokens","tokenUsage","fireErrorHook","err","buildStreamingResult"],"mappings":"AAsBA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACgB,CAChB,IAAMC,CAAAA,CAAU,MAAMF,CAAAA,CAAS,IAAA,EAAK,CAAE,KAAA,CAAM,IAAM,EAAE,CAAA,CAEpD,MAAM,IAAI,KAAA,CACR,CAAA,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CAAE,MAAAC,CAAAA,CAAO,KAAA,CAAAC,CAAAA,CAAO,SAAA,CAAWC,CAAU,CAAC,EAErDA,CACT,CAKO,SAASC,CAAAA,CACdJ,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAG,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAJ,CAAAA,CACM,CACNH,CAAAA,EAAO,WAAA,GAAc,CACnB,KAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,MAAA,CAAAG,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,UAAA,CAAY,IAAA,CAAK,GAAA,EAAI,CAAIJ,EACzB,SAAA,CAAW,IAAA,CAAK,GAAA,EAClB,CAAC,EACH,CAKO,SAASK,CAAAA,CACdR,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAO,CAAAA,CACAN,CAAAA,CACM,CACFM,CAAAA,YAAe,KAAA,EACjBT,CAAAA,EAAO,OAAA,GAAU,CACf,KAAA,CAAAC,EACA,KAAA,CAAAC,CAAAA,CACA,KAAA,CAAOO,CAAAA,CACP,UAAA,CAAY,IAAA,CAAK,KAAI,CAAIN,CAAAA,CACzB,SAAA,CAAW,IAAA,CAAK,GAAA,EAClB,CAAC,EAEL,CASO,SAASO,CAAAA,CACdR,CAAAA,CACAd,CAAAA,CACAkB,CAAAA,CACAC,EAOA,CAGA,OAAO,CACL,MAAA,CAAQnB,CAAAA,CACR,QAAA,CAAU,CAAC,CAAE,IAAA,CAAM,MAAA,CAAiB,OAAA,CAASc,CAAM,CAAA,CAJvB,CAAE,KAAM,WAAA,CAAa,OAAA,CAASd,CAAS,CAID,CAAA,CAClE,SAAA,CAAW,EAAC,CACZ,WAAA,CAAAkB,CAAAA,CACA,UAAA,CAAAC,CACF,CACF","file":"chunk-265ZKXYE.js","sourcesContent":["/**\n * Shared utilities for streaming adapters.\n *\n * Extracts common SSE parsing, error handling, hook lifecycle, and response\n * building logic used across Anthropic, OpenAI, and Gemini streaming runners.\n */\n\nimport type {\n AdapterHooks,\n AgentLike,\n Message,\n TokenUsage,\n} from \"../types.js\";\n\n// ============================================================================\n// HTTP Error Handling\n// ============================================================================\n\n/**\n * Throw a standardized HTTP error from a streaming response.\n * Reads up to 200 chars of the error body for diagnostics.\n */\nexport async function throwStreamingHTTPError(\n response: Response,\n adapterName: string,\n): Promise<never> {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] ${adapterName} streaming error ${response.status}${errBody ? ` – ${errBody.slice(0, 200)}` : \"\"}`,\n );\n}\n\n/**\n * Get an SSE reader from a response, throwing if body is missing.\n */\nexport function getSSEReader(\n response: Response,\n): ReadableStreamDefaultReader<Uint8Array> {\n const reader = response.body?.getReader();\n if (!reader) {\n throw new Error(\"[Directive] No response body\");\n }\n\n return reader;\n}\n\n// ============================================================================\n// API Key Validation\n// ============================================================================\n\n/**\n * Warn in non-production environments if an API key is empty.\n */\nexport function warnIfMissingApiKey(\n apiKey: string | undefined,\n functionName: string,\n): void {\n if (\n typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\" &&\n !apiKey\n ) {\n console.warn(\n `[Directive] ${functionName}: apiKey is empty. API calls will fail.`,\n );\n }\n}\n\n// ============================================================================\n// SSE Stream Parser\n// ============================================================================\n\n/** Result from parsing a single SSE event (provider-specific). */\nexport interface SSEEventResult {\n /** Text token to append to output. */\n text?: string;\n /** Updated input token count (cumulative, not delta). */\n inputTokens?: number;\n /** Updated output token count (cumulative, not delta). */\n outputTokens?: number;\n}\n\n/**\n * Parse an SSE stream from a Response, calling `onToken` for each text chunk\n * and `parseEvent` for provider-specific event extraction.\n *\n * Handles buffering, `[DONE]` sentinels, malformed JSON, and reader cleanup.\n *\n * @param reader - The ReadableStream reader from the response body.\n * @param onToken - Callback for each text token (may be undefined).\n * @param parseEvent - Provider-specific function to extract text and tokens from a parsed SSE event.\n * @param adapterName - Adapter name for dev-mode warnings.\n * @returns The full text output and final token counts.\n */\nexport async function parseSSEStream(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n onToken: ((token: string) => void) | undefined,\n parseEvent: (event: Record<string, unknown>) => SSEEventResult,\n adapterName: string,\n): Promise<{ fullText: string; inputTokens: number; outputTokens: number }> {\n const decoder = new TextDecoder();\n let buf = \"\";\n let fullText = \"\";\n let inputTokens = 0;\n let outputTokens = 0;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n buf += decoder.decode(value, { stream: true });\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) {\n continue;\n }\n const data = line.slice(6).trim();\n if (data === \"[DONE]\") {\n continue;\n }\n\n try {\n const event = JSON.parse(data);\n const result = parseEvent(event);\n if (result.text) {\n fullText += result.text;\n onToken?.(result.text);\n }\n if (result.inputTokens !== undefined) {\n inputTokens = result.inputTokens;\n }\n if (result.outputTokens !== undefined) {\n outputTokens = result.outputTokens;\n }\n } catch (parseErr) {\n if (parseErr instanceof SyntaxError) {\n if (\n typeof process !== \"undefined\" &&\n process.env?.NODE_ENV === \"development\"\n ) {\n console.warn(\n `[Directive] Malformed SSE event from ${adapterName}:`,\n data,\n );\n }\n } else {\n throw parseErr;\n }\n }\n }\n }\n } finally {\n reader.cancel().catch(() => {});\n }\n\n return { fullText, inputTokens, outputTokens };\n}\n\n// ============================================================================\n// Hook Lifecycle Helpers\n// ============================================================================\n\n/**\n * Fire the onBeforeCall hook and return the start timestamp.\n */\nexport function fireBeforeCallHook(\n hooks: AdapterHooks | undefined,\n agent: AgentLike,\n input: string,\n): number {\n const startTime = Date.now();\n hooks?.onBeforeCall?.({ agent, input, timestamp: startTime });\n\n return startTime;\n}\n\n/**\n * Fire the onAfterCall hook with timing and token data.\n */\nexport function fireAfterCallHook(\n hooks: AdapterHooks | undefined,\n agent: AgentLike,\n input: string,\n output: string,\n totalTokens: number,\n tokenUsage: TokenUsage,\n startTime: number,\n): void {\n hooks?.onAfterCall?.({\n agent,\n input,\n output,\n totalTokens,\n tokenUsage,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n });\n}\n\n/**\n * Fire the onError hook if the error is an Error instance.\n */\nexport function fireErrorHook(\n hooks: AdapterHooks | undefined,\n agent: AgentLike,\n input: string,\n err: unknown,\n startTime: number,\n): void {\n if (err instanceof Error) {\n hooks?.onError?.({\n agent,\n input,\n error: err,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n });\n }\n}\n\n// ============================================================================\n// Streaming Response Builder\n// ============================================================================\n\n/**\n * Build the standard streaming runner return value.\n */\nexport function buildStreamingResult(\n input: string,\n fullText: string,\n totalTokens: number,\n tokenUsage: TokenUsage,\n): {\n output: string;\n messages: Message[];\n toolCalls: never[];\n totalTokens: number;\n tokenUsage: TokenUsage;\n} {\n const assistantMsg: Message = { role: \"assistant\", content: fullText };\n\n return {\n output: fullText,\n messages: [{ role: \"user\" as const, content: input }, assistantMsg],\n toolCalls: [],\n totalTokens,\n tokenUsage,\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent-orchestrator.ts"],"names":["MAX_CONVERSATION_MESSAGES","MAX_TOOL_CALLS","createAgentOrchestrator","options","runner","factsSchema","init","constraints","resolvers","guardrails","onApprovalRequest","autoApproveToolCalls","maxTokenBudget","budgetWarningThreshold","onBudgetWarning","plugins","rawDebug","approvalTimeoutMs","agentRetry","hooks","memory","circuitBreaker","selfHealing","outputSchema","maxSchemaRetries","checkpointStore","breakpoints","onBreakpoint","breakpointTimeoutMs","debug","MAX_VERBOSE_LENGTH","fireHook","name","event","hookError","RESERVED_ORCHESTRATOR_KEYS","key","combinedSchema","orchestratorBridgeSchema","t","runAgentWithGuardrailsFn","system","directiveConstraints","convertOrchestratorConstraints","facts","getAgentState","directiveResolvers","convertOrchestratorResolvers","agent","input","currentFacts","opts","requirementGuard","_req","context","currentAgent","setAgentState","timeline","createDebugTimeline","snapshotId","callbackPlugin","createCallbackPlugin","orchestratorModule","createModule","setApprovalState","setConversation","setToolCalls","setBreakpointState","setBridgeFact","state","getOrchestratorState","combinedFacts","allPlugins","createDebugTimelinePlugin","createSystem","runAgentWithGuardrails","_currentFacts","callOptions","runAgentWithGuardrailsInner","error","fallbackRunner","rerouteEvent","startTime","contextMessages","contextStr","m","metaStr","formatSystemMeta","bpContext","mods","handleBreakpoint","effectiveInputGuardrails","effectiveOutputGuardrails","inputGuardrailsList","g","i","normalizeGuardrail","guardrail","guardStartTime","result","executeGuardrailWithRetry","GuardrailError","effectiveSchema","effectiveRunner","withStructuredOutput","executeAgentWithRetry","message","updated","getConversation","toolCall","toolCallGuardrails","guardResult","approvalId","approvalRequest","currentApproval","getApprovalState","waitForApproval","updatedToolCalls","getToolCalls","attempt","delayMs","outputGuardrailsList","shouldFireBudgetWarning","budgetPercentage","newTokenUsage","warningFired","getBridgeFact","callbackError","memoryError","outputStr","breakpointModifications","breakpointCancelReasons","waitForBreakpointResolution","bpId","signal","resolve","reject","settled","timeoutId","cleanupAll","onAbort","unsubscribe","BREAKPOINT_KEY","bpState","getBreakpointState","cancelReason","bpTimeout","type","match","matchBreakpoint","createBreakpointId","request","requestId","APPROVAL_KEY","approval","rejectedRequest","r","errorMsg","timeoutSeconds","getCombinedFacts","abortController","MAX_STREAM_BUFFER","chunks","waiters","closed","tokenCount","MAX_ACCUMULATED_OUTPUT","accumulatedOutput","abortHandler","cleanup","pushChunk","chunk","waiter","closeStream","resultPromise","processedInput","inputGuardrails","currentConversation","newTokens","currentToolCalls","outputGuardrails","duration","timeoutMs","isIdle","start","MAX_APPROVAL_HISTORY","approved","reason","MAX_REJECTION_HISTORY","rejected","cpOptions","cp","createCheckpointId","restoreOpts","validateCheckpoint","id","modifications","resolved","MAX_BREAKPOINT_HISTORY","cancelled"],"mappings":"mRA4GA,IAAMA,EAAAA,CAA4B,GAAA,CAE5BC,EAAAA,CAAiB,GAAA,CAmShB,SAASC,EAAAA,CAEdC,EAAAA,CAAu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AAMsG,CAAAA,CAAUC,CAAAA,CAAmBvG,IAAO,KAAK,CAAA,CACzC8J,EAAY,CAAC,GAAGxD,CAAAA,CAAQ,SAAA,CAAWoD,CAAE,CAAA,CAC3ChI,EAAmB1B,GAAAA,CAAO,KAAA,CAAO,CAC/B,GAAGsG,CAAAA,CACH,QAASA,CAAAA,CAAQ,OAAA,CAAQ,OAAQa,CAAAA,EAAMA,CAAAA,CAAE,KAAOuC,CAAE,CAAA,CAClD,UACEI,CAAAA,CAAU,MAAA,CAASD,EACfC,CAAAA,CAAU,KAAA,CAAM,CAACD,CAAsB,CAAA,CACvCC,CACR,CAAC,EACH,CAAC,EACH,CAAA,CAEA,qBAAA,EAA6C,CAG3C,OAAO,CAAC,GAFQvD,CAAAA,CAAmBvG,GAAAA,CAAO,KAAK,CAAA,CAE5B,OAAO,CAC5B,CAAA,CAEA,OAAA,EAAgB,CACdA,GAAAA,CAAO,OAAA,GACT,CACF,CAGF","file":"chunk-5ERCL33C.js","sourcesContent":["/**\n * Agent Orchestrator — constraint-driven agent execution with guardrails.\n *\n * Single-agent orchestrator backed by a Directive System with reactive state,\n * constraints, guardrails, streaming, approval workflow, and lifecycle hooks.\n */\n\nimport type {\n ModuleSchema,\n Plugin,\n Requirement,\n SingleModuleSystem,\n System,\n} from \"@directive-run/core\";\nimport { createModule, t } from \"@directive-run/core\";\nimport { createSystem } from \"@directive-run/core\";\nimport {\n createCallbackPlugin,\n getBridgeFact,\n requirementGuard,\n setBridgeFact,\n} from \"@directive-run/core/adapter-utils\";\nimport type { CircuitBreaker } from \"@directive-run/core/plugins\";\nimport type { AgentMemory } from \"./memory.js\";\nimport { formatSystemMeta } from \"./meta-context.js\";\nimport type { StreamChunk as StreamChunkBase } from \"./streaming.js\";\n\nimport type {\n AgentLike,\n AgentRetryConfig,\n AgentRunner,\n ApprovalRequest,\n GuardrailFn,\n GuardrailsConfig,\n InputGuardrailData,\n NamedGuardrail,\n OrchestratorConstraint,\n OrchestratorLifecycleHooks,\n OrchestratorResolver,\n OrchestratorState,\n OutputGuardrailData,\n RejectedRequest,\n RerouteEvent,\n RunOptions,\n RunResult,\n SelfHealingConfig,\n} from \"./types.js\";\n\nimport {\n APPROVAL_KEY,\n BREAKPOINT_KEY,\n GuardrailError,\n orchestratorBridgeSchema,\n} from \"./types.js\";\n\nimport {\n type DebugTimeline,\n createDebugTimeline,\n createDebugTimelinePlugin,\n} from \"./debug-timeline.js\";\n\nimport {\n executeAgentWithRetry,\n executeGuardrailWithRetry,\n normalizeGuardrail,\n} from \"./guardrail-utils.js\";\n\nimport {\n convertOrchestratorConstraints,\n convertOrchestratorResolvers,\n getAgentState,\n getApprovalState,\n getBreakpointState,\n getConversation,\n getOrchestratorState,\n getToolCalls,\n setAgentState,\n setApprovalState,\n setBreakpointState,\n setConversation,\n setToolCalls,\n} from \"./orchestrator-bridge.js\";\n\nimport type {\n BreakpointConfig,\n BreakpointContext,\n BreakpointModifications,\n BreakpointRequest,\n} from \"./breakpoints.js\";\nimport {\n MAX_BREAKPOINT_HISTORY,\n createBreakpointId,\n matchBreakpoint,\n} from \"./breakpoints.js\";\nimport {\n type Checkpoint,\n type CheckpointStore,\n createCheckpointId,\n validateCheckpoint,\n} from \"./checkpoint.js\";\nimport {\n type SafeParseable,\n withStructuredOutput,\n} from \"./structured-output.js\";\n\n// Bridge accessors and constraint/resolver converters imported from orchestrator-bridge.ts\n\n/** Maximum conversation messages retained (FIFO eviction) */\nconst MAX_CONVERSATION_MESSAGES = 500;\n/** Maximum tool calls retained (FIFO eviction) */\nconst MAX_TOOL_CALLS = 200;\n\n/** Built-in pause requirement type */\ninterface PauseBudgetExceededReq extends Requirement {\n type: \"__PAUSE_BUDGET_EXCEEDED\";\n}\n\n// ============================================================================\n// Exported Types\n// ============================================================================\n\n/** Orchestrator options */\nexport interface OrchestratorOptions<F extends Record<string, unknown>> {\n /** Function to run an agent */\n runner: AgentRunner;\n /**\n * Schema for custom facts tracked in the orchestrator's Directive System.\n * @example\n * ```typescript\n * import { t } from '@directive-run/core';\n * const orchestrator = createOrchestrator({\n * factsSchema: { confidence: t.number(), category: t.string() },\n * // ...\n * });\n * ```\n */\n factsSchema?: Record<string, { _type: unknown; _validators: [] }>;\n /** Initialize additional facts */\n init?: (facts: F & OrchestratorState) => void;\n /** Constraints for orchestration */\n constraints?: Record<string, OrchestratorConstraint<F>>;\n /** Resolvers for orchestration */\n resolvers?: Record<string, OrchestratorResolver<F, Requirement>>;\n /** Guardrails */\n guardrails?: GuardrailsConfig;\n /** Callback for approval requests */\n onApprovalRequest?: (request: ApprovalRequest) => void;\n /**\n * Auto-approve tool calls\n * @default true\n */\n autoApproveToolCalls?: boolean;\n /**\n * Maximum token budget across all agent runs.\n *\n * When exceeded, agents are automatically paused with status \"paused\".\n * Check `facts.agent.tokenUsage` to see current usage.\n *\n * For more sophisticated cost management (per-user budgets, tiered pricing,\n * cost alerts), see the Cost Management section in the documentation.\n *\n * @example\n * ```typescript\n * const orchestrator = createAgentOrchestrator({\n * maxTokenBudget: 10000, // Pause after 10K tokens\n * });\n *\n * // Check if paused due to budget\n * if (orchestrator.facts.agent.status === 'paused') {\n * console.log('Budget exceeded:', orchestrator.facts.agent.tokenUsage);\n * }\n * ```\n */\n maxTokenBudget?: number;\n /** Fires when token usage reaches this percentage of maxTokenBudget (0-1). @default 0.8 */\n budgetWarningThreshold?: number;\n /** Callback when budget warning threshold is reached */\n onBudgetWarning?: (event: {\n currentTokens: number;\n maxBudget: number;\n percentage: number;\n }) => void;\n /** Plugins */\n plugins?: Plugin[];\n /**\n * Enable debugging — `true` for default debug, or config object for advanced options\n * @default false\n */\n debug?: boolean | import(\"./types.js\").OrchestratorDebugConfig;\n /**\n * Approval timeout in milliseconds\n * @default 300000 (5 minutes)\n */\n approvalTimeoutMs?: number;\n /** Retry configuration for agent runs (no retries if not specified) */\n agentRetry?: AgentRetryConfig;\n /** Lifecycle hooks for observability */\n hooks?: OrchestratorLifecycleHooks;\n /**\n * Optional memory instance. When provided, context messages are auto-injected\n * into agent instructions before each run, and result messages are auto-stored.\n */\n memory?: AgentMemory;\n /**\n * Optional circuit breaker. Wraps every run() call.\n * When OPEN, throws CircuitBreakerOpenError instead of calling the agent.\n */\n circuitBreaker?: CircuitBreaker;\n /** Self-healing configuration for automatic fallback */\n selfHealing?: SelfHealingConfig;\n /**\n * Default schema for structured output. When set, agent output is parsed and\n * validated against this schema with automatic retry on failure.\n * Any Zod-compatible schema (anything with `safeParse`) works.\n */\n outputSchema?: SafeParseable<unknown>;\n /**\n * Max retries for structured output parsing.\n * @default 2\n */\n maxSchemaRetries?: number;\n /** Optional checkpoint store for save/restore workflow state. */\n checkpointStore?: CheckpointStore;\n /**\n * Breakpoint configurations for human-in-the-loop pause points.\n * Zero overhead when empty — guard checks at each insertion point.\n */\n breakpoints?: BreakpointConfig[];\n /** Callback fired when a breakpoint is hit and waiting for resolution. */\n onBreakpoint?: (request: BreakpointRequest) => void;\n /**\n * Timeout for breakpoint resolution in milliseconds.\n * @default 300000 (5 minutes)\n */\n breakpointTimeoutMs?: number;\n /**\n * Include system meta in agent instructions for structured LLM reasoning.\n * When true, constraint labels, resolver descriptions, fact annotations,\n * and module metadata are injected into the agent's system prompt.\n * @default false\n */\n metaContext?: boolean;\n}\n\n/** Streaming run result from orchestrator */\nexport interface OrchestratorStreamResult<T = unknown> {\n /** Async iterator for streaming chunks */\n stream: AsyncIterable<OrchestratorStreamChunk>;\n /** Promise that resolves to the final result */\n result: Promise<RunResult<T>>;\n /** Abort the stream */\n abort: () => void;\n}\n\n/** Stream chunk types for orchestrator — extends StreamChunk with approval events */\nexport type OrchestratorStreamChunk =\n | StreamChunkBase\n | { type: \"approval_required\"; requestId: string; toolName: string }\n | { type: \"approval_resolved\"; requestId: string; approved: boolean };\n\n/** Per-call options for run() */\nexport interface RunCallOptions {\n /** Override output guardrails for this call only. Set to [] to skip. */\n outputGuardrails?: Array<\n GuardrailFn<OutputGuardrailData> | NamedGuardrail<OutputGuardrailData>\n >;\n /** Override input guardrails for this call only. Set to [] to skip. */\n inputGuardrails?: Array<\n GuardrailFn<InputGuardrailData> | NamedGuardrail<InputGuardrailData>\n >;\n /** Signal for abort */\n signal?: AbortSignal;\n /** Override structured output schema for this call. Set to `null` to opt out. */\n outputSchema?: SafeParseable<unknown> | null;\n /** Override max schema retries for this call. */\n maxSchemaRetries?: number;\n}\n\n/** Orchestrator instance */\nexport interface AgentOrchestrator<F extends Record<string, unknown>> {\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n system: System<any>;\n facts: F & OrchestratorState;\n /** Run an agent with guardrails. Pass options to override guardrails per-call. */\n run<T>(\n agent: AgentLike,\n input: string,\n options?: RunCallOptions,\n ): Promise<RunResult<T>>;\n /**\n * Run an agent with streaming support.\n * Returns an async iterator for chunks and a promise for the final result.\n *\n * @example\n * ```typescript\n * const { stream, result, abort } = orchestrator.runStream(agent, input);\n *\n * for await (const chunk of stream) {\n * if (chunk.type === 'token') process.stdout.write(chunk.data);\n * if (chunk.type === 'approval_required') showApprovalDialog(chunk);\n * if (chunk.type === 'guardrail_triggered') handleGuardrail(chunk);\n * }\n *\n * const finalResult = await result;\n * ```\n */\n runStream<T>(\n agent: AgentLike,\n input: string,\n options?: { signal?: AbortSignal },\n ): OrchestratorStreamResult<T>;\n /** Approve a pending request */\n approve(requestId: string): void;\n /** Reject a pending request */\n reject(requestId: string, reason?: string): void;\n /** Pause all agents */\n pause(): void;\n /** Resume agents */\n resume(): void;\n /** Reset conversation state */\n reset(): void;\n /** Total tokens consumed across all agent runs */\n readonly totalTokens: number;\n /** Debug timeline (null when debug is false) */\n readonly timeline: DebugTimeline | null;\n /** Wait until agent is idle. Resolves immediately if already idle. */\n waitForIdle(timeoutMs?: number): Promise<void>;\n /** Create a checkpoint of the current orchestrator state. Only valid when agent is not running. */\n checkpoint(options?: { label?: string }): Promise<Checkpoint>;\n /** Restore orchestrator state from a checkpoint. */\n restore(\n checkpoint: Checkpoint,\n options?: { restoreTimeline?: boolean },\n ): void;\n /** Resume a pending breakpoint, optionally with input modifications. */\n resumeBreakpoint(id: string, modifications?: BreakpointModifications): void;\n /** Cancel a pending breakpoint with optional reason. */\n cancelBreakpoint(id: string, reason?: string): void;\n /** Get all currently pending breakpoint requests. */\n getPendingBreakpoints(): BreakpointRequest[];\n /** Destroy the orchestrator, releasing all resources. */\n destroy(): void;\n}\n\n// ============================================================================\n// Main Factory\n// ============================================================================\n\n/**\n * Create a constraint-driven agent orchestrator backed by a Directive System.\n *\n * Wraps a single agent runner with reactive state, guardrails, streaming,\n * approval workflows, breakpoints, structured output, and lifecycle hooks.\n * Constraints and resolvers let you declaratively control agent behavior\n * based on runtime facts.\n *\n * @param options - Orchestrator configuration including runner, guardrails, constraints, and plugins.\n * @returns An {@link AgentOrchestrator} instance with `run`, `runStream`, `approve`/`reject`, and checkpoint APIs.\n *\n * @example\n * ```typescript\n * import { run as runner } from '@openai/agents';\n *\n * const orchestrator = createAgentOrchestrator({\n * runner,\n * constraints: {\n * escalateToExpert: {\n * when: (facts) => facts.agent.output?.confidence < 0.7,\n * require: (facts) => ({\n * type: 'RUN_EXPERT_AGENT',\n * query: facts.agent.input,\n * }),\n * },\n * budgetExceeded: {\n * when: (facts) => facts.agent.tokenUsage > 10000,\n * require: { type: 'PAUSE_AGENTS' },\n * },\n * },\n * guardrails: {\n * input: [\n * async (data) => {\n * const hasPII = await detectPII(data.input);\n * return { passed: !hasPII, reason: hasPII ? 'Contains PII' : undefined };\n * },\n * ],\n * output: [\n * async (data) => {\n * const isToxic = await checkToxicity(data.output);\n * return { passed: !isToxic, reason: isToxic ? 'Toxic content' : undefined };\n * },\n * ],\n * },\n * });\n *\n * // Run with guardrails and constraint-driven orchestration\n * const result = await orchestrator.run(myAgent, 'Hello, can you help me?');\n * ```\n *\n * @throws If autoApproveToolCalls is false but no onApprovalRequest callback is provided\n * @public\n */\nexport function createAgentOrchestrator<\n F extends Record<string, unknown> = Record<string, never>,\n>(options: OrchestratorOptions<F>): AgentOrchestrator<F> {\n const {\n runner,\n factsSchema = {},\n init,\n constraints = {},\n resolvers = {},\n guardrails = {},\n onApprovalRequest,\n autoApproveToolCalls = true,\n maxTokenBudget,\n budgetWarningThreshold = 0.8,\n onBudgetWarning,\n plugins = [],\n debug: rawDebug = false,\n approvalTimeoutMs = 300000,\n agentRetry,\n hooks = {},\n memory,\n circuitBreaker,\n selfHealing,\n outputSchema,\n maxSchemaRetries,\n checkpointStore,\n breakpoints,\n onBreakpoint,\n breakpointTimeoutMs,\n } = options;\n\n // Normalize debug config\n const debug = typeof rawDebug === \"object\" ? true : !!rawDebug;\n const MAX_VERBOSE_LENGTH = 5000;\n\n // Warn if selfHealing is configured without circuitBreaker (selfHealing only triggers in CB error path)\n if (debug && selfHealing && !circuitBreaker) {\n console.warn(\n \"[Directive] selfHealing config has no effect without a circuitBreaker — \" +\n \"fallback behavior requires the circuit breaker to detect failures.\",\n );\n }\n\n // Validate budget warning threshold\n if (budgetWarningThreshold < 0 || budgetWarningThreshold > 1) {\n throw new Error(\n `[Directive Orchestrator] budgetWarningThreshold must be between 0 and 1, got ${budgetWarningThreshold}`,\n );\n }\n\n // Enforce approval workflow configuration - require either auto-approve or callback\n if (!autoApproveToolCalls && !onApprovalRequest) {\n throw new Error(\n \"[Directive] Invalid approval configuration: autoApproveToolCalls is false but no onApprovalRequest callback provided. \" +\n \"Tool calls would wait for approval indefinitely. Either:\\n\" +\n \" - Set autoApproveToolCalls: true to auto-approve all tool calls\\n\" +\n \" - Provide an onApprovalRequest callback to handle approvals programmatically\",\n );\n }\n\n /** Safe hook caller — user-provided hooks must never crash the orchestrator */\n function fireHook<K extends keyof OrchestratorLifecycleHooks>(\n name: K,\n event: Parameters<NonNullable<OrchestratorLifecycleHooks[K]>>[0],\n ): void {\n try {\n (hooks[name] as ((e: typeof event) => void) | undefined)?.(event);\n } catch (hookError) {\n if (debug) {\n console.debug(`[Directive] hooks.${name} threw:`, hookError);\n }\n }\n }\n\n // Dev-mode: validate that user-provided facts keys don't collide with bridge state keys\n const RESERVED_ORCHESTRATOR_KEYS = [\n \"agent\",\n \"approval\",\n \"conversation\",\n \"toolCalls\",\n ];\n for (const key of Object.keys(factsSchema)) {\n if (RESERVED_ORCHESTRATOR_KEYS.includes(key)) {\n throw new Error(\n `[Directive] Facts schema key \"${key}\" conflicts with orchestrator state. ` +\n `Reserved keys: ${RESERVED_ORCHESTRATOR_KEYS.join(\", \")}. ` +\n \"Rename your fact to avoid the collision.\",\n );\n }\n }\n\n // Build schema by combining bridge schema with user-provided schema\n const combinedSchema = {\n facts: {\n ...orchestratorBridgeSchema.facts,\n ...factsSchema,\n __budgetWarningFired: t.boolean(),\n },\n derivations: {},\n events: {},\n requirements: {},\n } satisfies ModuleSchema;\n\n // Forward declaration for runAgentWithGuardrails (used in resolver converter)\n // biome-ignore lint/style/useConst: forward declaration, assigned later\n let runAgentWithGuardrailsFn: <T>(\n agent: AgentLike,\n input: string,\n currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions,\n ) => Promise<RunResult<T>>;\n\n // Forward declaration for system (used in resolver converter)\n // biome-ignore lint/style/useConst: forward declaration, assigned later\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n let system: SingleModuleSystem<any>;\n\n // Convert user constraints\n // biome-ignore lint/suspicious/noExplicitAny: Constraint types are complex\n const directiveConstraints: Record<string, any> =\n convertOrchestratorConstraints<F>(constraints);\n\n // Add built-in budget limit constraint\n if (maxTokenBudget) {\n directiveConstraints.__budgetLimit = {\n priority: 100, // High priority\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies\n when: (facts: any) => getAgentState(facts).tokenUsage > maxTokenBudget,\n require: { type: \"__PAUSE_BUDGET_EXCEEDED\" } as PauseBudgetExceededReq,\n };\n }\n\n // Convert user resolvers\n // biome-ignore lint/suspicious/noExplicitAny: Resolver types are complex\n const directiveResolvers: Record<string, any> =\n convertOrchestratorResolvers<F>(\n resolvers,\n (agent, input, currentFacts, opts) =>\n runAgentWithGuardrailsFn(agent, input, currentFacts, opts),\n () => system.facts,\n );\n\n // Add built-in pause resolver\n directiveResolvers.__pause = {\n requirement: requirementGuard<PauseBudgetExceededReq>(\n \"__PAUSE_BUDGET_EXCEEDED\",\n ),\n // biome-ignore lint/suspicious/noExplicitAny: Context type varies\n resolve: async (_req: Requirement, context: any) => {\n const currentAgent = getAgentState(context.facts);\n setAgentState(context.facts, {\n ...currentAgent,\n status: \"paused\",\n });\n },\n };\n\n // ---- Debug Timeline setup ----\n let timeline: DebugTimeline | null = null;\n if (debug) {\n timeline = createDebugTimeline({\n getSnapshotId: () => {\n try {\n return (system as any).history?.currentIndex ?? null;\n } catch {\n return null;\n }\n },\n goToSnapshot: (snapshotId: number) => {\n try {\n (system as any).history?.goTo?.(snapshotId);\n } catch {\n // System may not support goTo\n }\n },\n });\n }\n\n // Create callback plugin for onApprovalRequest\n const callbackPlugin = createCallbackPlugin(\n \"directive-ai-callbacks\",\n {}, // No requirement callbacks needed, approval is handled separately\n );\n\n // Create module\n // biome-ignore lint/suspicious/noExplicitAny: Bridge module uses dynamic constraints/resolvers\n const orchestratorModule = createModule(\"directive-ai-orchestrator\", {\n schema: combinedSchema,\n init: (facts) => {\n setAgentState(facts, {\n status: \"idle\",\n currentAgent: null,\n input: null,\n output: null,\n error: null,\n tokenUsage: 0,\n turnCount: 0,\n startedAt: null,\n completedAt: null,\n });\n setApprovalState(facts, {\n pending: [],\n approved: [],\n rejected: [],\n });\n setConversation(facts, []);\n setToolCalls(facts, []);\n setBreakpointState(facts, { pending: [], resolved: [], cancelled: [] });\n setBridgeFact(facts, \"__budgetWarningFired\", false);\n if (init) {\n const state = getOrchestratorState(facts);\n const combinedFacts = { ...facts, ...state } as unknown as F &\n OrchestratorState;\n init(combinedFacts);\n }\n },\n constraints: directiveConstraints,\n resolvers: directiveResolvers as any,\n });\n\n // Build plugins array with optional timeline plugin\n const allPlugins = [...plugins, callbackPlugin];\n if (debug && timeline) {\n allPlugins.push(\n createDebugTimelinePlugin(timeline, () => {\n try {\n return (system as any).history?.currentIndex ?? null;\n } catch {\n return null;\n }\n }),\n );\n }\n\n // Create system\n system = createSystem({\n module: orchestratorModule,\n plugins: allPlugins,\n history: debug ? true : undefined,\n });\n\n system.start();\n\n // Helper to run agent with guardrails\n async function runAgentWithGuardrails<T>(\n agent: AgentLike,\n input: string,\n _currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions,\n ): Promise<RunResult<T>> {\n // Wrap in circuit breaker if configured\n if (circuitBreaker) {\n try {\n return await circuitBreaker.execute(() =>\n runAgentWithGuardrailsInner<T>(\n agent,\n input,\n _currentFacts,\n opts,\n callOptions,\n ),\n );\n } catch (error) {\n // Self-healing fallback\n if (selfHealing) {\n // Try fallback runners in order\n if (selfHealing.fallbackRunners) {\n for (const fallbackRunner of selfHealing.fallbackRunners) {\n try {\n const rerouteEvent: RerouteEvent = {\n originalAgent: agent.name,\n reroutedTo: \"fallback-runner\",\n reason:\n error instanceof Error ? error.message : String(error),\n timestamp: Date.now(),\n };\n try {\n selfHealing.onReroute?.(rerouteEvent);\n } catch {\n /* non-fatal */\n }\n if (timeline) {\n timeline.record({\n type: \"reroute\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n from: agent.name,\n to: \"fallback-runner\",\n reason:\n error instanceof Error ? error.message : String(error),\n });\n }\n\n return await fallbackRunner<T>(agent, input, opts);\n } catch {\n // Try next fallback\n }\n }\n }\n\n // Try fallback agent\n if (selfHealing.fallbackAgent) {\n try {\n const rerouteEvent: RerouteEvent = {\n originalAgent: agent.name,\n reroutedTo: selfHealing.fallbackAgent.name,\n reason: error instanceof Error ? error.message : String(error),\n timestamp: Date.now(),\n };\n try {\n selfHealing.onReroute?.(rerouteEvent);\n } catch {\n /* non-fatal */\n }\n if (timeline) {\n timeline.record({\n type: \"reroute\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n from: agent.name,\n to: selfHealing.fallbackAgent.name,\n reason:\n error instanceof Error ? error.message : String(error),\n });\n }\n\n return await runner<T>(selfHealing.fallbackAgent, input, opts);\n } catch {\n // Fallback agent also failed\n }\n }\n\n // Apply degradation policy\n if (\n selfHealing.degradation === \"fallback-response\" &&\n selfHealing.fallbackResponse !== undefined\n ) {\n return {\n output: selfHealing.fallbackResponse as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n }\n throw error;\n }\n }\n\n return runAgentWithGuardrailsInner<T>(\n agent,\n input,\n _currentFacts,\n opts,\n callOptions,\n );\n }\n\n async function runAgentWithGuardrailsInner<T>(\n agent: AgentLike,\n input: string,\n _currentFacts: F & OrchestratorState,\n opts?: RunOptions,\n callOptions?: RunCallOptions,\n ): Promise<RunResult<T>> {\n const startTime = Date.now();\n\n // Inject memory context into agent instructions if memory is configured\n if (memory) {\n const contextMessages = memory.getContextMessages();\n if (contextMessages.length > 0) {\n const contextStr = contextMessages\n .map((m) => `${m.role}: ${m.content}`)\n .join(\"\\n\");\n agent = {\n ...agent,\n instructions:\n (agent.instructions ?? \"\") +\n \"\\n\\nConversation context:\\n\" +\n contextStr,\n };\n }\n }\n\n // Inject system meta context if enabled\n if (options.metaContext) {\n const metaStr = formatSystemMeta(system.inspect());\n if (metaStr) {\n agent = {\n ...agent,\n instructions: (agent.instructions ?? \"\") + \"\\n\\n\" + metaStr,\n };\n }\n }\n\n // Breakpoint: pre_input_guardrails\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_input_guardrails\",\n };\n const mods = await handleBreakpoint(\n \"pre_input_guardrails\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n // Resolve which guardrails to use: per-call override > orchestrator defaults\n const effectiveInputGuardrails =\n callOptions?.inputGuardrails !== undefined\n ? callOptions.inputGuardrails\n : (guardrails.input ?? []);\n const effectiveOutputGuardrails =\n callOptions?.outputGuardrails !== undefined\n ? callOptions.outputGuardrails\n : (guardrails.output ?? []);\n\n // Run input guardrails BEFORE agent_start so timeline shows correct order\n const inputGuardrailsList = effectiveInputGuardrails.map((g, i) =>\n normalizeGuardrail(g, i, \"input\"),\n );\n for (const guardrail of inputGuardrailsList) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const result = await executeGuardrailWithRetry(\n guardrail,\n { input, agentName: agent.name },\n context,\n );\n // Call onGuardrailCheck hook\n fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\n guardrailName: name,\n guardrailType: \"input\",\n passed: result.passed,\n reason: result.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!result.passed) {\n throw new GuardrailError({\n code: \"INPUT_GUARDRAIL_FAILED\",\n message: `Input guardrail \"${name}\" failed: ${result.reason}`,\n guardrailName: name,\n guardrailType: \"input\",\n userMessage: result.reason ?? \"Input validation failed\",\n agentName: agent.name,\n input,\n });\n }\n if (result.transformed !== undefined) {\n input = result.transformed as string;\n }\n }\n\n // Call onAgentStart hook (after guardrails pass)\n fireHook(\"onAgentStart\", {\n agentName: agent.name,\n input,\n timestamp: startTime,\n });\n\n if (timeline) {\n timeline.record({\n type: \"agent_start\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n inputLength: input.length,\n modelId: agent.model ?? undefined,\n ...(agent.instructions\n ? { instructions: agent.instructions.slice(0, MAX_VERBOSE_LENGTH) }\n : {}),\n input: input.slice(0, MAX_VERBOSE_LENGTH),\n });\n }\n\n // Update state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"running\",\n currentAgent: agent.name,\n input,\n startedAt: Date.now(),\n });\n });\n\n // Breakpoint: pre_agent_run\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_agent_run\",\n };\n const mods = await handleBreakpoint(\n \"pre_agent_run\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n // Structured output wrapping\n const effectiveSchema =\n callOptions?.outputSchema !== undefined\n ? callOptions.outputSchema\n : outputSchema;\n\n let effectiveRunner = runner;\n if (effectiveSchema) {\n effectiveRunner = withStructuredOutput(runner, {\n schema: effectiveSchema,\n maxRetries: callOptions?.maxSchemaRetries ?? maxSchemaRetries ?? 2,\n });\n }\n\n // Run the agent with retry support\n const result = await executeAgentWithRetry<T>(\n effectiveRunner,\n agent,\n input,\n {\n ...opts,\n signal: opts?.signal,\n onMessage: (message) => {\n const currentConversation = getConversation(system.facts);\n const updated = [...currentConversation, message];\n setConversation(\n system.facts,\n updated.length > MAX_CONVERSATION_MESSAGES\n ? updated.slice(-MAX_CONVERSATION_MESSAGES)\n : updated,\n );\n opts?.onMessage?.(message);\n },\n onToolCall: async (toolCall) => {\n // Run tool call guardrails with retry support\n const toolCallGuardrails = (guardrails.toolCall ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"toolCall\"),\n );\n for (const guardrail of toolCallGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n { toolCall, agentName: agent.name, input },\n context,\n );\n fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\n guardrailName: name,\n guardrailType: \"toolCall\",\n passed: guardResult.passed,\n reason: guardResult.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!guardResult.passed) {\n throw new GuardrailError({\n code: \"TOOL_CALL_GUARDRAIL_FAILED\",\n message: `Tool call guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"toolCall\",\n userMessage: guardResult.reason ?? \"Tool call blocked\",\n data: { toolCall },\n agentName: agent.name,\n input,\n });\n }\n }\n\n // Check if approval is needed\n if (!autoApproveToolCalls) {\n const approvalId = `tool-${toolCall.id}`;\n const approvalRequest: ApprovalRequest = {\n id: approvalId,\n type: \"tool_call\",\n agentName: agent.name,\n description: `Tool call: ${toolCall.name}`,\n data: toolCall,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const currentApproval = getApprovalState(system.facts);\n setApprovalState(system.facts, {\n ...currentApproval,\n pending: [...currentApproval.pending, approvalRequest],\n });\n });\n\n onApprovalRequest?.(approvalRequest);\n\n // Wait for approval (pass signal so abort cancels the wait)\n await waitForApproval(\n approvalId,\n callOptions?.signal ?? opts?.signal,\n );\n }\n\n const currentToolCalls = getToolCalls(system.facts);\n const updatedToolCalls = [...currentToolCalls, toolCall];\n setToolCalls(\n system.facts,\n updatedToolCalls.length > MAX_TOOL_CALLS\n ? updatedToolCalls.slice(-MAX_TOOL_CALLS)\n : updatedToolCalls,\n );\n opts?.onToolCall?.(toolCall);\n },\n },\n agentRetry\n ? {\n ...agentRetry,\n onRetry: (attempt, error, delayMs) => {\n agentRetry.onRetry?.(attempt, error, delayMs);\n fireHook(\"onAgentRetry\", {\n agentName: agent.name,\n input,\n attempt,\n error,\n delayMs,\n timestamp: Date.now(),\n });\n },\n }\n : undefined,\n );\n\n // Breakpoint: pre_output_guardrails\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"pre_output_guardrails\",\n };\n const mods = await handleBreakpoint(\n \"pre_output_guardrails\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n // Run output guardrails with retry support\n const outputGuardrailsList = effectiveOutputGuardrails.map((g, i) =>\n normalizeGuardrail(g, i, \"output\"),\n );\n for (const guardrail of outputGuardrailsList) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input,\n facts: system.facts.$store.toObject(),\n };\n const guardStartTime = Date.now();\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n {\n output: result.output,\n agentName: agent.name,\n input,\n messages: result.messages,\n },\n context,\n );\n fireHook(\"onGuardrailCheck\", {\n agentId: agent.name,\n guardrailName: name,\n guardrailType: \"output\",\n passed: guardResult.passed,\n reason: guardResult.reason,\n durationMs: Date.now() - guardStartTime,\n timestamp: Date.now(),\n });\n if (!guardResult.passed) {\n throw new GuardrailError({\n code: \"OUTPUT_GUARDRAIL_FAILED\",\n message: `Output guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"output\",\n userMessage: guardResult.reason ?? \"Output validation failed\",\n agentName: agent.name,\n input,\n });\n }\n if (guardResult.transformed !== undefined) {\n (result as { output: unknown }).output = guardResult.transformed;\n }\n }\n\n // Update state\n let shouldFireBudgetWarning = false;\n let budgetPercentage = 0;\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n const newTokenUsage = currentAgent.tokenUsage + result.totalTokens;\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"completed\",\n output: result.output,\n tokenUsage: newTokenUsage,\n turnCount: currentAgent.turnCount + result.messages.length,\n completedAt: Date.now(),\n });\n\n // Check budget warning threshold\n if (maxTokenBudget && onBudgetWarning) {\n budgetPercentage = newTokenUsage / maxTokenBudget;\n const warningFired = getBridgeFact<boolean>(\n system.facts,\n \"__budgetWarningFired\",\n );\n if (budgetPercentage >= budgetWarningThreshold && !warningFired) {\n setBridgeFact(system.facts, \"__budgetWarningFired\", true);\n shouldFireBudgetWarning = true;\n }\n }\n });\n\n // Fire budget warning callback outside of batch (callbacks shouldn't run inside batch)\n if (shouldFireBudgetWarning) {\n try {\n onBudgetWarning!({\n currentTokens: getAgentState(system.facts).tokenUsage,\n maxBudget: maxTokenBudget!,\n percentage: budgetPercentage,\n });\n } catch (callbackError) {\n if (debug) {\n console.debug(\n \"[Directive Orchestrator] onBudgetWarning threw:\",\n callbackError,\n );\n }\n }\n }\n\n // Store messages in memory if configured (best-effort)\n if (memory && result.messages.length > 0) {\n try {\n memory.addMessages(result.messages);\n } catch (memoryError) {\n if (debug) {\n console.debug(\"[Directive] Memory addMessages failed:\", memoryError);\n }\n }\n }\n\n // Call onAgentComplete hook\n fireHook(\"onAgentComplete\", {\n agentName: agent.name,\n input,\n output: result.output,\n tokenUsage: result.totalTokens,\n durationMs: Date.now() - startTime,\n timestamp: Date.now(),\n });\n\n if (timeline) {\n const outputStr =\n typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output);\n timeline.record({\n type: \"agent_complete\",\n timestamp: Date.now(),\n agentId: agent.name,\n snapshotId: null,\n outputLength: outputStr?.length ?? 0,\n totalTokens: result.totalTokens,\n inputTokens: result.tokenUsage?.inputTokens ?? 0,\n outputTokens: result.tokenUsage?.outputTokens ?? 0,\n durationMs: Date.now() - startTime,\n modelId: agent.model ?? undefined,\n output: outputStr.slice(0, MAX_VERBOSE_LENGTH),\n });\n }\n\n // Breakpoint: post_run\n if (breakpoints && breakpoints.length > 0) {\n const bpContext: BreakpointContext = {\n agentId: agent.name,\n agentName: agent.name,\n input,\n state: system.facts.$store.toObject(),\n breakpointType: \"post_run\",\n };\n const mods = await handleBreakpoint(\n \"post_run\",\n bpContext,\n callOptions?.signal ?? opts?.signal,\n );\n if (mods?.skip) {\n return {\n output: undefined as T,\n messages: [],\n toolCalls: [],\n totalTokens: 0,\n };\n }\n if (mods?.input) {\n input = mods.input;\n }\n }\n\n return result;\n }\n\n // Assign the function to the forward-declared variable\n runAgentWithGuardrailsFn = runAgentWithGuardrails;\n\n // ---- Breakpoint infrastructure ----\n const breakpointModifications = new Map<string, BreakpointModifications>();\n const breakpointCancelReasons = new Map<string, string>();\n\n function waitForBreakpointResolution(\n bpId: string,\n signal?: AbortSignal,\n ): Promise<BreakpointModifications | null> {\n if (signal?.aborted) {\n return Promise.reject(\n signal.reason ?? new Error(\"Aborted while waiting for breakpoint\"),\n );\n }\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanupAll = () => {\n if (settled) {\n return;\n }\n\n settled = true;\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n unsubscribe();\n };\n\n const onAbort = () => {\n cleanupAll();\n reject(\n signal!.reason ?? new Error(`Breakpoint wait for ${bpId} aborted`),\n );\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const unsubscribe = system.facts.$store.subscribe(\n [BREAKPOINT_KEY],\n () => {\n if (settled) {\n return;\n }\n\n const bpState = getBreakpointState(system.facts);\n if (bpState.resolved.includes(bpId)) {\n cleanupAll();\n const mods = breakpointModifications.get(bpId) ?? null;\n breakpointModifications.delete(bpId);\n resolve(mods);\n } else if (bpState.cancelled.includes(bpId)) {\n cleanupAll();\n breakpointModifications.delete(bpId);\n const cancelReason = breakpointCancelReasons.get(bpId);\n breakpointCancelReasons.delete(bpId);\n reject(\n new Error(\n cancelReason\n ? `Breakpoint ${bpId} was cancelled: ${cancelReason}`\n : `Breakpoint ${bpId} was cancelled`,\n ),\n );\n }\n },\n );\n\n const bpTimeout = breakpointTimeoutMs ?? 300000;\n timeoutId = setTimeout(() => {\n if (settled) {\n return;\n }\n\n cleanupAll();\n breakpointModifications.delete(bpId);\n breakpointCancelReasons.delete(bpId);\n reject(\n new Error(\n `[Directive] Breakpoint timeout: ${bpId} not resolved within ${Math.round(bpTimeout / 1000)}s`,\n ),\n );\n }, bpTimeout);\n });\n }\n\n async function handleBreakpoint(\n type: string,\n context: BreakpointContext,\n signal?: AbortSignal,\n ): Promise<BreakpointModifications | null> {\n if (!breakpoints || breakpoints.length === 0) {\n return null;\n }\n\n const match = matchBreakpoint(\n breakpoints as BreakpointConfig<string>[],\n type,\n context,\n );\n if (!match) {\n return null;\n }\n\n const bpId = createBreakpointId();\n const request: BreakpointRequest = {\n id: bpId,\n type,\n agentId: context.agentId,\n input: context.input,\n label: match.label,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n setBreakpointState(system.facts, {\n ...bpState,\n pending: [...bpState.pending, request],\n });\n });\n\n try {\n onBreakpoint?.(request);\n } catch {\n /* non-fatal */\n }\n try {\n hooks.onBreakpoint?.(request);\n } catch {\n /* non-fatal */\n }\n\n if (timeline) {\n timeline.record({\n type: \"breakpoint_hit\",\n timestamp: Date.now(),\n snapshotId: null,\n agentId: context.agentId,\n breakpointId: bpId,\n breakpointType: type,\n label: match.label,\n });\n }\n\n const mods = await waitForBreakpointResolution(bpId, signal);\n\n if (timeline) {\n timeline.record({\n type: \"breakpoint_resumed\",\n timestamp: Date.now(),\n snapshotId: null,\n agentId: context.agentId,\n breakpointId: bpId,\n modified: !!mods?.input,\n skipped: !!mods?.skip,\n });\n }\n\n return mods;\n }\n\n // Wait for approval with configurable timeout and abort signal support\n function waitForApproval(\n requestId: string,\n signal?: AbortSignal,\n ): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(\n signal.reason ?? new Error(\"Aborted while waiting for approval\"),\n );\n }\n\n return new Promise((resolve, reject) => {\n let settled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanupAll = () => {\n if (settled) {\n return;\n }\n\n settled = true;\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n unsubscribe();\n };\n\n const onAbort = () => {\n cleanupAll();\n reject(\n signal!.reason ?? new Error(`Approval wait for ${requestId} aborted`),\n );\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const unsubscribe = system.facts.$store.subscribe([APPROVAL_KEY], () => {\n if (settled) {\n return;\n }\n\n const approval = getApprovalState(system.facts);\n if (approval.approved.includes(requestId)) {\n cleanupAll();\n resolve();\n } else {\n const rejectedRequest = approval.rejected.find(\n (r) => r.id === requestId,\n );\n if (rejectedRequest) {\n cleanupAll();\n const errorMsg = rejectedRequest.reason\n ? `Request ${requestId} rejected: ${rejectedRequest.reason}`\n : `Request ${requestId} rejected`;\n reject(new Error(errorMsg));\n }\n }\n });\n\n // Set timeout to prevent indefinite hanging (uses configured approvalTimeoutMs)\n timeoutId = setTimeout(() => {\n if (settled) {\n return;\n }\n\n cleanupAll();\n const timeoutSeconds = Math.round(approvalTimeoutMs / 1000);\n reject(\n new Error(\n `[Directive] Approval timeout: Request ${requestId} not resolved within ${timeoutSeconds}s.\\n` +\n \"Solutions:\\n\" +\n \" 1. Handle via onApprovalRequest callback and call orchestrator.approve()/reject()\\n\" +\n \" 2. Set autoApproveToolCalls: true to auto-approve\\n\" +\n ` 3. Increase approvalTimeoutMs (current: ${approvalTimeoutMs}ms)\\n` +\n \"See: https://directive.run/docs/ai/running-agents\",\n ),\n );\n }, approvalTimeoutMs);\n });\n }\n\n /** Get facts as the combined type for external access */\n function getCombinedFacts(): F & OrchestratorState {\n const state = getOrchestratorState(system.facts);\n\n return { ...state } as unknown as F & OrchestratorState;\n }\n\n const orchestrator: AgentOrchestrator<F> = {\n system: system as unknown as System<any>,\n get facts() {\n return getCombinedFacts();\n },\n get totalTokens() {\n return getAgentState(system.facts).tokenUsage;\n },\n get timeline() {\n return timeline;\n },\n\n async run<T>(\n agent: AgentLike,\n input: string,\n options?: RunCallOptions,\n ): Promise<RunResult<T>> {\n return runAgentWithGuardrails<T>(\n agent,\n input,\n getCombinedFacts(),\n undefined,\n options,\n );\n },\n\n runStream<T>(\n agent: AgentLike,\n input: string,\n options: { signal?: AbortSignal } = {},\n ): OrchestratorStreamResult<T> {\n const abortController = new AbortController();\n const MAX_STREAM_BUFFER = 10_000;\n const chunks: OrchestratorStreamChunk[] = [];\n const waiters: Array<(chunk: OrchestratorStreamChunk | null) => void> =\n [];\n let closed = false;\n const startTime = Date.now();\n let tokenCount = 0;\n const MAX_ACCUMULATED_OUTPUT = 100_000;\n let accumulatedOutput = \"\";\n\n // Combine external abort signal\n let abortHandler: (() => void) | undefined;\n if (options.signal) {\n abortHandler = () => abortController.abort();\n options.signal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n\n const cleanup = () => {\n if (abortHandler && options.signal) {\n options.signal.removeEventListener(\"abort\", abortHandler);\n }\n };\n\n // Push a chunk to the stream\n const pushChunk = (chunk: OrchestratorStreamChunk) => {\n if (closed) return;\n const waiter = waiters.shift();\n if (waiter) {\n waiter(chunk);\n } else {\n chunks.push(chunk);\n // FIFO eviction when buffer exceeds max\n if (chunks.length > MAX_STREAM_BUFFER) {\n chunks.shift();\n }\n }\n };\n\n // Close the stream\n const closeStream = () => {\n closed = true;\n cleanup();\n for (const waiter of waiters) {\n waiter(null);\n }\n waiters.length = 0;\n };\n\n // Run the agent with streaming callbacks\n const resultPromise = (async (): Promise<RunResult<T>> => {\n pushChunk({\n type: \"progress\",\n phase: \"starting\",\n message: \"Running input guardrails\",\n });\n\n try {\n // Run input guardrails first with retry support\n let processedInput = input;\n const inputGuardrails = (guardrails.input ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"input\"),\n );\n for (const guardrail of inputGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const result = await executeGuardrailWithRetry(\n guardrail,\n { input: processedInput, agentName: agent.name },\n context,\n );\n if (!result.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: result.reason ?? \"Input validation failed\",\n partialOutput: accumulatedOutput,\n stopped: true,\n });\n throw new GuardrailError({\n code: \"INPUT_GUARDRAIL_FAILED\",\n message: `Input guardrail \"${name}\" failed: ${result.reason}`,\n guardrailName: name,\n guardrailType: \"input\",\n userMessage: result.reason ?? \"Input validation failed\",\n agentName: agent.name,\n input: processedInput,\n });\n }\n if (result.transformed !== undefined) {\n processedInput = result.transformed as string;\n }\n }\n\n pushChunk({\n type: \"progress\",\n phase: \"generating\",\n message: \"Starting agent\",\n });\n\n // Update state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"running\",\n currentAgent: agent.name,\n input: processedInput,\n startedAt: Date.now(),\n });\n });\n\n // Run agent with streaming callbacks and retry support\n const result = await executeAgentWithRetry<T>(\n runner,\n agent,\n processedInput,\n {\n signal: abortController.signal,\n onMessage: (message) => {\n const currentConversation = getConversation(system.facts);\n setConversation(system.facts, [\n ...currentConversation,\n message,\n ]);\n pushChunk({ type: \"message\", message });\n\n // Approximate token counting from content\n if (message.role === \"assistant\" && message.content) {\n const newTokens = Math.ceil(message.content.length / 4);\n tokenCount += newTokens;\n accumulatedOutput += message.content;\n if (accumulatedOutput.length > MAX_ACCUMULATED_OUTPUT) {\n accumulatedOutput = accumulatedOutput.slice(\n -MAX_ACCUMULATED_OUTPUT,\n );\n }\n pushChunk({\n type: \"token\",\n data: message.content,\n tokenCount,\n });\n }\n },\n onToolCall: async (toolCall) => {\n pushChunk({\n type: \"tool_start\",\n tool: toolCall.name,\n toolCallId: toolCall.id,\n arguments: toolCall.arguments,\n });\n\n // Run tool call guardrails with retry support\n const toolCallGuardrails = (guardrails.toolCall ?? []).map(\n (g, i) => normalizeGuardrail(g, i, \"toolCall\"),\n );\n for (const guardrail of toolCallGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n { toolCall, agentName: agent.name, input: processedInput },\n context,\n );\n if (!guardResult.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: guardResult.reason ?? \"Tool call blocked\",\n partialOutput: accumulatedOutput,\n stopped: true,\n });\n throw new GuardrailError({\n code: \"TOOL_CALL_GUARDRAIL_FAILED\",\n message: `Tool call guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"toolCall\",\n userMessage: guardResult.reason ?? \"Tool call blocked\",\n data: { toolCall },\n agentName: agent.name,\n input: processedInput,\n });\n }\n }\n\n // Check if approval is needed\n if (!autoApproveToolCalls) {\n const approvalId = `tool-${toolCall.id}`;\n pushChunk({\n type: \"approval_required\",\n requestId: approvalId,\n toolName: toolCall.name,\n });\n\n const approvalRequest: ApprovalRequest = {\n id: approvalId,\n type: \"tool_call\",\n agentName: agent.name,\n description: `Tool call: ${toolCall.name}`,\n data: toolCall,\n requestedAt: Date.now(),\n };\n\n system.batch(() => {\n const currentApproval = getApprovalState(system.facts);\n setApprovalState(system.facts, {\n ...currentApproval,\n pending: [...currentApproval.pending, approvalRequest],\n });\n });\n\n onApprovalRequest?.(approvalRequest);\n await waitForApproval(approvalId, abortController.signal);\n pushChunk({\n type: \"approval_resolved\",\n requestId: approvalId,\n approved: true,\n });\n }\n\n const currentToolCalls = getToolCalls(system.facts);\n setToolCalls(system.facts, [...currentToolCalls, toolCall]);\n\n if (toolCall.result) {\n pushChunk({\n type: \"tool_end\",\n tool: toolCall.name,\n toolCallId: toolCall.id,\n result: toolCall.result,\n });\n }\n },\n },\n agentRetry,\n );\n\n // Run output guardrails\n pushChunk({\n type: \"progress\",\n phase: \"finishing\",\n message: \"Running output guardrails\",\n });\n\n const outputGuardrails = (guardrails.output ?? []).map((g, i) =>\n normalizeGuardrail(g, i, \"output\"),\n );\n for (const guardrail of outputGuardrails) {\n const { name } = guardrail;\n const context = {\n agentName: agent.name,\n input: processedInput,\n facts: system.facts.$store.toObject(),\n };\n const guardResult = await executeGuardrailWithRetry(\n guardrail,\n {\n output: result.output,\n agentName: agent.name,\n input: processedInput,\n messages: result.messages,\n },\n context,\n );\n if (!guardResult.passed) {\n pushChunk({\n type: \"guardrail_triggered\",\n guardrailName: name,\n reason: guardResult.reason ?? \"Output validation failed\",\n partialOutput:\n typeof result.output === \"string\" ? result.output : \"\",\n stopped: true,\n });\n throw new GuardrailError({\n code: \"OUTPUT_GUARDRAIL_FAILED\",\n message: `Output guardrail \"${name}\" failed: ${guardResult.reason}`,\n guardrailName: name,\n guardrailType: \"output\",\n userMessage: guardResult.reason ?? \"Output validation failed\",\n agentName: agent.name,\n input: processedInput,\n });\n }\n if (guardResult.transformed !== undefined) {\n (result as { output: unknown }).output = guardResult.transformed;\n }\n }\n\n // Update final state\n system.batch(() => {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"completed\",\n output: result.output,\n tokenUsage: currentAgent.tokenUsage + result.totalTokens,\n turnCount: currentAgent.turnCount + result.messages.length,\n completedAt: Date.now(),\n });\n });\n\n const duration = Date.now() - startTime;\n pushChunk({\n type: \"done\",\n totalTokens: result.totalTokens,\n duration,\n droppedTokens: 0,\n });\n closeStream();\n\n return result;\n } catch (error) {\n pushChunk({\n type: \"error\",\n error: error instanceof Error ? error : new Error(String(error)),\n });\n closeStream();\n throw error;\n }\n })();\n\n // Prevent unhandled rejection if caller only consumes stream (not .result)\n resultPromise.catch(() => {});\n\n // Create async iterator\n const stream: AsyncIterable<OrchestratorStreamChunk> = {\n [Symbol.asyncIterator](): AsyncIterator<OrchestratorStreamChunk> {\n return {\n async next(): Promise<IteratorResult<OrchestratorStreamChunk>> {\n if (chunks.length > 0) {\n return { done: false, value: chunks.shift()! };\n }\n if (closed) {\n return { done: true, value: undefined };\n }\n\n return new Promise<IteratorResult<OrchestratorStreamChunk>>(\n (resolve) => {\n waiters.push((chunk) => {\n if (chunk === null) {\n resolve({ done: true, value: undefined });\n } else {\n resolve({ done: false, value: chunk });\n }\n });\n },\n );\n },\n };\n },\n };\n\n return {\n stream,\n result: resultPromise,\n abort: () => {\n abortController.abort();\n closeStream();\n },\n };\n },\n\n async waitForIdle(timeoutMs?: number): Promise<void> {\n const isIdle = () => getAgentState(system.facts).status !== \"running\";\n if (isIdle()) {\n return;\n }\n\n const start = Date.now();\n while (!isIdle()) {\n if (timeoutMs !== undefined && Date.now() - start > timeoutMs) {\n throw new Error(\"[Directive Orchestrator] waitForIdle timed out\");\n }\n await new Promise((r) => setTimeout(r, 50));\n }\n },\n\n approve(requestId: string): void {\n system.batch(() => {\n const approval = getApprovalState(system.facts);\n if (!approval.pending.some((r) => r.id === requestId)) {\n if (debug)\n console.debug(\n `[Directive] approve() ignored: no pending request \"${requestId}\"`,\n );\n\n return;\n }\n const MAX_APPROVAL_HISTORY = 200;\n const approved = [...approval.approved, requestId];\n setApprovalState(system.facts, {\n ...approval,\n pending: approval.pending.filter((r) => r.id !== requestId),\n approved:\n approved.length > MAX_APPROVAL_HISTORY\n ? approved.slice(-MAX_APPROVAL_HISTORY)\n : approved,\n });\n });\n },\n\n reject(requestId: string, reason?: string): void {\n system.batch(() => {\n const approval = getApprovalState(system.facts);\n if (!approval.pending.some((r) => r.id === requestId)) {\n if (debug)\n console.debug(\n `[Directive] reject() ignored: no pending request \"${requestId}\"`,\n );\n\n return;\n }\n if (reason && debug) {\n console.debug(`[Directive] Request ${requestId} rejected: ${reason}`);\n }\n const rejectedRequest: RejectedRequest = {\n id: requestId,\n reason,\n rejectedAt: Date.now(),\n };\n const MAX_REJECTION_HISTORY = 200;\n const rejected = [...approval.rejected, rejectedRequest];\n setApprovalState(system.facts, {\n ...approval,\n pending: approval.pending.filter((r) => r.id !== requestId),\n rejected:\n rejected.length > MAX_REJECTION_HISTORY\n ? rejected.slice(-MAX_REJECTION_HISTORY)\n : rejected,\n });\n });\n },\n\n pause(): void {\n const currentAgent = getAgentState(system.facts);\n setAgentState(system.facts, {\n ...currentAgent,\n status: \"paused\",\n });\n },\n\n resume(): void {\n const agent = getAgentState(system.facts);\n if (agent.status === \"paused\") {\n setAgentState(system.facts, {\n ...agent,\n status: agent.currentAgent ? \"running\" : \"idle\",\n });\n }\n },\n\n reset(): void {\n system.batch(() => {\n setAgentState(system.facts, {\n status: \"idle\",\n currentAgent: null,\n input: null,\n output: null,\n error: null,\n tokenUsage: 0,\n turnCount: 0,\n startedAt: null,\n completedAt: null,\n });\n setApprovalState(system.facts, {\n pending: [],\n approved: [],\n rejected: [],\n });\n setConversation(system.facts, []);\n setToolCalls(system.facts, []);\n setBreakpointState(system.facts, {\n pending: [],\n resolved: [],\n cancelled: [],\n });\n setBridgeFact(system.facts, \"__budgetWarningFired\", false);\n });\n breakpointModifications.clear();\n breakpointCancelReasons.clear();\n },\n\n async checkpoint(cpOptions?: { label?: string }): Promise<Checkpoint> {\n const agentState = getAgentState(system.facts);\n if (agentState.status === \"running\") {\n throw new Error(\"[Directive] Cannot checkpoint while agent is running\");\n }\n if (!system.history?.export) {\n throw new Error(\n \"[Directive] Checkpointing requires history. Set `debug: true` in orchestrator options.\",\n );\n }\n\n const cp: Checkpoint = {\n version: 1,\n id: createCheckpointId(),\n createdAt: new Date().toISOString(),\n label: cpOptions?.label,\n systemExport: system.history.export(),\n timelineExport: timeline?.export() ?? null,\n localState: { type: \"single\" },\n memoryExport: memory ? ((memory as any).export?.() ?? null) : null,\n orchestratorType: \"single\",\n };\n\n if (checkpointStore) {\n await checkpointStore.save(cp);\n }\n\n return cp;\n },\n\n restore(cp: Checkpoint, restoreOpts?: { restoreTimeline?: boolean }): void {\n if (!validateCheckpoint(cp)) {\n throw new Error(\"[Directive] Invalid checkpoint data\");\n }\n if (cp.orchestratorType !== \"single\") {\n throw new Error(\n \"[Directive] Cannot restore multi-agent checkpoint in single-agent orchestrator\",\n );\n }\n if (!system.history?.import) {\n throw new Error(\n \"[Directive] Restoring a checkpoint requires history. Set `debug: true` in orchestrator options.\",\n );\n }\n\n system.history.import(cp.systemExport);\n\n if (\n restoreOpts?.restoreTimeline !== false &&\n cp.timelineExport &&\n timeline\n ) {\n timeline.import(cp.timelineExport);\n }\n\n if (cp.memoryExport !== null && memory && (memory as any).import) {\n (memory as any).import(cp.memoryExport);\n }\n },\n\n resumeBreakpoint(\n id: string,\n modifications?: BreakpointModifications,\n ): void {\n if (modifications) {\n breakpointModifications.set(id, modifications);\n }\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n const resolved = [...bpState.resolved, id];\n setBreakpointState(system.facts, {\n ...bpState,\n pending: bpState.pending.filter((r) => r.id !== id),\n resolved:\n resolved.length > MAX_BREAKPOINT_HISTORY\n ? resolved.slice(-MAX_BREAKPOINT_HISTORY)\n : resolved,\n });\n });\n },\n\n cancelBreakpoint(id: string, reason?: string): void {\n if (reason) {\n breakpointCancelReasons.set(id, reason);\n }\n system.batch(() => {\n const bpState = getBreakpointState(system.facts);\n const cancelled = [...bpState.cancelled, id];\n setBreakpointState(system.facts, {\n ...bpState,\n pending: bpState.pending.filter((r) => r.id !== id),\n cancelled:\n cancelled.length > MAX_BREAKPOINT_HISTORY\n ? cancelled.slice(-MAX_BREAKPOINT_HISTORY)\n : cancelled,\n });\n });\n },\n\n getPendingBreakpoints(): BreakpointRequest[] {\n const bpState = getBreakpointState(system.facts);\n\n return [...bpState.pending];\n },\n\n destroy(): void {\n system.destroy();\n },\n };\n\n return orchestrator;\n}\n"]}
|