@directive-run/ai 1.22.0 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/{chunk-IR3IHBVQ.cjs → chunk-7JTR4QBA.cjs} +2 -2
  2. package/dist/{chunk-IR3IHBVQ.cjs.map → chunk-7JTR4QBA.cjs.map} +1 -1
  3. package/dist/{chunk-G7CRWJT7.js → chunk-7KCLEIAG.js} +3 -3
  4. package/dist/chunk-7KCLEIAG.js.map +1 -0
  5. package/dist/{chunk-5JQ2A3JK.js → chunk-BZB3RDI2.js} +2 -2
  6. package/dist/{chunk-5JQ2A3JK.js.map → chunk-BZB3RDI2.js.map} +1 -1
  7. package/dist/{chunk-RHJAMXLS.js → chunk-CXWHLEBQ.js} +3 -3
  8. package/dist/{chunk-RHJAMXLS.js.map → chunk-CXWHLEBQ.js.map} +1 -1
  9. package/dist/{chunk-TH2D22JP.cjs → chunk-ESJQSOKJ.cjs} +7 -7
  10. package/dist/chunk-ESJQSOKJ.cjs.map +1 -0
  11. package/dist/{chunk-7EJN6TYX.cjs → chunk-GWWZXJOG.cjs} +3 -3
  12. package/dist/chunk-GWWZXJOG.cjs.map +1 -0
  13. package/dist/{chunk-QRDBUGPO.js → chunk-LOHC2KP5.js} +3 -3
  14. package/dist/chunk-LOHC2KP5.js.map +1 -0
  15. package/dist/{chunk-ZGJ2XHGI.cjs → chunk-MPMBFW2P.cjs} +2 -2
  16. package/dist/chunk-MPMBFW2P.cjs.map +1 -0
  17. package/dist/{chunk-XGHNOSXT.cjs → chunk-PEM2LPOC.cjs} +4 -4
  18. package/dist/{chunk-XGHNOSXT.cjs.map → chunk-PEM2LPOC.cjs.map} +1 -1
  19. package/dist/{chunk-VSVR4RFK.js → chunk-TEPEQE42.js} +2 -2
  20. package/dist/chunk-TEPEQE42.js.map +1 -0
  21. package/dist/devtools.cjs +1 -1
  22. package/dist/devtools.js +1 -1
  23. package/dist/guardrails.cjs +1 -1
  24. package/dist/guardrails.js +1 -1
  25. package/dist/index.cjs +4 -4
  26. package/dist/index.js +1 -1
  27. package/dist/{multi-agent-orchestrator-RMTLPKB4.js → multi-agent-orchestrator-FIF4GLVR.js} +2 -2
  28. package/dist/{multi-agent-orchestrator-RMTLPKB4.js.map → multi-agent-orchestrator-FIF4GLVR.js.map} +1 -1
  29. package/dist/multi-agent-orchestrator-PHDHFCW3.cjs +2 -0
  30. package/dist/{multi-agent-orchestrator-OX2TKD5Y.cjs.map → multi-agent-orchestrator-PHDHFCW3.cjs.map} +1 -1
  31. package/dist/multi-agent.cjs +1 -1
  32. package/dist/multi-agent.js +1 -1
  33. package/dist/testing.cjs +1 -1
  34. package/dist/testing.js +1 -1
  35. package/package.json +2 -2
  36. package/dist/chunk-7EJN6TYX.cjs.map +0 -1
  37. package/dist/chunk-G7CRWJT7.js.map +0 -1
  38. package/dist/chunk-QRDBUGPO.js.map +0 -1
  39. package/dist/chunk-TH2D22JP.cjs.map +0 -1
  40. package/dist/chunk-VSVR4RFK.js.map +0 -1
  41. package/dist/chunk-ZGJ2XHGI.cjs.map +0 -1
  42. package/dist/multi-agent-orchestrator-OX2TKD5Y.cjs +0 -2
package/dist/devtools.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkIR3IHBVQ_cjs=require('./chunk-IR3IHBVQ.cjs'),chunkWOFIBIPW_cjs=require('./chunk-WOFIBIPW.cjs');Object.defineProperty(exports,"connectDevTools",{enumerable:true,get:function(){return chunkIR3IHBVQ_cjs.b}});Object.defineProperty(exports,"createDevToolsServer",{enumerable:true,get:function(){return chunkIR3IHBVQ_cjs.a}});Object.defineProperty(exports,"createWsTransport",{enumerable:true,get:function(){return chunkIR3IHBVQ_cjs.c}});Object.defineProperty(exports,"createDebugTimeline",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.a}});Object.defineProperty(exports,"createDebugTimelinePlugin",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.b}});Object.defineProperty(exports,"createHealthMonitor",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.c}});//# sourceMappingURL=devtools.cjs.map
1
+ 'use strict';var chunk7JTR4QBA_cjs=require('./chunk-7JTR4QBA.cjs'),chunkWOFIBIPW_cjs=require('./chunk-WOFIBIPW.cjs');Object.defineProperty(exports,"connectDevTools",{enumerable:true,get:function(){return chunk7JTR4QBA_cjs.b}});Object.defineProperty(exports,"createDevToolsServer",{enumerable:true,get:function(){return chunk7JTR4QBA_cjs.a}});Object.defineProperty(exports,"createWsTransport",{enumerable:true,get:function(){return chunk7JTR4QBA_cjs.c}});Object.defineProperty(exports,"createDebugTimeline",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.a}});Object.defineProperty(exports,"createDebugTimelinePlugin",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.b}});Object.defineProperty(exports,"createHealthMonitor",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.c}});//# sourceMappingURL=devtools.cjs.map
2
2
  //# sourceMappingURL=devtools.cjs.map
package/dist/devtools.js CHANGED
@@ -1,2 +1,2 @@
1
- export{b as connectDevTools,a as createDevToolsServer,c as createWsTransport}from'./chunk-5JQ2A3JK.js';export{a as createDebugTimeline,b as createDebugTimelinePlugin,c as createHealthMonitor}from'./chunk-FBT73WFY.js';//# sourceMappingURL=devtools.js.map
1
+ export{b as connectDevTools,a as createDevToolsServer,c as createWsTransport}from'./chunk-BZB3RDI2.js';export{a as createDebugTimeline,b as createDebugTimelinePlugin,c as createHealthMonitor}from'./chunk-FBT73WFY.js';//# sourceMappingURL=devtools.js.map
2
2
  //# sourceMappingURL=devtools.js.map
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkZGJ2XHGI_cjs=require('./chunk-ZGJ2XHGI.cjs');require('./chunk-K64WKZ22.cjs');Object.defineProperty(exports,"DEFAULT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.o}});Object.defineProperty(exports,"STRICT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.p}});Object.defineProperty(exports,"createBatchedEmbedder",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.A}});Object.defineProperty(exports,"createBruteForceIndex",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.B}});Object.defineProperty(exports,"createContentFilterGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.h}});Object.defineProperty(exports,"createEnhancedPIIGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.k}});Object.defineProperty(exports,"createFactPIIGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.i}});Object.defineProperty(exports,"createInMemoryStorage",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.w}});Object.defineProperty(exports,"createLengthGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.g}});Object.defineProperty(exports,"createModerationGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.b}});Object.defineProperty(exports,"createOutputPIIGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.l}});Object.defineProperty(exports,"createOutputSchemaGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.e}});Object.defineProperty(exports,"createOutputTypeGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.f}});Object.defineProperty(exports,"createPIIGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.a}});Object.defineProperty(exports,"createPromptInjectionGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.s}});Object.defineProperty(exports,"createRateLimitGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.c}});Object.defineProperty(exports,"createSemanticCache",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.x}});Object.defineProperty(exports,"createSemanticCacheGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.y}});Object.defineProperty(exports,"createTestEmbedder",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.z}});Object.defineProperty(exports,"createToolGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.d}});Object.defineProperty(exports,"createUntrustedContentGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.u}});Object.defineProperty(exports,"createVPTreeIndex",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.C}});Object.defineProperty(exports,"detectAndRedactPII",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.n}});Object.defineProperty(exports,"detectPII",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.m}});Object.defineProperty(exports,"detectPromptInjection",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.q}});Object.defineProperty(exports,"markUntrustedContent",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.t}});Object.defineProperty(exports,"redactPII",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.j}});Object.defineProperty(exports,"sanitizeInjection",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.r}});//# sourceMappingURL=guardrails.cjs.map
1
+ 'use strict';var chunkMPMBFW2P_cjs=require('./chunk-MPMBFW2P.cjs');require('./chunk-K64WKZ22.cjs');Object.defineProperty(exports,"DEFAULT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.o}});Object.defineProperty(exports,"STRICT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.p}});Object.defineProperty(exports,"createBatchedEmbedder",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.A}});Object.defineProperty(exports,"createBruteForceIndex",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.B}});Object.defineProperty(exports,"createContentFilterGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.h}});Object.defineProperty(exports,"createEnhancedPIIGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.k}});Object.defineProperty(exports,"createFactPIIGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.i}});Object.defineProperty(exports,"createInMemoryStorage",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.w}});Object.defineProperty(exports,"createLengthGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.g}});Object.defineProperty(exports,"createModerationGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.b}});Object.defineProperty(exports,"createOutputPIIGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.l}});Object.defineProperty(exports,"createOutputSchemaGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.e}});Object.defineProperty(exports,"createOutputTypeGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.f}});Object.defineProperty(exports,"createPIIGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.a}});Object.defineProperty(exports,"createPromptInjectionGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.s}});Object.defineProperty(exports,"createRateLimitGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.c}});Object.defineProperty(exports,"createSemanticCache",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.x}});Object.defineProperty(exports,"createSemanticCacheGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.y}});Object.defineProperty(exports,"createTestEmbedder",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.z}});Object.defineProperty(exports,"createToolGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.d}});Object.defineProperty(exports,"createUntrustedContentGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.u}});Object.defineProperty(exports,"createVPTreeIndex",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.C}});Object.defineProperty(exports,"detectAndRedactPII",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.n}});Object.defineProperty(exports,"detectPII",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.m}});Object.defineProperty(exports,"detectPromptInjection",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.q}});Object.defineProperty(exports,"markUntrustedContent",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.t}});Object.defineProperty(exports,"redactPII",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.j}});Object.defineProperty(exports,"sanitizeInjection",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.r}});//# sourceMappingURL=guardrails.cjs.map
2
2
  //# sourceMappingURL=guardrails.cjs.map
@@ -1,2 +1,2 @@
1
- export{o as DEFAULT_INJECTION_PATTERNS,p as STRICT_INJECTION_PATTERNS,A as createBatchedEmbedder,B as createBruteForceIndex,h as createContentFilterGuardrail,k as createEnhancedPIIGuardrail,i as createFactPIIGuardrail,w as createInMemoryStorage,g as createLengthGuardrail,b as createModerationGuardrail,l as createOutputPIIGuardrail,e as createOutputSchemaGuardrail,f as createOutputTypeGuardrail,a as createPIIGuardrail,s as createPromptInjectionGuardrail,c as createRateLimitGuardrail,x as createSemanticCache,y as createSemanticCacheGuardrail,z as createTestEmbedder,d as createToolGuardrail,u as createUntrustedContentGuardrail,C as createVPTreeIndex,n as detectAndRedactPII,m as detectPII,q as detectPromptInjection,t as markUntrustedContent,j as redactPII,r as sanitizeInjection}from'./chunk-VSVR4RFK.js';import'./chunk-UR5BMWEN.js';//# sourceMappingURL=guardrails.js.map
1
+ export{o as DEFAULT_INJECTION_PATTERNS,p as STRICT_INJECTION_PATTERNS,A as createBatchedEmbedder,B as createBruteForceIndex,h as createContentFilterGuardrail,k as createEnhancedPIIGuardrail,i as createFactPIIGuardrail,w as createInMemoryStorage,g as createLengthGuardrail,b as createModerationGuardrail,l as createOutputPIIGuardrail,e as createOutputSchemaGuardrail,f as createOutputTypeGuardrail,a as createPIIGuardrail,s as createPromptInjectionGuardrail,c as createRateLimitGuardrail,x as createSemanticCache,y as createSemanticCacheGuardrail,z as createTestEmbedder,d as createToolGuardrail,u as createUntrustedContentGuardrail,C as createVPTreeIndex,n as detectAndRedactPII,m as detectPII,q as detectPromptInjection,t as markUntrustedContent,j as redactPII,r as sanitizeInjection}from'./chunk-TEPEQE42.js';import'./chunk-UR5BMWEN.js';//# sourceMappingURL=guardrails.js.map
2
2
  //# sourceMappingURL=guardrails.js.map
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkZGJ2XHGI_cjs=require('./chunk-ZGJ2XHGI.cjs'),chunkIR3IHBVQ_cjs=require('./chunk-IR3IHBVQ.cjs'),chunkXN5LUOVS_cjs=require('./chunk-XN5LUOVS.cjs'),chunkC6MQ4WL6_cjs=require('./chunk-C6MQ4WL6.cjs'),chunkTH2D22JP_cjs=require('./chunk-TH2D22JP.cjs'),chunk3WO4MWJM_cjs=require('./chunk-3WO4MWJM.cjs'),chunkXGHNOSXT_cjs=require('./chunk-XGHNOSXT.cjs'),chunk7EJN6TYX_cjs=require('./chunk-7EJN6TYX.cjs'),chunkK64WKZ22_cjs=require('./chunk-K64WKZ22.cjs'),chunkWOFIBIPW_cjs=require('./chunk-WOFIBIPW.cjs'),chunkMDXDPECP_cjs=require('./chunk-MDXDPECP.cjs'),chunkWCQK3JOR_cjs=require('./chunk-WCQK3JOR.cjs'),plugins=require('@directive-run/core/plugins'),G=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var G__default=/*#__PURE__*/_interopDefault(G);function Hr(r,...e){let t=r;for(let n of e)t=n(t);return t}function j(r,e){let t=typeof r.content=="string"?r.content:JSON.stringify(r.content);return Math.ceil(t.length/4)}function V(r,e){return r.reduce((t,n)=>t+j(n),0)}function X(r={}){return (e,t={})=>{let n={...r,...t},s=n.maxMessages??100,c=n.preserveRecentCount??5;if(e.length<=s)return {keep:[...e],toSummarize:[],estimatedTokens:V(e)};let o=e.slice(-c),u=e.slice(0,-c),a=Math.max(0,s-c),y=u.slice(-a),p=u.slice(0,-a||void 0),h=[...y,...o];return {keep:h,toSummarize:p.length>0?p:[],estimatedTokens:V(h)}}}function Y(r={}){return (e,t={})=>{let n={...r,...t},s=n.maxTokens??4e3,c=n.preserveRecentCount??5,o=n.countSystemMessages??true,u=e.slice(-c),a=e.slice(0,-c),y=u.reduce((l,g)=>!o&&g.role==="system"?l:l+j(g),0),p=[],h=[],m=y;for(let l=a.length-1;l>=0;l--){let g=a[l],C=!o&&g.role==="system"?0:j(g);if(m+C<=s)p.unshift(g),m+=C;else {h.push(...a.slice(0,l+1));break}}return {keep:[...p,...u],toSummarize:h,estimatedTokens:m}}}function Vr(r={}){let e=X(r),t=Y(r);return (n,s={})=>{let c={...r,...s},o=e(n,c),u=t(n,c);return o.keep.length<=u.keep.length?o:u}}function Kr(r){let{strategy:e,summarizer:t,strategyConfig:n={},autoManage:s=false,onMemoryManaged:c,onManageError:o,maxContextTokens:u}=r,a={messages:[],summaries:[],totalMessagesProcessed:0,estimatedTokens:0},y=false;async function p(){if(y)return {messagesBefore:a.messages.length,messagesAfter:a.messages.length,messagesSummarized:0,estimatedTokensBefore:a.estimatedTokens,estimatedTokensAfter:a.estimatedTokens};y=true;try{let m=a.messages.length,l=a.estimatedTokens,g=e(a.messages,n);if(g.toSummarize.length===0)return {messagesBefore:m,messagesAfter:m,messagesSummarized:0,estimatedTokensBefore:l,estimatedTokensAfter:g.estimatedTokens};let C;t&&g.toSummarize.length>0&&(C=await t(g.toSummarize),a.summaries.push({content:C,messagesCount:g.toSummarize.length,createdAt:Date.now()})),a.messages=g.keep,a.estimatedTokens=g.estimatedTokens;let E={messagesBefore:m,messagesAfter:a.messages.length,messagesSummarized:g.toSummarize.length,summary:C,estimatedTokensBefore:l,estimatedTokensAfter:g.estimatedTokens};return c?.(E),E}finally{y=false;}}function h(){if(y)return;e(a.messages,n).toSummarize.length>0&&p().catch(l=>{let g=l instanceof Error?l:new Error(String(l));o?o(g):console.error("[Directive Memory] Auto-manage error:",g);});}return {getState(){return {...a,messages:[...a.messages],summaries:a.summaries.map(m=>({...m}))}},addMessage(m){a.messages.push(m),a.totalMessagesProcessed++,a.estimatedTokens+=j(m),s&&h();},addMessages(m){for(let l of m)a.messages.push(l),a.totalMessagesProcessed++,a.estimatedTokens+=j(l);s&&h();},getContextMessages(){let m=[];if(a.summaries.length>0){let l=a.summaries.map(g=>g.content).join(`
1
+ 'use strict';var chunkMPMBFW2P_cjs=require('./chunk-MPMBFW2P.cjs'),chunk7JTR4QBA_cjs=require('./chunk-7JTR4QBA.cjs'),chunkXN5LUOVS_cjs=require('./chunk-XN5LUOVS.cjs'),chunkC6MQ4WL6_cjs=require('./chunk-C6MQ4WL6.cjs'),chunkESJQSOKJ_cjs=require('./chunk-ESJQSOKJ.cjs'),chunk3WO4MWJM_cjs=require('./chunk-3WO4MWJM.cjs'),chunkPEM2LPOC_cjs=require('./chunk-PEM2LPOC.cjs'),chunkGWWZXJOG_cjs=require('./chunk-GWWZXJOG.cjs'),chunkK64WKZ22_cjs=require('./chunk-K64WKZ22.cjs'),chunkWOFIBIPW_cjs=require('./chunk-WOFIBIPW.cjs'),chunkMDXDPECP_cjs=require('./chunk-MDXDPECP.cjs'),chunkWCQK3JOR_cjs=require('./chunk-WCQK3JOR.cjs'),plugins=require('@directive-run/core/plugins'),G=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var G__default=/*#__PURE__*/_interopDefault(G);function Hr(r,...e){let t=r;for(let n of e)t=n(t);return t}function j(r,e){let t=typeof r.content=="string"?r.content:JSON.stringify(r.content);return Math.ceil(t.length/4)}function V(r,e){return r.reduce((t,n)=>t+j(n),0)}function X(r={}){return (e,t={})=>{let n={...r,...t},s=n.maxMessages??100,c=n.preserveRecentCount??5;if(e.length<=s)return {keep:[...e],toSummarize:[],estimatedTokens:V(e)};let o=e.slice(-c),u=e.slice(0,-c),a=Math.max(0,s-c),y=u.slice(-a),p=u.slice(0,-a||void 0),h=[...y,...o];return {keep:h,toSummarize:p.length>0?p:[],estimatedTokens:V(h)}}}function Y(r={}){return (e,t={})=>{let n={...r,...t},s=n.maxTokens??4e3,c=n.preserveRecentCount??5,o=n.countSystemMessages??true,u=e.slice(-c),a=e.slice(0,-c),y=u.reduce((l,g)=>!o&&g.role==="system"?l:l+j(g),0),p=[],h=[],m=y;for(let l=a.length-1;l>=0;l--){let g=a[l],C=!o&&g.role==="system"?0:j(g);if(m+C<=s)p.unshift(g),m+=C;else {h.push(...a.slice(0,l+1));break}}return {keep:[...p,...u],toSummarize:h,estimatedTokens:m}}}function Vr(r={}){let e=X(r),t=Y(r);return (n,s={})=>{let c={...r,...s},o=e(n,c),u=t(n,c);return o.keep.length<=u.keep.length?o:u}}function Kr(r){let{strategy:e,summarizer:t,strategyConfig:n={},autoManage:s=false,onMemoryManaged:c,onManageError:o,maxContextTokens:u}=r,a={messages:[],summaries:[],totalMessagesProcessed:0,estimatedTokens:0},y=false;async function p(){if(y)return {messagesBefore:a.messages.length,messagesAfter:a.messages.length,messagesSummarized:0,estimatedTokensBefore:a.estimatedTokens,estimatedTokensAfter:a.estimatedTokens};y=true;try{let m=a.messages.length,l=a.estimatedTokens,g=e(a.messages,n);if(g.toSummarize.length===0)return {messagesBefore:m,messagesAfter:m,messagesSummarized:0,estimatedTokensBefore:l,estimatedTokensAfter:g.estimatedTokens};let C;t&&g.toSummarize.length>0&&(C=await t(g.toSummarize),a.summaries.push({content:C,messagesCount:g.toSummarize.length,createdAt:Date.now()})),a.messages=g.keep,a.estimatedTokens=g.estimatedTokens;let E={messagesBefore:m,messagesAfter:a.messages.length,messagesSummarized:g.toSummarize.length,summary:C,estimatedTokensBefore:l,estimatedTokensAfter:g.estimatedTokens};return c?.(E),E}finally{y=false;}}function h(){if(y)return;e(a.messages,n).toSummarize.length>0&&p().catch(l=>{let g=l instanceof Error?l:new Error(String(l));o?o(g):console.error("[Directive Memory] Auto-manage error:",g);});}return {getState(){return {...a,messages:[...a.messages],summaries:a.summaries.map(m=>({...m}))}},addMessage(m){a.messages.push(m),a.totalMessagesProcessed++,a.estimatedTokens+=j(m),s&&h();},addMessages(m){for(let l of m)a.messages.push(l),a.totalMessagesProcessed++,a.estimatedTokens+=j(l);s&&h();},getContextMessages(){let m=[];if(a.summaries.length>0){let l=a.summaries.map(g=>g.content).join(`
2
2
 
3
3
  ---
4
4
 
@@ -17,14 +17,14 @@ Focus on information that would be useful context for continuing the conversatio
17
17
  CONVERSATION:
18
18
  ${c}
19
19
 
20
- SUMMARY:`;return r(o)}}var Qr=1e4,Xr=10080*60*1e3,Yr=6e4,Z="0".repeat(64);function Zr(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function en(r){return new TextEncoder().encode(r)}function tn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}async function ee(r){let e=en(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return tn(new Uint8Array(t))}function te(r){let{id:e,timestamp:t,eventType:n,previousHash:s,payload:c,actorId:o,sessionId:u}=r;return JSON.stringify({id:e,timestamp:t,eventType:n,previousHash:s,payload:c,actorId:o,sessionId:u})}function rn(r){return JSON.parse(JSON.stringify(r))}async function nn(r,e){let t=rn(r);async function n(s){if(typeof s=="string"){let c=await chunkZGJ2XHGI_cjs.m(s,{types:e.types,minConfidence:e.minConfidence??.7});if(c.detected){let o=e.allowlist?c.items.filter(u=>!e.allowlist.includes(u.value.toLowerCase())):c.items;if(o.length>0)return chunkZGJ2XHGI_cjs.j(s,o,e.redactionStyle)}return s}if(Array.isArray(s))return Promise.all(s.map(n));if(s&&typeof s=="object"){let c={};for(let[o,u]of Object.entries(s))c[o]=await n(u);return c}return s}for(let[s,c]of Object.entries(t))t[s]=await n(c);return t}function on(r={}){let{maxEntries:e=Qr,retentionMs:t=Xr,exportInterval:n=Yr,exporter:s,piiMasking:c,signing:o,sessionId:u,actorId:a,events:y={}}=r,p=[],h=0,m=0,l=0,g=true,C;function E(){return p.length===0?Z:p[p.length-1].hash}async function S(d,f,b){let A={id:Zr(),timestamp:Date.now(),eventType:d,previousHash:E(),payload:f,actorId:a,sessionId:u};c?.enabled&&(A.maskedPayload=await nn(f,c));let x=te(A),w=await ee(x),P={...A,hash:w};for(o&&(P.signature=await o.signFn(w)),p.push(P);p.length>e;)p.shift(),m++,h>0&&h--;return y.onEntryAdded?.(P),P}return s&&n>0&&(C=setInterval(async()=>{try{let d=p.slice(h);d.length>0&&(await s(d),l+=d.length,h=p.length);}catch(d){y.onExportError?.(d instanceof Error?d:new Error(String(d)),p.slice(h));}},n)),{getEntries(d){let f=[...p];if(d){if(d.eventTypes?.length){let b=new Set(d.eventTypes);f=f.filter(A=>b.has(A.eventType));}d.actorId&&(f=f.filter(b=>b.actorId===d.actorId)),d.sessionId&&(f=f.filter(b=>b.sessionId===d.sessionId)),d.since!==void 0&&(f=f.filter(b=>b.timestamp>=d.since)),d.until!==void 0&&(f=f.filter(b=>b.timestamp<=d.until)),d.offset!==void 0&&(f=f.slice(d.offset)),d.limit!==void 0&&(f=f.slice(0,d.limit));}return f},async verifyChain(){if(p.length===0)return {valid:true,entriesVerified:0,verifiedAt:Date.now()};p[0].previousHash;for(let f=0;f<p.length;f++){let b=p[f],A=te({id:b.id,timestamp:b.timestamp,eventType:b.eventType,previousHash:b.previousHash,payload:b.payload,actorId:b.actorId,sessionId:b.sessionId}),x=await ee(A);if(b.hash!==x){g=false;let w={valid:false,entriesVerified:f,brokenAt:{index:f,entryId:b.id,expectedHash:x,actualHash:b.hash},verifiedAt:Date.now()};return y.onChainBroken?.(w),w}if(f>0){let w=p[f-1];if(b.previousHash!==w.hash){g=false;let P={valid:false,entriesVerified:f,brokenAt:{index:f,entryId:b.id,expectedHash:w.hash,actualHash:b.previousHash},verifiedAt:Date.now()};return y.onChainBroken?.(P),P}}if(o?.verifyFn&&b.signature&&!await o.verifyFn(b.hash,b.signature)){g=false;let P={valid:false,entriesVerified:f,brokenAt:{index:f,entryId:b.id,expectedHash:"signature-invalid",actualHash:b.signature},verifiedAt:Date.now()};return y.onChainBroken?.(P),P}}return g=true,{valid:true,entriesVerified:p.length,verifiedAt:Date.now()}},async export(d){let f=[...p];return d!==void 0&&(f=f.filter(b=>b.timestamp>=d)),s&&f.length>0&&(await s(f),l+=f.length),f},prune(){let d=Date.now()-t,f=p.length;for(;p.length>0&&p[0].timestamp<d;)p.shift(),h>0&&h--;let b=f-p.length;return m+=b,b},getStats(){let d={};for(let f of p)d[f.eventType]=(d[f.eventType]??0)+1;return {totalEntries:p.length,byEventType:d,oldestEntry:p[0]?.timestamp,newestEntry:p[p.length-1]?.timestamp,entriesPruned:m,entriesExported:l,chainIntegrity:g}},async destroy(){if(C&&(clearInterval(C),C=void 0),s)try{let d=p.slice(h);d.length>0&&(await s(d),l+=d.length);}catch(d){y.onExportError?.(d instanceof Error?d:new Error(String(d)),p.slice(h));}},addEntry(d,f){return S(d,f)},createPlugin(){return {name:"audit-trail",onFactSet:(d,f,b)=>{S("fact.set",{key:d,value:f,prev:b}).catch(console.error);},onFactsBatch:d=>{S("fact.batch",{changes:d.map(f=>({key:f.key,value:f.value,prev:f.prev}))}).catch(console.error);},onRequirementCreated:d=>{S("requirement.created",{id:d.id,type:d.requirement.type,payload:d.requirement}).catch(console.error);},onRequirementMet:(d,f)=>{S("requirement.met",{id:d.id,type:d.requirement.type,byResolver:f}).catch(console.error);},onResolverStart:(d,f)=>{S("resolver.start",{resolver:d,requirementId:f.id,requirementType:f.requirement.type}).catch(console.error);},onResolverComplete:(d,f,b)=>{S("resolver.complete",{resolver:d,requirementId:f.id,requirementType:f.requirement.type,duration:b}).catch(console.error);},onResolverError:(d,f,b)=>{S("resolver.error",{resolver:d,requirementId:f.id,requirementType:f.requirement.type,error:b instanceof Error?b.message:String(b)}).catch(console.error);},onError:d=>{S("error.occurred",{source:d.source,sourceId:d.sourceId,message:d.message,context:d.context}).catch(console.error);},onErrorRecovery:(d,f)=>{S("error.recovery",{source:d.source,message:d.message,strategy:f}).catch(console.error);}}}}}function an(r){return {onAgentStart:(e,t)=>{r.addEntry("agent.run.start",{agentName:e,input:t});},onAgentComplete:(e,t,n,s)=>{r.addEntry("agent.run.complete",{agentName:e,output:t,tokens:n,cost:s});},onAgentError:(e,t)=>{r.addEntry("agent.run.error",{agentName:e,error:t.message,stack:t.stack});},onToolStart:(e,t,n)=>{r.addEntry("tool.call.start",{toolName:e,toolCallId:t,args:n});},onToolComplete:(e,t,n)=>{r.addEntry("tool.call.complete",{toolName:e,toolCallId:t,result:n});},onToolError:(e,t,n)=>{r.addEntry("tool.call.error",{toolName:e,toolCallId:t,error:n.message});},onApprovalRequested:(e,t,n)=>{r.addEntry("approval.requested",{toolName:e,toolCallId:t,args:n});},onApprovalGranted:(e,t)=>{r.addEntry("approval.granted",{toolName:e,toolCallId:t});},onApprovalDenied:(e,t,n)=>{r.addEntry("approval.denied",{toolName:e,toolCallId:t,reason:n});}}}function sn(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function cn(r){return new TextEncoder().encode(r)}function un(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}async function re(r){let e=cn(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return un(new Uint8Array(t))}function ln(r){if(r.length===0)return "";let e=new Set;for(let s of r)for(let c of Object.keys(s))e.add(c);let t=Array.from(e),n=[t.join(",")];for(let s of r){let c=t.map(o=>{let u=s[o];if(u==null)return "";if(typeof u=="object")return JSON.stringify(u).replace(/"/g,'""');let a=String(u);return a.includes(",")||a.includes(`
20
+ SUMMARY:`;return r(o)}}var Qr=1e4,Xr=10080*60*1e3,Yr=6e4,Z="0".repeat(64);function Zr(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function en(r){return new TextEncoder().encode(r)}function tn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}async function ee(r){let e=en(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return tn(new Uint8Array(t))}function te(r){let{id:e,timestamp:t,eventType:n,previousHash:s,payload:c,actorId:o,sessionId:u}=r;return JSON.stringify({id:e,timestamp:t,eventType:n,previousHash:s,payload:c,actorId:o,sessionId:u})}function rn(r){return JSON.parse(JSON.stringify(r))}async function nn(r,e){let t=rn(r);async function n(s){if(typeof s=="string"){let c=await chunkMPMBFW2P_cjs.m(s,{types:e.types,minConfidence:e.minConfidence??.7});if(c.detected){let o=e.allowlist?c.items.filter(u=>!e.allowlist.includes(u.value.toLowerCase())):c.items;if(o.length>0)return chunkMPMBFW2P_cjs.j(s,o,e.redactionStyle)}return s}if(Array.isArray(s))return Promise.all(s.map(n));if(s&&typeof s=="object"){let c={};for(let[o,u]of Object.entries(s))c[o]=await n(u);return c}return s}for(let[s,c]of Object.entries(t))t[s]=await n(c);return t}function on(r={}){let{maxEntries:e=Qr,retentionMs:t=Xr,exportInterval:n=Yr,exporter:s,piiMasking:c,signing:o,sessionId:u,actorId:a,events:y={}}=r,p=[],h=0,m=0,l=0,g=true,C;function E(){return p.length===0?Z:p[p.length-1].hash}async function S(d,f,b){let A={id:Zr(),timestamp:Date.now(),eventType:d,previousHash:E(),payload:f,actorId:a,sessionId:u};c?.enabled&&(A.maskedPayload=await nn(f,c));let x=te(A),w=await ee(x),P={...A,hash:w};for(o&&(P.signature=await o.signFn(w)),p.push(P);p.length>e;)p.shift(),m++,h>0&&h--;return y.onEntryAdded?.(P),P}return s&&n>0&&(C=setInterval(async()=>{try{let d=p.slice(h);d.length>0&&(await s(d),l+=d.length,h=p.length);}catch(d){y.onExportError?.(d instanceof Error?d:new Error(String(d)),p.slice(h));}},n)),{getEntries(d){let f=[...p];if(d){if(d.eventTypes?.length){let b=new Set(d.eventTypes);f=f.filter(A=>b.has(A.eventType));}d.actorId&&(f=f.filter(b=>b.actorId===d.actorId)),d.sessionId&&(f=f.filter(b=>b.sessionId===d.sessionId)),d.since!==void 0&&(f=f.filter(b=>b.timestamp>=d.since)),d.until!==void 0&&(f=f.filter(b=>b.timestamp<=d.until)),d.offset!==void 0&&(f=f.slice(d.offset)),d.limit!==void 0&&(f=f.slice(0,d.limit));}return f},async verifyChain(){if(p.length===0)return {valid:true,entriesVerified:0,verifiedAt:Date.now()};p[0].previousHash;for(let f=0;f<p.length;f++){let b=p[f],A=te({id:b.id,timestamp:b.timestamp,eventType:b.eventType,previousHash:b.previousHash,payload:b.payload,actorId:b.actorId,sessionId:b.sessionId}),x=await ee(A);if(b.hash!==x){g=false;let w={valid:false,entriesVerified:f,brokenAt:{index:f,entryId:b.id,expectedHash:x,actualHash:b.hash},verifiedAt:Date.now()};return y.onChainBroken?.(w),w}if(f>0){let w=p[f-1];if(b.previousHash!==w.hash){g=false;let P={valid:false,entriesVerified:f,brokenAt:{index:f,entryId:b.id,expectedHash:w.hash,actualHash:b.previousHash},verifiedAt:Date.now()};return y.onChainBroken?.(P),P}}if(o?.verifyFn&&b.signature&&!await o.verifyFn(b.hash,b.signature)){g=false;let P={valid:false,entriesVerified:f,brokenAt:{index:f,entryId:b.id,expectedHash:"signature-invalid",actualHash:b.signature},verifiedAt:Date.now()};return y.onChainBroken?.(P),P}}return g=true,{valid:true,entriesVerified:p.length,verifiedAt:Date.now()}},async export(d){let f=[...p];return d!==void 0&&(f=f.filter(b=>b.timestamp>=d)),s&&f.length>0&&(await s(f),l+=f.length),f},prune(){let d=Date.now()-t,f=p.length;for(;p.length>0&&p[0].timestamp<d;)p.shift(),h>0&&h--;let b=f-p.length;return m+=b,b},getStats(){let d={};for(let f of p)d[f.eventType]=(d[f.eventType]??0)+1;return {totalEntries:p.length,byEventType:d,oldestEntry:p[0]?.timestamp,newestEntry:p[p.length-1]?.timestamp,entriesPruned:m,entriesExported:l,chainIntegrity:g}},async destroy(){if(C&&(clearInterval(C),C=void 0),s)try{let d=p.slice(h);d.length>0&&(await s(d),l+=d.length);}catch(d){y.onExportError?.(d instanceof Error?d:new Error(String(d)),p.slice(h));}},addEntry(d,f){return S(d,f)},createPlugin(){return {name:"audit-trail",onFactSet:(d,f,b)=>{S("fact.set",{key:d,value:f,prev:b}).catch(console.error);},onFactsBatch:d=>{S("fact.batch",{changes:d.map(f=>({key:f.key,value:f.value,prev:f.prev}))}).catch(console.error);},onRequirementCreated:d=>{S("requirement.created",{id:d.id,type:d.requirement.type,payload:d.requirement}).catch(console.error);},onRequirementMet:(d,f)=>{S("requirement.met",{id:d.id,type:d.requirement.type,byResolver:f}).catch(console.error);},onResolverStart:(d,f)=>{S("resolver.start",{resolver:d,requirementId:f.id,requirementType:f.requirement.type}).catch(console.error);},onResolverComplete:(d,f,b)=>{S("resolver.complete",{resolver:d,requirementId:f.id,requirementType:f.requirement.type,duration:b}).catch(console.error);},onResolverError:(d,f,b)=>{S("resolver.error",{resolver:d,requirementId:f.id,requirementType:f.requirement.type,error:b instanceof Error?b.message:String(b)}).catch(console.error);},onError:d=>{S("error.occurred",{source:d.source,sourceId:d.sourceId,message:d.message,context:d.context}).catch(console.error);},onErrorRecovery:(d,f)=>{S("error.recovery",{source:d.source,message:d.message,strategy:f}).catch(console.error);}}}}}function an(r){return {onAgentStart:(e,t)=>{r.addEntry("agent.run.start",{agentName:e,input:t});},onAgentComplete:(e,t,n,s)=>{r.addEntry("agent.run.complete",{agentName:e,output:t,tokens:n,cost:s});},onAgentError:(e,t)=>{r.addEntry("agent.run.error",{agentName:e,error:t.message,stack:t.stack});},onToolStart:(e,t,n)=>{r.addEntry("tool.call.start",{toolName:e,toolCallId:t,args:n});},onToolComplete:(e,t,n)=>{r.addEntry("tool.call.complete",{toolName:e,toolCallId:t,result:n});},onToolError:(e,t,n)=>{r.addEntry("tool.call.error",{toolName:e,toolCallId:t,error:n.message});},onApprovalRequested:(e,t,n)=>{r.addEntry("approval.requested",{toolName:e,toolCallId:t,args:n});},onApprovalGranted:(e,t)=>{r.addEntry("approval.granted",{toolName:e,toolCallId:t});},onApprovalDenied:(e,t,n)=>{r.addEntry("approval.denied",{toolName:e,toolCallId:t,reason:n});}}}function sn(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function cn(r){return new TextEncoder().encode(r)}function un(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}async function re(r){let e=cn(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return un(new Uint8Array(t))}function ln(r){if(r.length===0)return "";let e=new Set;for(let s of r)for(let c of Object.keys(s))e.add(c);let t=Array.from(e),n=[t.join(",")];for(let s of r){let c=t.map(o=>{let u=s[o];if(u==null)return "";if(typeof u=="object")return JSON.stringify(u).replace(/"/g,'""');let a=String(u);return a.includes(",")||a.includes(`
21
21
  `)||a.includes('"')?`"${a.replace(/"/g,'""')}"`:a});n.push(c.join(","));}return n.join(`
22
22
  `)}function dn(){let r=new Map,e=new Map,t=new Map;return {async getSubjectData(n,s){let c=[];for(let[o,u]of r){if(s&&!s.includes(o))continue;let a=u.get(n);a&&a.length>0&&c.push({category:o,records:[...a]});}return c},async deleteSubjectData(n,s){let c=0;for(let[o,u]of r){if(s&&!s.includes(o))continue;let a=u.get(n);a&&(c+=a.length,u.delete(n));}return c},async anonymizeSubjectData(n,s){let c=0;for(let[o,u]of r){if(s&&!s.includes(o))continue;let a=u.get(n);if(a)for(let y of a)y.data={...y.data,_anonymized:true,_anonymizedAt:Date.now()},c++;}return c},async getExpiredData(n,s){let c=[],o=r.get(n);if(o)for(let u of o.values())for(let a of u)a.createdAt<s&&c.push({id:a.id,createdAt:a.createdAt});return c},async deleteByIds(n){let s=new Set(n),c=0;for(let o of r.values())for(let[u,a]of o){let y=a.filter(p=>!s.has(p.id));y.length!==a.length&&(c+=a.length-y.length,y.length===0?o.delete(u):o.set(u,y));}return c},async storeConsent(n){e.set(`${n.subjectId}:${n.purpose}`,n);},async getConsent(n,s){return e.get(`${n}:${s}`)??null},async getConsentsBySubject(n){let s=[];for(let[c,o]of e)c.startsWith(`${n}:`)&&s.push(o);return s},async getConsentsByPurpose(n){let s=[];for(let[c,o]of e)c.endsWith(`:${n}`)&&s.push(o);return s},async storeDeletionCertificate(n){t.set(n.subjectId,n);}}}function pn(r){let{storage:e,retention:t,exportExpirationMs:n=864e5,events:s={}}=r,c={async grant(o,u,a={}){let y={subjectId:o,purpose:u,granted:true,grantedAt:Date.now(),expiresAt:a.expiresAt,source:a.source,version:a.version};return await e.storeConsent(y),s.onConsentChange?.(y),y},async revoke(o,u){let a=await e.getConsent(o,u);if(!a)return null;let y={...a,granted:false,revokedAt:Date.now()};return await e.storeConsent(y),s.onConsentChange?.(y),y},async check(o,u){let a=await e.getConsent(o,u);return !(!a||!a.granted||a.expiresAt&&a.expiresAt<Date.now())},async getForSubject(o){return e.getConsentsBySubject(o)},async getForPurpose(o){return e.getConsentsByPurpose(o)}};return {async exportData(o){try{let u=await e.getSubjectData(o.subjectId,o.categories),a=[],y=[];for(let{category:l,records:g}of u){y.push(l);for(let C of g)a.push({category:l,...C});}if(o.includeAudit&&e.getAuditEntries){let l=await e.getAuditEntries(o.subjectId);y.push("audit");for(let g of l)a.push({category:"audit",id:g.id,data:g.payload,createdAt:g.timestamp});}let p;o.format==="csv"?p=ln(a.map(l=>({category:l.category,id:l.id,createdAt:new Date(l.createdAt).toISOString(),...l.data}))):p=JSON.stringify({subjectId:o.subjectId,exportedAt:new Date().toISOString(),recordCount:a.length,categories:y,records:a},null,2);let h=await re(p),m={success:!0,subjectId:o.subjectId,format:o.format,data:p,categories:y,recordCount:a.length,checksum:h,exportedAt:Date.now(),expiresAt:Date.now()+n};return s.onExport?.(m),m}catch(u){return {success:false,subjectId:o.subjectId,format:o.format,data:"",categories:[],recordCount:0,checksum:"",exportedAt:Date.now(),error:u instanceof Error?u.message:String(u)}}},async deleteData(o){try{let u=0,a=[];o.anonymize?u=await e.anonymizeSubjectData(o.subjectId,o.categories):u=await e.deleteSubjectData(o.subjectId,o.categories),o.categories?a.push(...o.categories):o.scope==="all"&&a.push("all");let y=JSON.stringify({subjectId:o.subjectId,type:o.anonymize?"anonymization":"hard",scope:o.scope,categories:a,recordCount:u,deletedAt:Date.now(),reason:o.reason}),p={id:sn(),subjectId:o.subjectId,type:o.anonymize?"anonymization":"hard",scope:o.scope,categories:a,recordCount:u,deletedAt:Date.now(),reason:o.reason,hash:await re(y)};await e.storeDeletionCertificate(p);let h={success:!0,subjectId:o.subjectId,scope:o.scope,anonymized:o.anonymize??!1,recordsAffected:u,categoriesAffected:a,certificate:p,deletedAt:Date.now()};return s.onDelete?.(h),h}catch(u){return {success:false,subjectId:o.subjectId,scope:o.scope,anonymized:o.anonymize??false,recordsAffected:0,categoriesAffected:[],certificate:{id:"error",subjectId:o.subjectId,type:"hard",scope:o.scope,categories:[],recordCount:0,deletedAt:Date.now(),hash:""},deletedAt:Date.now(),error:u instanceof Error?u.message:String(u)}}},consent:c,async enforceRetention(){if(!t)return 0;let o=0,u=Date.now(),a=new Set;if(t.categoryRetention)for(let y of Object.keys(t.categoryRetention))a.add(y);a.add("default");for(let y of a){let p=t.categoryRetention?.[y]??t.defaultRetentionMs,h=u-p,m=await e.getExpiredData(y,h);if(m.length>0){await t.onBeforeDelete?.({category:y,count:m.length});let l=await e.deleteByIds(m.map(g=>g.id));o+=l,t.onAfterDelete?.({category:y,count:l}),s.onRetentionEnforced?.(y,l);}}return o},createConsentGuardrail(o){return async u=>{let y=u.input.match(/user[_-]?id[:\s]*([a-zA-Z0-9-]+)/i)?.[1];return y?await c.check(y,o)?{passed:true}:{passed:false,reason:`No consent for '${o}' from subject ${y}`}:{passed:true}}},async getDeletionCertificate(o){return null}}}function K(r={}){let{bufferSize:e=100}=r;if(e<1||!Number.isFinite(e))throw new Error(`[Directive StreamChannel] bufferSize must be >= 1, got ${e}`);let t=[],n="open",s=null,c=null,o=null,u=false;function a(l){if(c){let g=c;c=null,g.resolve({value:l,done:false});}}function y(){if(c){let l=c;c=null,l.resolve({value:void 0,done:true});}}function p(l){if(c){let g=c;c=null,u=false,g.reject(l);}}function h(){if(o){let l=o;o=null,l();}}return {async send(l){if(n!=="open")throw new Error(`[Directive StreamChannel] Cannot send to ${n} channel${r.name?` "${r.name}"`:""}`);if(c){a(l);return}if(t.length>=e){if(await new Promise(g=>{o=g;}),n!=="open")throw new Error(`[Directive StreamChannel] Cannot send to ${n} channel${r.name?` "${r.name}"`:""}`);if(c){a(l);return}}t.push(l);},end(){n==="open"&&(n="closed",y());},error(l){n==="open"&&(n="error",s=l,p(l),h());},getState(){return n},bufferedCount(){return t.length},[Symbol.asyncIterator](){if(u)throw new Error("[Directive StreamChannel] Channel only supports a single consumer. Create a separate channel for each consumer.");return u=true,{next(){if(n==="error"&&s)return u=false,Promise.reject(s);if(t.length>0){let l=t.shift();return h(),Promise.resolve({value:l,done:false})}return n==="closed"?(u=false,Promise.resolve({value:void 0,done:true})):new Promise((l,g)=>{c={resolve:l,reject:g};})},return(){return n="closed",t.length=0,u=false,h(),Promise.resolve({value:void 0,done:true})}}}}}function gn(r){let e=K(r),t=K(r);return {sideA:{send:n=>e.send(n),receive:t,close(){e.end(),t.end();}},sideB:{send:n=>t.send(n),receive:e,close(){e.end(),t.end();}}}}async function mn(r,e,t){try{for await(let n of r){let s=await t(n);await e.send(s);}e.end();}catch(n){e.error(n instanceof Error?n:new Error(String(n)));}}function fn(...r){return {[Symbol.asyncIterator](){let t=[],n=0,s=null,c=null,o=false,u=false,a=[];function y(p){if(s){let h=s;return s=null,h(p),true}return false}for(let p of r){let h=p[Symbol.asyncIterator]();a.push(h),(async()=>{try{for(;!o;){let m=await h.next();if(m.done||o)break;y({value:m.value,done:!1})||(t.length<1e4?t.push(m.value):u||(u=!0,console.warn("[Directive mergeStreams] Buffer exceeded 10000 items. Values are being dropped. Ensure the consumer keeps up or use bounded StreamChannel sources.")));}}catch(m){o||(o=true,c=m instanceof Error?m:new Error(String(m)),y({value:void 0,done:true}));}n++,n>=r.length&&!o&&y({value:void 0,done:true});})();}return {next(){return c?Promise.reject(c):t.length>0?Promise.resolve({value:t.shift(),done:false}):n>=r.length?Promise.resolve({value:void 0,done:true}):new Promise(p=>{s=p;})},return(){o=true,t.length=0;for(let p of a)p.return?.({value:void 0,done:true});if(s){let p=s;s=null,p({value:void 0,done:true});}return Promise.resolve({value:void 0,done:true})}}}}}function yn(r,e){let t=r.metadata.title??"",n=r.metadata.section??"",s=r.metadata.url??"";return `${t&&n&&s?`[${t} \u2014 ${n}](${s})`:t||r.id}
23
23
  ${r.content}`}function hn(r,e){return r.length===0?"":`Relevant documentation context:
24
24
 
25
25
  ${r.join(`
26
26
 
27
- `)}`}function vn(r,e,t){return Math.max(e,Math.min(t,r))}function Sn(r){let{embedder:e,storage:t,topK:n=5,minSimilarity:s=.3,formatChunk:c=yn,formatContext:o=hn,onError:u}=r,a=vn(s,0,1);typeof process<"u"&&process.env?.NODE_ENV==="development"&&s!==a&&console.warn(`[Directive] RAG: minSimilarity ${s} clamped to ${a} (valid range: 0-1)`);async function y(h,m){let l=Math.max(1,Math.floor(m??n));if(t.search)return t.search(await e(h),l,a);let g=await e(h),E=(await t.getChunks()).map(S=>({...S,similarity:chunkZGJ2XHGI_cjs.v(g,S.embedding)}));return E.sort((S,d)=>d.similarity-S.similarity),E.filter(S=>S.similarity>=a).slice(0,l)}async function p(h,m={}){let{prefix:l,history:g,topK:C,filter:E}=m,S=[];try{S=await y(h,C);}catch(A){u?.(A instanceof Error?A:new Error(String(A)));}E&&(S=S.filter(A=>E(A)));let d=S.map(A=>c(A,A.similarity)),f=o(d,h),b=[];if(l&&b.push(l),f&&b.push(f),g&&g.length>0){let A=g.map(x=>`${x.role.charAt(0).toUpperCase()+x.role.slice(1)}: ${x.content}`).join(`
27
+ `)}`}function vn(r,e,t){return Math.max(e,Math.min(t,r))}function Sn(r){let{embedder:e,storage:t,topK:n=5,minSimilarity:s=.3,formatChunk:c=yn,formatContext:o=hn,onError:u}=r,a=vn(s,0,1);typeof process<"u"&&process.env?.NODE_ENV==="development"&&s!==a&&console.warn(`[Directive] RAG: minSimilarity ${s} clamped to ${a} (valid range: 0-1)`);async function y(h,m){let l=Math.max(1,Math.floor(m??n));if(t.search)return t.search(await e(h),l,a);let g=await e(h),E=(await t.getChunks()).map(S=>({...S,similarity:chunkMPMBFW2P_cjs.v(g,S.embedding)}));return E.sort((S,d)=>d.similarity-S.similarity),E.filter(S=>S.similarity>=a).slice(0,l)}async function p(h,m={}){let{prefix:l,history:g,topK:C,filter:E}=m,S=[];try{S=await y(h,C);}catch(A){u?.(A instanceof Error?A:new Error(String(A)));}E&&(S=S.filter(A=>E(A)));let d=S.map(A=>c(A,A.similarity)),f=o(d,h),b=[];if(l&&b.push(l),f&&b.push(f),g&&g.length>0){let A=g.map(x=>`${x.role.charAt(0).toUpperCase()+x.role.slice(1)}: ${x.content}`).join(`
28
28
 
29
29
  `);b.push(`Previous conversation:
30
30
  ${A}`);}return b.push(h),b.join(`
@@ -37,5 +37,5 @@ ${A}`);}return b.push(h),b.join(`
37
37
 
38
38
  `)}return new ReadableStream({async start(C){let E=null,S=null;try{n>0&&(E=setInterval(()=>{try{C.enqueue(g({type:"heartbeat",timestamp:Date.now()}));}catch{}},n)),S=y.stream(p,h,{signal:m?.signal});let d=0,f=!1;for await(let b of S){if(d+=b.length,d>e){C.enqueue(g({type:"truncated",text:t})),C.enqueue(g({type:"done"})),f=!0,S.abort();break}C.enqueue(g({type:"text",text:b}));}try{await S.result;}catch{}f||C.enqueue(g({type:"done"}));}catch(d){let f=o(d);C.enqueue(g({type:"error",message:f}));}finally{E&&clearInterval(E),C.close();}}})}let a={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...c};return {toResponse(y,p,h,m){let l=u(y,p,h,m);return new Response(l,{headers:a})},toStream(y,p,h,m){return u(y,p,h,m)}}}var F=class extends Error{retryCount;lastError;constructor(e,t){super(`[Directive] All ${e} retries exhausted: ${t.message}`),this.name="RetryExhaustedError",this.retryCount=e,this.lastError=t,this.cause=t;}},En=new Set([400,401,403,404,422]);function W(r){let e=r;if(typeof e.status=="number"&&e.status>=100&&e.status<=599)return e.status;if(typeof e.statusCode=="number"&&e.statusCode>=100&&e.statusCode<=599)return e.statusCode;let n=(r.message.length>1e3?r.message.slice(0,1e3):r.message).match(/(?:failed|error|status|http)[:\s]+(\d{3})\b/i);if(!n)return null;let s=Number(n[1]);return s>=100&&s<=599?s:null}function oe(r){let e=r;if(typeof e.retryAfter=="number"&&e.retryAfter>0)return e.retryAfter*1e3;let n=(r.message.length>1e3?r.message.slice(0,1e3):r.message).match(/retry[- ]?after[:\s]+(\d+)/i);if(!n)return null;let s=Number(n[1]);return s>0?s*1e3:null}function An(r,e,t){let n=e*2**(r-1),s=Math.random()*e*.5,c=n+s;return Math.min(c,t)}function Tn(r,e,t,n){if(W(r)===429){let c=oe(r);if(c!==null)return Math.min(c,n)}return An(e,t,n)}function wn(r){let e=W(r);return e===null?true:!En.has(e)}function kn(r,e={}){let{maxRetries:t=3,baseDelayMs:n=1e3,maxDelayMs:s=3e4,isRetryable:c,onRetry:o}=e;if(!Number.isFinite(t)||t<0)throw new Error("[Directive] withRetry: maxRetries must be a non-negative finite number.");if(!Number.isFinite(n)||n<0)throw new Error("[Directive] withRetry: baseDelayMs must be a non-negative finite number.");if(!Number.isFinite(s)||s<0)throw new Error("[Directive] withRetry: maxDelayMs must be a non-negative finite number.");return async(u,a,y)=>{let p;for(let h=0;h<=t;h++)try{return await r(u,a,y)}catch(m){if(p=m instanceof Error?m:new Error(String(m)),h>=t)break;if(c)try{if(!c(p))break}catch{break}if(!wn(p))break;let l=Tn(p,h+1,n,s);try{o?.(h+1,p,l);}catch{}let g=y?.signal;if(g?.aborted)break;await new Promise((C,E)=>{let S=setTimeout(()=>{g?.removeEventListener("abort",d),C();},l);function d(){clearTimeout(S),E(g.reason??new Error("Aborted"));}g&&g.addEventListener("abort",d,{once:true});});}throw new F(t,p)}}var _=class extends Error{errors;constructor(e){let t=e.map((n,s)=>` [${s}] ${n.message}`).join(`
39
39
  `);super(`[Directive] All ${e.length} providers failed:
40
- ${t}`),this.name="AllProvidersFailedError",this.errors=Object.freeze([...e]),e.length>0&&(this.cause=e[e.length-1]);}};function xn(r,e={}){if(r.length===0)throw new Error("[Directive] withFallback requires at least one runner.");let{shouldFallback:t,onFallback:n}=e;return async(s,c,o)=>{let u=[];for(let a=0;a<r.length;a++)try{return await r[a](s,c,o)}catch(y){let p=y instanceof Error?y:new Error(String(y));if(u.push(p),a<r.length-1){if(t)try{if(!t(p))break}catch{break}try{n?.(a,a+1,p);}catch{}}}throw new _(u)}}var N=class extends Error{estimated;remaining;window;constructor(e){super(`[Directive] Budget exceeded (${e.window}): estimated $${e.estimated.toFixed(4)}, remaining $${e.remaining.toFixed(4)}`),this.name="BudgetExceededError",this.estimated=e.estimated,this.remaining=e.remaining,this.window=e.window;}},$=class{entries=[];record(e){this.entries.push({timestamp:Date.now(),cost:e});}getCostInWindow(e){let t=Date.now()-e;this.prune(t);let n=0;for(let s of this.entries)s.timestamp>=t&&(n+=s.cost);return n}prune(e){let t=0;for(;t<this.entries.length&&this.entries[t].timestamp<e;)t++;t>0&&this.entries.splice(0,t);}clear(){this.entries=[];}},ae={hour:3600*1e3,day:1440*60*1e3};function In(r,e){return Math.ceil(r.length/e)}function se(r,e){return r.inputTokens/1e6*e.inputPerMillion+r.outputTokens/1e6*e.outputPerMillion}function ie(r,e,t=1){let n=Math.ceil(r*t);return r/1e6*e.inputPerMillion+n/1e6*e.outputPerMillion}function Mn(r,e){let{maxCostPerCall:t,budgets:n=[],pricing:s,charsPerToken:c=4,estimatedOutputMultiplier:o=1,onBudgetExceeded:u}=e;if(!Number.isFinite(c)||c<=0)throw new Error("[Directive] withBudget: charsPerToken must be a positive finite number.");if(t!=null&&(!Number.isFinite(t)||t<0))throw new Error("[Directive] withBudget: maxCostPerCall must be a non-negative finite number.");if(!Number.isFinite(o)||o<0)throw new Error("[Directive] withBudget: estimatedOutputMultiplier must be a non-negative finite number.");t!=null&&!s&&console.warn("[Directive] withBudget: maxCostPerCall has no effect without pricing. Provide a pricing config to enable per-call cost estimation.");for(let m of n)if(!Number.isFinite(m.maxCost)||m.maxCost<0)throw new Error(`[Directive] withBudget: budgets[${m.window}].maxCost must be a non-negative finite number.`);let a=new Map;for(let m of n)a.set(m.window,new $);let y=new $,p=async(m,l,g)=>{let C=In(l,c);if(t!=null&&s){let S=ie(C,s,o);if(S>t){let d={estimated:S,remaining:t,window:"per-call"};try{u?.(d);}catch{}throw new N(d)}}for(let S of n){let d=ae[S.window],b=a.get(S.window).getCostInWindow(d),A=S.maxCost-b,x=ie(C,S.pricing,o);if(x>A){let w={estimated:x,remaining:Math.max(0,A),window:S.window};try{u?.(w);}catch{}throw new N(w)}}let E=await r(m,l,g);if(E.tokenUsage){for(let S of n){let d=a.get(S.window),f=se(E.tokenUsage,S.pricing);d.record(f);}if(s&&n.length===0){let S=se(E.tokenUsage,s);y.record(S);}}return E};function h(m){let l=a.get(m);if(!l)return 0;let g=ae[m];return l.getCostInWindow(g)}return p.getSpent=h,p}function Pn(r,e){return {match:(t,n)=>n.length<=r,model:e}}function Dn(r,e){return {match:t=>t.name===r,model:e}}function On(r,e){return {match:(t,n)=>(r.lastIndex=0,r.test(n)),model:e}}function Bn(r,e){let t=Array.isArray(e)?{rules:e}:e,{rules:n,onModelSelected:s}=t;return async(c,o,u)=>{let a=c.model;for(let p of n)try{if(p.match(c,o)){a=p.model;break}}catch{}try{s?.(c.model,a);}catch{}let y=a!==c.model?{...c,model:a}:c;return r(y,o,u)}}function jn(r,e={}){let{maxBatchSize:t=20,maxWaitMs:n=5e3,concurrency:s=5}=e;if(!Number.isFinite(t)||t<1)throw new Error("[Directive] createBatchQueue: maxBatchSize must be a positive finite number (>= 1).");if(!Number.isFinite(n)||n<0)throw new Error("[Directive] createBatchQueue: maxWaitMs must be a non-negative finite number.");if(!Number.isFinite(s)||s<1)throw new Error("[Directive] createBatchQueue: concurrency must be a positive finite number (>= 1).");let c=[],o=null,u=false,a=null;function y(){o===null&&(o=setTimeout(()=>{o=null,m().catch(()=>{});},n));}function p(){o!==null&&(clearTimeout(o),o=null);}async function h(l){let g=0;async function C(){for(;g<l.length;){let S=g++,d=l[S];try{let f=await r(d.agent,d.input,d.options);d.resolve(f);}catch(f){d.reject(f instanceof Error?f:new Error(String(f)));}}}let E=Array.from({length:Math.min(s,l.length)},()=>C());await Promise.all(E);}async function m(){if(a&&await a,c.length===0)return;p();let l=c.splice(0);a=h(l).finally(()=>{a=null,c.length>0&&y();}),await a;}return {submit(l,g,C){return u?Promise.reject(new Error("[Directive] BatchQueue has been destroyed.")):new Promise((E,S)=>{c.push({agent:l,input:g,options:C,resolve:E,reject:S}),c.length>=t?(p(),m().catch(()=>{})):y();})},async flush(){await m();},get pending(){return c.length},async destroy(){u||(u=true,p(),c.length>0&&await m());}}}function ce(){return {callCount:0,errorCount:0,totalCost:0,avgLatencyMs:0,lastErrorAt:null}}function Nn(r,e){return !r||!e?0:r.inputTokens/1e6*e.inputPerMillion+r.outputTokens/1e6*e.outputPerMillion}function Gn(r){let{providers:e,defaultProvider:t,constraints:n=[],onProviderSelected:s,errorCooldownMs:c=3e4,preferCheapest:o=false}=r;if(!Number.isFinite(c)||c<0)throw new Error("[Directive] createConstraintRouter: errorCooldownMs must be a non-negative finite number.");let u=new Map;for(let g of e)u.set(g.name,g);if(!u.has(t))throw new Error(`[Directive] Default provider "${t}" not found in providers list.`);let a={totalCost:0,callCount:0,errorCount:0,lastProvider:null,avgLatencyMs:0,providers:Object.create(null)};for(let g of e)a.providers[g.name]=ce();let y=0,p=[...n].sort((g,C)=>(C.priority??0)-(g.priority??0));function h(){let g=Date.now();for(let E of p)try{if(E.when(a)){let S=u.get(E.provider);if(S)return {provider:S,reason:"constraint"}}}catch{}let C=e.filter(E=>{let S=a.providers[E.name];return S?!(S.lastErrorAt&&g-S.lastErrorAt<c):true});if(o&&C.length>0){let E=[...C].sort((S,d)=>{let f=S.pricing?S.pricing.inputPerMillion+S.pricing.outputPerMillion:Number.POSITIVE_INFINITY,b=d.pricing?d.pricing.inputPerMillion+d.pricing.outputPerMillion:Number.POSITIVE_INFINITY;return f!==b?f-b:S.name===t?-1:d.name===t?1:0});if(E[0]!==u.get(t))return {provider:E[0],reason:"cheapest"}}return C.length>0&&!C.some(E=>E.name===t)?{provider:C[0],reason:"default"}:{provider:u.get(t),reason:"default"}}function m(g,C,E,S,d){let f=a.providers[g]??ce();if(f.callCount++,a.callCount++,d)f.errorCount++,a.errorCount++,f.lastErrorAt=Date.now();else {let A=Nn(E,S);f.totalCost+=A,a.totalCost+=A;}y+=C,a.avgLatencyMs=y/a.callCount;let b=f.callCount>0?(f.avgLatencyMs*(f.callCount-1)+C)/f.callCount:C;f.avgLatencyMs=b,a.providers[g]=f,a.lastProvider=g;}let l=async(g,C,E)=>{let{provider:S,reason:d}=h();try{s?.(S.name,d);}catch{}let f=Date.now();try{let b=await S.runner(g,C,E),A=Date.now()-f;return m(S.name,A,b.tokenUsage,S.pricing),b}catch(b){let A=Date.now()-f,x=b instanceof Error?b:new Error(String(b));throw m(S.name,A,void 0,S.pricing,x),x}};return Object.defineProperty(l,"facts",{get:()=>{let g=Object.create(null);for(let C of Object.keys(a.providers))g[C]={...a.providers[C]};return {...a,providers:g}},enumerable:true}),l}var I={UNSET:0,OK:1,ERROR:2},L=class{constructor(e,t,n,s,c,o){this.name=e;this.spanId=t;this.traceId=n;this.parentSpanId=s;this.onEnd=o;if(this.startTime=Date.now(),c)for(let[u,a]of Object.entries(c))this.attributes[u]=a;}attributes=Object.create(null);spanEvents=[];status={code:I.UNSET};startTime;endTime=0;setAttribute(e,t){this.attributes[e]=t;}addEvent(e,t){this.spanEvents.push({name:e,attributes:t,timestamp:Date.now()});}setStatus(e){this.status=e;}end(){this.endTime=Date.now(),this.onEnd?.(this);}toSpanData(){return {name:this.name,traceId:this.traceId,spanId:this.spanId,parentSpanId:this.parentSpanId,attributes:{...this.attributes},events:[...this.spanEvents],status:{...this.status},startTime:this.startTime,endTime:this.endTime,durationMs:this.endTime-this.startTime}}},J=class{spans=[];startSpan(e,t){let n=t?.spanId??`fallback-${crypto.randomUUID()}`,s=t?.traceId??`fallback-${crypto.randomUUID()}`,c=t?.parentSpanId;return new L(e,n,s,c,t?.attributes,o=>{this.spans.push(o.toSpanData());})}clear(){this.spans.length=0;}};function Fn(r){let e=r.spanPrefix??"directive.ai",t=r.instrumentEvents,n=r.spanTtlMs??3e5,s=!r.tracer,c=s?new J:null,o=r.tracer??c,u=0;function a(){return `${Date.now().toString(36)}-${(u++).toString(36)}`}function y(){return `${Date.now().toString(36)}-${crypto.randomUUID().slice(0,8)}`}let p=new Map,h=0,m=new Map,l=[],g=null,C=false;function E(i){return t?t.has(i):true}function S(i,v){return `${i}:${v}:${h++}`}function d(i,v){let R=`${i}:${v}`,T=m.get(R);if(T){for(let k=T.length-1;k>=0;k--){let O=p.get(T[k]);if(O)return {key:T[k],entry:O}}m.delete(R);}return null}function f(i,v,R,T){let k=`${i}:${v}`;T.indexKey=k,p.set(R,T);let O=m.get(k);O?O.push(R):m.set(k,[R]);}function b(i){let v=p.get(i);p.delete(i);let R=v?.indexKey;if(R){let T=m.get(R);if(T){let k=T.indexOf(i);k!==-1&&T.splice(k,1),T.length===0&&m.delete(R);}}}function A(){let i=Date.now();if(p.size<1e4){for(let[R,T]of p)i-T.startTime>n&&(M(T,"directive.stale",true),D(T,{code:I.ERROR,message:"Span TTL exceeded \u2014 cleaned up"}),w(T),b(R),true);return void 0}for(let[v,R]of p)i-R.startTime>n&&(M(R,"directive.stale",true),D(R,{code:I.ERROR,message:"Span TTL exceeded \u2014 cleaned up"}),w(R),b(v));}function x(i,v,R){let T=a(),k=R?.traceId??y(),O=R?.spanId,B;s?B=o.startSpan(i,{attributes:v,spanId:T,traceId:k,parentSpanId:O}):B=o.startSpan(i,{attributes:v});let z={span:B,spanId:T,traceId:k,startTime:Date.now()};return s||(z.shadow={span:B,name:i,spanId:T,traceId:k,parentSpanId:O,attributes:{...v},events:[],status:{code:I.UNSET},startTime:z.startTime}),{span:B,entry:z}}function w(i){i.span.end(),r.onSpanEnd&&r.onSpanEnd(P(i));}function P(i){if(i.span instanceof L)return i.span.toSpanData();if(i.shadow){let R=Date.now();return {name:i.shadow.name,traceId:i.shadow.traceId,spanId:i.shadow.spanId,parentSpanId:i.shadow.parentSpanId,attributes:{...i.shadow.attributes},events:[...i.shadow.events],status:{...i.shadow.status},startTime:i.shadow.startTime,endTime:R,durationMs:R-i.shadow.startTime}}let v=Date.now();return {name:"unknown",traceId:i.traceId,spanId:i.spanId,attributes:{},events:[],status:{code:I.UNSET},startTime:i.startTime,endTime:v,durationMs:v-i.startTime}}function M(i,v,R){i.span.setAttribute(v,R),i.shadow&&(i.shadow.attributes[v]=R);}function q(i,v,R){i.span.addEvent(v,R),i.shadow&&i.shadow.events.push({name:v,attributes:R,timestamp:Date.now()});}function D(i,v){i.span.setStatus(v),i.shadow&&(i.shadow.status={...v});}function ue(i){if(E(i.type))switch(A(),i.type){case "agent_start":le(i);break;case "agent_complete":de(i);break;case "agent_error":pe(i);break;case "guardrail_check":ge(i);break;case "constraint_evaluate":me(i);break;case "resolver_start":fe(i);break;case "resolver_complete":ye(i);break;case "resolver_error":he(i);break;case "pattern_start":ve(i);break;case "pattern_complete":Se(i);break;default:if(i.agentId){let v=d("agent",i.agentId);v&&q(v.entry,i.type,{"event.id":i.id,"event.timestamp":i.timestamp});}}}function le(i){let v=l.length>0?l[l.length-1]:null,{entry:R}=x(`${e}.agent.run`,{"directive.service":r.serviceName,"directive.agent.name":i.agentId,"directive.agent.input_length":i.inputLength,"gen_ai.operation.name":"agent.run","gen_ai.agent.name":i.agentId},v),T=S("agent",i.agentId);f("agent",i.agentId,T,R);}function de(i){let v=d("agent",i.agentId);v&&(M(v.entry,"directive.agent.output_length",i.outputLength),M(v.entry,"directive.agent.total_tokens",i.totalTokens),M(v.entry,"directive.agent.duration_ms",i.durationMs),M(v.entry,"gen_ai.usage.total_tokens",i.totalTokens),D(v.entry,{code:I.OK}),w(v.entry),b(v.key));}function pe(i){let v=d("agent",i.agentId);v&&(M(v.entry,"directive.agent.duration_ms",i.durationMs),M(v.entry,"directive.agent.error",i.errorMessage),M(v.entry,"gen_ai.error.message",i.errorMessage),D(v.entry,{code:I.ERROR,message:i.errorMessage}),w(v.entry),b(v.key));}function ge(i){let v=i.agentId?d("agent",i.agentId)?.entry??null:null,{entry:R}=x(`${e}.guardrail.check`,{"directive.service":r.serviceName,"directive.guardrail.name":i.guardrailName,"directive.guardrail.type":i.guardrailType,"directive.guardrail.passed":i.passed,"directive.guardrail.duration_ms":i.durationMs,"gen_ai.guardrail.name":i.guardrailName,"gen_ai.guardrail.type":i.guardrailType,"gen_ai.guardrail.passed":i.passed},v);i.reason&&M(R,"directive.guardrail.reason",i.reason),D(R,{code:i.passed?I.OK:I.ERROR,message:i.passed?void 0:i.reason}),w(R);}function me(i){if(i.agentId){let R=d("agent",i.agentId);if(R){q(R.entry,"constraint_evaluate",{"directive.constraint.id":i.constraintId,"directive.constraint.fired":i.fired});return}}let{entry:v}=x(`${e}.constraint.evaluate`,{"directive.service":r.serviceName,"directive.constraint.id":i.constraintId,"directive.constraint.fired":i.fired},null);D(v,{code:I.OK}),w(v);}function fe(i){let R=(i.agentId?d("agent",i.agentId)?.entry??null:null)??(l.length>0?l[l.length-1]:null),{entry:T}=x(`${e}.resolver.execute`,{"directive.service":r.serviceName,"directive.resolver.id":i.resolverId,"directive.resolver.requirement_type":i.requirementType},R),k=S("resolver",i.resolverId);f("resolver",i.resolverId,k,T);}function ye(i){let v=d("resolver",i.resolverId);v&&(M(v.entry,"directive.resolver.duration_ms",i.durationMs),D(v.entry,{code:I.OK}),w(v.entry),b(v.key));}function he(i){let v=d("resolver",i.resolverId);v&&(M(v.entry,"directive.resolver.duration_ms",i.durationMs),M(v.entry,"directive.resolver.error",i.errorMessage),D(v.entry,{code:I.ERROR,message:i.errorMessage}),w(v.entry),b(v.key));}function ve(i){let v=l.length>0?l[l.length-1]:null,{entry:R}=x(`${e}.pattern.${i.patternType}`,{"directive.service":r.serviceName,"directive.pattern.id":i.patternId,"directive.pattern.type":i.patternType},v),T=S("pattern",i.patternId);f("pattern",i.patternId,T,R),l.length<100&&l.push(R);}function Se(i){let v=d("pattern",i.patternId);if(v){M(v.entry,"directive.pattern.duration_ms",i.durationMs),i.error?(M(v.entry,"directive.pattern.error",i.error),D(v.entry,{code:I.ERROR,message:i.error})):D(v.entry,{code:I.OK}),w(v.entry),b(v.key);let R=l.indexOf(v.entry);R!==-1&&l.splice(R,1);}}return {attach(i){if(g&&g!==i)throw new Error("[Directive OTEL] Plugin already attached to a different timeline. Create a new plugin instance.");g=i;let v=i.subscribe(ue),R=setInterval(A,Math.min(n,6e4));return ()=>{v(),clearInterval(R),g=null;for(let[T,k]of p)M(k,"directive.detached",true),D(k,{code:I.ERROR,message:"Plugin detached while span was active"}),w(k);p.clear(),m.clear(),l.length=0;}},getSpans(){return c?[...c.spans]:(C||(C=true,typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[Directive OTEL] getSpans() returns [] when using an external tracer. Use the onSpanEnd callback to collect span data instead.")),[])},clearSpans(){c?.clear();},getTracer(){return o},getActiveSpanCount(){return p.size}}}function _n(r,e){let{tracer:t,serviceName:n,spanPrefix:s="directive.source",publishSampleRate:c=1}=e,o=new Map;function u(h,m){return `${m}::${h}`}function a(h,m){return {"service.name":n,"source.id":h,"source.module_id":m}}function y(h){switch(h.type){case "source.attach":{let m=h.id,l=h.moduleId,g=t.startSpan(`${s}.attached`,{attributes:{...a(m,l),"directive.attached":true}});o.set(u(m,l),{span:g,startedAt:Date.now()});break}case "source.publish":{if(c<1&&Math.random()>c)break;let m=h.id,l=h.moduleId,g=h.eventName,C=o.get(u(m,l));if(!C)break;C.span.addEvent("publish",{"source.event_name":g,"timestamp.ms":Date.now()});break}case "source.detach":{let m=h.id,l=h.moduleId,g=o.get(u(m,l));if(!g)break;g.span.setStatus({code:I.OK}),g.span.end(),o.delete(u(m,l));break}case "source.error":{let m=h.id,l=h.moduleId,g=h.phase,C=h.error,E=C instanceof Error?C.message:typeof C=="string"?C:String(C),S=t.startSpan(`${s}.error`,{attributes:{...a(m,l),"directive.phase":g,"error.message":E}});S.setStatus({code:I.ERROR,message:E}),S.end();let d=o.get(u(m,l));d&&d.span.addEvent("error",{"directive.phase":g,"error.message":E});break}}}let p=r.observe(y);return ()=>{p();for(let[,h]of o)h.span.setAttribute("directive.detached",true),h.span.setStatus({code:I.OK}),h.span.end();o.clear();}}Object.defineProperty(exports,"DEFAULT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.o}});Object.defineProperty(exports,"STRICT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.p}});Object.defineProperty(exports,"createBatchedEmbedder",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.A}});Object.defineProperty(exports,"createBruteForceIndex",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.B}});Object.defineProperty(exports,"createContentFilterGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.h}});Object.defineProperty(exports,"createEnhancedPIIGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.k}});Object.defineProperty(exports,"createFactPIIGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.i}});Object.defineProperty(exports,"createInMemoryStorage",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.w}});Object.defineProperty(exports,"createLengthGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.g}});Object.defineProperty(exports,"createModerationGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.b}});Object.defineProperty(exports,"createOutputPIIGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.l}});Object.defineProperty(exports,"createOutputSchemaGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.e}});Object.defineProperty(exports,"createOutputTypeGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.f}});Object.defineProperty(exports,"createPIIGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.a}});Object.defineProperty(exports,"createPromptInjectionGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.s}});Object.defineProperty(exports,"createRateLimitGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.c}});Object.defineProperty(exports,"createSemanticCache",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.x}});Object.defineProperty(exports,"createSemanticCacheGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.y}});Object.defineProperty(exports,"createTestEmbedder",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.z}});Object.defineProperty(exports,"createToolGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.d}});Object.defineProperty(exports,"createUntrustedContentGuardrail",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.u}});Object.defineProperty(exports,"createVPTreeIndex",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.C}});Object.defineProperty(exports,"detectAndRedactPII",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.n}});Object.defineProperty(exports,"detectPII",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.m}});Object.defineProperty(exports,"detectPromptInjection",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.q}});Object.defineProperty(exports,"markUntrustedContent",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.t}});Object.defineProperty(exports,"redactPII",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.j}});Object.defineProperty(exports,"sanitizeInjection",{enumerable:true,get:function(){return chunkZGJ2XHGI_cjs.r}});Object.defineProperty(exports,"connectDevTools",{enumerable:true,get:function(){return chunkIR3IHBVQ_cjs.b}});Object.defineProperty(exports,"createDevToolsServer",{enumerable:true,get:function(){return chunkIR3IHBVQ_cjs.a}});Object.defineProperty(exports,"createWsTransport",{enumerable:true,get:function(){return chunkIR3IHBVQ_cjs.c}});Object.defineProperty(exports,"createEvalSuite",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.k}});Object.defineProperty(exports,"evalAssert",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.l}});Object.defineProperty(exports,"evalCoherence",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.j}});Object.defineProperty(exports,"evalCost",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.a}});Object.defineProperty(exports,"evalFaithfulness",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.h}});Object.defineProperty(exports,"evalJudge",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.f}});Object.defineProperty(exports,"evalLatency",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.b}});Object.defineProperty(exports,"evalMatch",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.g}});Object.defineProperty(exports,"evalOutputLength",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.c}});Object.defineProperty(exports,"evalRelevance",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.i}});Object.defineProperty(exports,"evalSafety",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.d}});Object.defineProperty(exports,"evalStructure",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.e}});Object.defineProperty(exports,"convertToolsForLLM",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.b}});Object.defineProperty(exports,"createMCPAdapter",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.a}});Object.defineProperty(exports,"mcpCallTool",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.c}});Object.defineProperty(exports,"mcpGetPrompt",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.e}});Object.defineProperty(exports,"mcpReadResource",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.d}});Object.defineProperty(exports,"mcpSyncResources",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.f}});Object.defineProperty(exports,"createAgentOrchestrator",{enumerable:true,get:function(){return chunkTH2D22JP_cjs.a}});Object.defineProperty(exports,"createRunner",{enumerable:true,get:function(){return chunk3WO4MWJM_cjs.f}});Object.defineProperty(exports,"estimateCost",{enumerable:true,get:function(){return chunk3WO4MWJM_cjs.c}});Object.defineProperty(exports,"hasPendingApprovals",{enumerable:true,get:function(){return chunk3WO4MWJM_cjs.b}});Object.defineProperty(exports,"isAgentRunning",{enumerable:true,get:function(){return chunk3WO4MWJM_cjs.a}});Object.defineProperty(exports,"validateBaseURL",{enumerable:true,get:function(){return chunk3WO4MWJM_cjs.d}});Object.defineProperty(exports,"createAgentNetwork",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.c}});Object.defineProperty(exports,"createDelegator",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.e}});Object.defineProperty(exports,"createMessageBus",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.b}});Object.defineProperty(exports,"createPubSub",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.f}});Object.defineProperty(exports,"createResponder",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.d}});Object.defineProperty(exports,"explainGoal",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.j}});Object.defineProperty(exports,"getDependencyGraph",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.g}});Object.defineProperty(exports,"patternToMermaid",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.a}});Object.defineProperty(exports,"planGoal",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.i}});Object.defineProperty(exports,"validateGoal",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.h}});Object.defineProperty(exports,"InMemoryCheckpointStore",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.y}});Object.defineProperty(exports,"MAX_BREAKPOINT_HISTORY",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.s}});Object.defineProperty(exports,"ReflectionExhaustedError",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.K}});Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.N}});Object.defineProperty(exports,"adaptOutputGuardrail",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.E}});Object.defineProperty(exports,"aggregateTokens",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ia}});Object.defineProperty(exports,"allReadyStrategy",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs._}});Object.defineProperty(exports,"capabilityRoute",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.la}});Object.defineProperty(exports,"collectOutputs",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ha}});Object.defineProperty(exports,"collectTokens",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.F}});Object.defineProperty(exports,"combineStreamingGuardrails",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.D}});Object.defineProperty(exports,"composePatterns",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ja}});Object.defineProperty(exports,"concatResults",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.fa}});Object.defineProperty(exports,"costEfficientStrategy",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.aa}});Object.defineProperty(exports,"createBreakpointId",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.t}});Object.defineProperty(exports,"createCheckpointId",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.w}});Object.defineProperty(exports,"createInitialBreakpointState",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.v}});Object.defineProperty(exports,"createLengthStreamingGuardrail",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.B}});Object.defineProperty(exports,"createMultiAgentOrchestrator",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ra}});Object.defineProperty(exports,"createPatternStreamingGuardrail",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.C}});Object.defineProperty(exports,"createStreamingRunner",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.z}});Object.defineProperty(exports,"createToxicityStreamingGuardrail",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.A}});Object.defineProperty(exports,"dag",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.W}});Object.defineProperty(exports,"debate",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.na}});Object.defineProperty(exports,"derivedConstraint",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.pa}});Object.defineProperty(exports,"diffCheckpoints",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.Q}});Object.defineProperty(exports,"filterStream",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.H}});Object.defineProperty(exports,"findAgentsByCapability",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ka}});Object.defineProperty(exports,"forkFromCheckpoint",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.R}});Object.defineProperty(exports,"formatSystemMeta",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.a}});Object.defineProperty(exports,"getCheckpointProgress",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.P}});Object.defineProperty(exports,"getPatternStep",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.O}});Object.defineProperty(exports,"goal",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.Z}});Object.defineProperty(exports,"highestImpactStrategy",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.$}});Object.defineProperty(exports,"mapStream",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.I}});Object.defineProperty(exports,"matchBreakpoint",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.u}});Object.defineProperty(exports,"mergeTaggedStreams",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.J}});Object.defineProperty(exports,"parallel",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.T}});Object.defineProperty(exports,"patternFromJSON",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ca}});Object.defineProperty(exports,"patternToJSON",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ba}});Object.defineProperty(exports,"pickBestResult",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ga}});Object.defineProperty(exports,"race",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.Y}});Object.defineProperty(exports,"reflect",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.X}});Object.defineProperty(exports,"runAgentRequirement",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ea}});Object.defineProperty(exports,"runDebate",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.oa}});Object.defineProperty(exports,"selectAgent",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.da}});Object.defineProperty(exports,"sequential",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.U}});Object.defineProperty(exports,"spawnOnCondition",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ma}});Object.defineProperty(exports,"spawnPool",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.qa}});Object.defineProperty(exports,"supervisor",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.V}});Object.defineProperty(exports,"tapStream",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.G}});Object.defineProperty(exports,"toAIContext",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.b}});Object.defineProperty(exports,"validateCheckpoint",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.x}});Object.defineProperty(exports,"withReflection",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.L}});Object.defineProperty(exports,"GuardrailError",{enumerable:true,get:function(){return chunkK64WKZ22_cjs.a}});Object.defineProperty(exports,"isGuardrailError",{enumerable:true,get:function(){return chunkK64WKZ22_cjs.b}});Object.defineProperty(exports,"createDebugTimeline",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.a}});Object.defineProperty(exports,"createDebugTimelinePlugin",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.b}});Object.defineProperty(exports,"createHealthMonitor",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.c}});Object.defineProperty(exports,"PredicateFromIntentError",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.a}});Object.defineProperty(exports,"predicateFromIntent",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.b}});Object.defineProperty(exports,"predicateFromIntentRaw",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.c}});Object.defineProperty(exports,"predicateFromIntentWithProvenance",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.g}});Object.defineProperty(exports,"predicateToolSpec",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.f}});Object.defineProperty(exports,"predicateToolSpecAnthropic",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.e}});Object.defineProperty(exports,"predicateToolSpecOpenAI",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.d}});Object.defineProperty(exports,"StructuredOutputError",{enumerable:true,get:function(){return chunkWCQK3JOR_cjs.c}});Object.defineProperty(exports,"extractJsonFromOutput",{enumerable:true,get:function(){return chunkWCQK3JOR_cjs.a}});Object.defineProperty(exports,"withStructuredOutput",{enumerable:true,get:function(){return chunkWCQK3JOR_cjs.b}});Object.defineProperty(exports,"CircuitBreakerOpenError",{enumerable:true,get:function(){return plugins.CircuitBreakerOpenError}});Object.defineProperty(exports,"createCircuitBreaker",{enumerable:true,get:function(){return plugins.createCircuitBreaker}});Object.defineProperty(exports,"createOTLPExporter",{enumerable:true,get:function(){return plugins.createOTLPExporter}});exports.AllProvidersFailedError=_;exports.BudgetExceededError=N;exports.OtelStatusCode=I;exports.RetryExhaustedError=F;exports.attachSourcesToOtel=_n;exports.byAgentName=Dn;exports.byInputLength=Pn;exports.byPattern=On;exports.createAgentAuditHandlers=an;exports.createAgentMemory=Kr;exports.createAuditTrail=on;exports.createBatchQueue=jn;exports.createBidirectionalStream=gn;exports.createCompliance=pn;exports.createConstraintRouter=Gn;exports.createHybridStrategy=Vr;exports.createInMemoryComplianceStorage=dn;exports.createJSONFileStore=Cn;exports.createKeyPointsSummarizer=Jr;exports.createLLMSummarizer=qr;exports.createOtelPlugin=Fn;exports.createRAGEnricher=Sn;exports.createSSETransport=Rn;exports.createSlidingWindowStrategy=X;exports.createStreamChannel=K;exports.createTokenBasedStrategy=Y;exports.createTruncationSummarizer=Wr;exports.mergeStreams=fn;exports.parseHttpStatus=W;exports.parseRetryAfter=oe;exports.pipe=Hr;exports.pipeThrough=mn;exports.withBudget=Mn;exports.withFallback=xn;exports.withModelSelection=Bn;exports.withRetry=kn;//# sourceMappingURL=index.cjs.map
40
+ ${t}`),this.name="AllProvidersFailedError",this.errors=Object.freeze([...e]),e.length>0&&(this.cause=e[e.length-1]);}};function xn(r,e={}){if(r.length===0)throw new Error("[Directive] withFallback requires at least one runner.");let{shouldFallback:t,onFallback:n}=e;return async(s,c,o)=>{let u=[];for(let a=0;a<r.length;a++)try{return await r[a](s,c,o)}catch(y){let p=y instanceof Error?y:new Error(String(y));if(u.push(p),a<r.length-1){if(t)try{if(!t(p))break}catch{break}try{n?.(a,a+1,p);}catch{}}}throw new _(u)}}var N=class extends Error{estimated;remaining;window;constructor(e){super(`[Directive] Budget exceeded (${e.window}): estimated $${e.estimated.toFixed(4)}, remaining $${e.remaining.toFixed(4)}`),this.name="BudgetExceededError",this.estimated=e.estimated,this.remaining=e.remaining,this.window=e.window;}},$=class{entries=[];record(e){this.entries.push({timestamp:Date.now(),cost:e});}getCostInWindow(e){let t=Date.now()-e;this.prune(t);let n=0;for(let s of this.entries)s.timestamp>=t&&(n+=s.cost);return n}prune(e){let t=0;for(;t<this.entries.length&&this.entries[t].timestamp<e;)t++;t>0&&this.entries.splice(0,t);}clear(){this.entries=[];}},ae={hour:3600*1e3,day:1440*60*1e3};function In(r,e){return Math.ceil(r.length/e)}function se(r,e){return r.inputTokens/1e6*e.inputPerMillion+r.outputTokens/1e6*e.outputPerMillion}function ie(r,e,t=1){let n=Math.ceil(r*t);return r/1e6*e.inputPerMillion+n/1e6*e.outputPerMillion}function Mn(r,e){let{maxCostPerCall:t,budgets:n=[],pricing:s,charsPerToken:c=4,estimatedOutputMultiplier:o=1,onBudgetExceeded:u}=e;if(!Number.isFinite(c)||c<=0)throw new Error("[Directive] withBudget: charsPerToken must be a positive finite number.");if(t!=null&&(!Number.isFinite(t)||t<0))throw new Error("[Directive] withBudget: maxCostPerCall must be a non-negative finite number.");if(!Number.isFinite(o)||o<0)throw new Error("[Directive] withBudget: estimatedOutputMultiplier must be a non-negative finite number.");t!=null&&!s&&console.warn("[Directive] withBudget: maxCostPerCall has no effect without pricing. Provide a pricing config to enable per-call cost estimation.");for(let m of n)if(!Number.isFinite(m.maxCost)||m.maxCost<0)throw new Error(`[Directive] withBudget: budgets[${m.window}].maxCost must be a non-negative finite number.`);let a=new Map;for(let m of n)a.set(m.window,new $);let y=new $,p=async(m,l,g)=>{let C=In(l,c);if(t!=null&&s){let S=ie(C,s,o);if(S>t){let d={estimated:S,remaining:t,window:"per-call"};try{u?.(d);}catch{}throw new N(d)}}for(let S of n){let d=ae[S.window],b=a.get(S.window).getCostInWindow(d),A=S.maxCost-b,x=ie(C,S.pricing,o);if(x>A){let w={estimated:x,remaining:Math.max(0,A),window:S.window};try{u?.(w);}catch{}throw new N(w)}}let E=await r(m,l,g);if(E.tokenUsage){for(let S of n){let d=a.get(S.window),f=se(E.tokenUsage,S.pricing);d.record(f);}if(s&&n.length===0){let S=se(E.tokenUsage,s);y.record(S);}}return E};function h(m){let l=a.get(m);if(!l)return 0;let g=ae[m];return l.getCostInWindow(g)}return p.getSpent=h,p}function Pn(r,e){return {match:(t,n)=>n.length<=r,model:e}}function Dn(r,e){return {match:t=>t.name===r,model:e}}function On(r,e){return {match:(t,n)=>(r.lastIndex=0,r.test(n)),model:e}}function Bn(r,e){let t=Array.isArray(e)?{rules:e}:e,{rules:n,onModelSelected:s}=t;return async(c,o,u)=>{let a=c.model;for(let p of n)try{if(p.match(c,o)){a=p.model;break}}catch{}try{s?.(c.model,a);}catch{}let y=a!==c.model?{...c,model:a}:c;return r(y,o,u)}}function jn(r,e={}){let{maxBatchSize:t=20,maxWaitMs:n=5e3,concurrency:s=5}=e;if(!Number.isFinite(t)||t<1)throw new Error("[Directive] createBatchQueue: maxBatchSize must be a positive finite number (>= 1).");if(!Number.isFinite(n)||n<0)throw new Error("[Directive] createBatchQueue: maxWaitMs must be a non-negative finite number.");if(!Number.isFinite(s)||s<1)throw new Error("[Directive] createBatchQueue: concurrency must be a positive finite number (>= 1).");let c=[],o=null,u=false,a=null;function y(){o===null&&(o=setTimeout(()=>{o=null,m().catch(()=>{});},n));}function p(){o!==null&&(clearTimeout(o),o=null);}async function h(l){let g=0;async function C(){for(;g<l.length;){let S=g++,d=l[S];try{let f=await r(d.agent,d.input,d.options);d.resolve(f);}catch(f){d.reject(f instanceof Error?f:new Error(String(f)));}}}let E=Array.from({length:Math.min(s,l.length)},()=>C());await Promise.all(E);}async function m(){if(a&&await a,c.length===0)return;p();let l=c.splice(0);a=h(l).finally(()=>{a=null,c.length>0&&y();}),await a;}return {submit(l,g,C){return u?Promise.reject(new Error("[Directive] BatchQueue has been destroyed.")):new Promise((E,S)=>{c.push({agent:l,input:g,options:C,resolve:E,reject:S}),c.length>=t?(p(),m().catch(()=>{})):y();})},async flush(){await m();},get pending(){return c.length},async destroy(){u||(u=true,p(),c.length>0&&await m());}}}function ce(){return {callCount:0,errorCount:0,totalCost:0,avgLatencyMs:0,lastErrorAt:null}}function Nn(r,e){return !r||!e?0:r.inputTokens/1e6*e.inputPerMillion+r.outputTokens/1e6*e.outputPerMillion}function Gn(r){let{providers:e,defaultProvider:t,constraints:n=[],onProviderSelected:s,errorCooldownMs:c=3e4,preferCheapest:o=false}=r;if(!Number.isFinite(c)||c<0)throw new Error("[Directive] createConstraintRouter: errorCooldownMs must be a non-negative finite number.");let u=new Map;for(let g of e)u.set(g.name,g);if(!u.has(t))throw new Error(`[Directive] Default provider "${t}" not found in providers list.`);let a={totalCost:0,callCount:0,errorCount:0,lastProvider:null,avgLatencyMs:0,providers:Object.create(null)};for(let g of e)a.providers[g.name]=ce();let y=0,p=[...n].sort((g,C)=>(C.priority??0)-(g.priority??0));function h(){let g=Date.now();for(let E of p)try{if(E.when(a)){let S=u.get(E.provider);if(S)return {provider:S,reason:"constraint"}}}catch{}let C=e.filter(E=>{let S=a.providers[E.name];return S?!(S.lastErrorAt&&g-S.lastErrorAt<c):true});if(o&&C.length>0){let E=[...C].sort((S,d)=>{let f=S.pricing?S.pricing.inputPerMillion+S.pricing.outputPerMillion:Number.POSITIVE_INFINITY,b=d.pricing?d.pricing.inputPerMillion+d.pricing.outputPerMillion:Number.POSITIVE_INFINITY;return f!==b?f-b:S.name===t?-1:d.name===t?1:0});if(E[0]!==u.get(t))return {provider:E[0],reason:"cheapest"}}return C.length>0&&!C.some(E=>E.name===t)?{provider:C[0],reason:"default"}:{provider:u.get(t),reason:"default"}}function m(g,C,E,S,d){let f=a.providers[g]??ce();if(f.callCount++,a.callCount++,d)f.errorCount++,a.errorCount++,f.lastErrorAt=Date.now();else {let A=Nn(E,S);f.totalCost+=A,a.totalCost+=A;}y+=C,a.avgLatencyMs=y/a.callCount;let b=f.callCount>0?(f.avgLatencyMs*(f.callCount-1)+C)/f.callCount:C;f.avgLatencyMs=b,a.providers[g]=f,a.lastProvider=g;}let l=async(g,C,E)=>{let{provider:S,reason:d}=h();try{s?.(S.name,d);}catch{}let f=Date.now();try{let b=await S.runner(g,C,E),A=Date.now()-f;return m(S.name,A,b.tokenUsage,S.pricing),b}catch(b){let A=Date.now()-f,x=b instanceof Error?b:new Error(String(b));throw m(S.name,A,void 0,S.pricing,x),x}};return Object.defineProperty(l,"facts",{get:()=>{let g=Object.create(null);for(let C of Object.keys(a.providers))g[C]={...a.providers[C]};return {...a,providers:g}},enumerable:true}),l}var I={UNSET:0,OK:1,ERROR:2},L=class{constructor(e,t,n,s,c,o){this.name=e;this.spanId=t;this.traceId=n;this.parentSpanId=s;this.onEnd=o;if(this.startTime=Date.now(),c)for(let[u,a]of Object.entries(c))this.attributes[u]=a;}attributes=Object.create(null);spanEvents=[];status={code:I.UNSET};startTime;endTime=0;setAttribute(e,t){this.attributes[e]=t;}addEvent(e,t){this.spanEvents.push({name:e,attributes:t,timestamp:Date.now()});}setStatus(e){this.status=e;}end(){this.endTime=Date.now(),this.onEnd?.(this);}toSpanData(){return {name:this.name,traceId:this.traceId,spanId:this.spanId,parentSpanId:this.parentSpanId,attributes:{...this.attributes},events:[...this.spanEvents],status:{...this.status},startTime:this.startTime,endTime:this.endTime,durationMs:this.endTime-this.startTime}}},J=class{spans=[];startSpan(e,t){let n=t?.spanId??`fallback-${crypto.randomUUID()}`,s=t?.traceId??`fallback-${crypto.randomUUID()}`,c=t?.parentSpanId;return new L(e,n,s,c,t?.attributes,o=>{this.spans.push(o.toSpanData());})}clear(){this.spans.length=0;}};function Fn(r){let e=r.spanPrefix??"directive.ai",t=r.instrumentEvents,n=r.spanTtlMs??3e5,s=!r.tracer,c=s?new J:null,o=r.tracer??c,u=0;function a(){return `${Date.now().toString(36)}-${(u++).toString(36)}`}function y(){return `${Date.now().toString(36)}-${crypto.randomUUID().slice(0,8)}`}let p=new Map,h=0,m=new Map,l=[],g=null,C=false;function E(i){return t?t.has(i):true}function S(i,v){return `${i}:${v}:${h++}`}function d(i,v){let R=`${i}:${v}`,T=m.get(R);if(T){for(let k=T.length-1;k>=0;k--){let O=p.get(T[k]);if(O)return {key:T[k],entry:O}}m.delete(R);}return null}function f(i,v,R,T){let k=`${i}:${v}`;T.indexKey=k,p.set(R,T);let O=m.get(k);O?O.push(R):m.set(k,[R]);}function b(i){let v=p.get(i);p.delete(i);let R=v?.indexKey;if(R){let T=m.get(R);if(T){let k=T.indexOf(i);k!==-1&&T.splice(k,1),T.length===0&&m.delete(R);}}}function A(){let i=Date.now();if(p.size<1e4){for(let[R,T]of p)i-T.startTime>n&&(M(T,"directive.stale",true),D(T,{code:I.ERROR,message:"Span TTL exceeded \u2014 cleaned up"}),w(T),b(R),true);return void 0}for(let[v,R]of p)i-R.startTime>n&&(M(R,"directive.stale",true),D(R,{code:I.ERROR,message:"Span TTL exceeded \u2014 cleaned up"}),w(R),b(v));}function x(i,v,R){let T=a(),k=R?.traceId??y(),O=R?.spanId,B;s?B=o.startSpan(i,{attributes:v,spanId:T,traceId:k,parentSpanId:O}):B=o.startSpan(i,{attributes:v});let z={span:B,spanId:T,traceId:k,startTime:Date.now()};return s||(z.shadow={span:B,name:i,spanId:T,traceId:k,parentSpanId:O,attributes:{...v},events:[],status:{code:I.UNSET},startTime:z.startTime}),{span:B,entry:z}}function w(i){i.span.end(),r.onSpanEnd&&r.onSpanEnd(P(i));}function P(i){if(i.span instanceof L)return i.span.toSpanData();if(i.shadow){let R=Date.now();return {name:i.shadow.name,traceId:i.shadow.traceId,spanId:i.shadow.spanId,parentSpanId:i.shadow.parentSpanId,attributes:{...i.shadow.attributes},events:[...i.shadow.events],status:{...i.shadow.status},startTime:i.shadow.startTime,endTime:R,durationMs:R-i.shadow.startTime}}let v=Date.now();return {name:"unknown",traceId:i.traceId,spanId:i.spanId,attributes:{},events:[],status:{code:I.UNSET},startTime:i.startTime,endTime:v,durationMs:v-i.startTime}}function M(i,v,R){i.span.setAttribute(v,R),i.shadow&&(i.shadow.attributes[v]=R);}function q(i,v,R){i.span.addEvent(v,R),i.shadow&&i.shadow.events.push({name:v,attributes:R,timestamp:Date.now()});}function D(i,v){i.span.setStatus(v),i.shadow&&(i.shadow.status={...v});}function ue(i){if(E(i.type))switch(A(),i.type){case "agent_start":le(i);break;case "agent_complete":de(i);break;case "agent_error":pe(i);break;case "guardrail_check":ge(i);break;case "constraint_evaluate":me(i);break;case "resolver_start":fe(i);break;case "resolver_complete":ye(i);break;case "resolver_error":he(i);break;case "pattern_start":ve(i);break;case "pattern_complete":Se(i);break;default:if(i.agentId){let v=d("agent",i.agentId);v&&q(v.entry,i.type,{"event.id":i.id,"event.timestamp":i.timestamp});}}}function le(i){let v=l.length>0?l[l.length-1]:null,{entry:R}=x(`${e}.agent.run`,{"directive.service":r.serviceName,"directive.agent.name":i.agentId,"directive.agent.input_length":i.inputLength,"gen_ai.operation.name":"agent.run","gen_ai.agent.name":i.agentId},v),T=S("agent",i.agentId);f("agent",i.agentId,T,R);}function de(i){let v=d("agent",i.agentId);v&&(M(v.entry,"directive.agent.output_length",i.outputLength),M(v.entry,"directive.agent.total_tokens",i.totalTokens),M(v.entry,"directive.agent.duration_ms",i.durationMs),M(v.entry,"gen_ai.usage.total_tokens",i.totalTokens),D(v.entry,{code:I.OK}),w(v.entry),b(v.key));}function pe(i){let v=d("agent",i.agentId);v&&(M(v.entry,"directive.agent.duration_ms",i.durationMs),M(v.entry,"directive.agent.error",i.errorMessage),M(v.entry,"gen_ai.error.message",i.errorMessage),D(v.entry,{code:I.ERROR,message:i.errorMessage}),w(v.entry),b(v.key));}function ge(i){let v=i.agentId?d("agent",i.agentId)?.entry??null:null,{entry:R}=x(`${e}.guardrail.check`,{"directive.service":r.serviceName,"directive.guardrail.name":i.guardrailName,"directive.guardrail.type":i.guardrailType,"directive.guardrail.passed":i.passed,"directive.guardrail.duration_ms":i.durationMs,"gen_ai.guardrail.name":i.guardrailName,"gen_ai.guardrail.type":i.guardrailType,"gen_ai.guardrail.passed":i.passed},v);i.reason&&M(R,"directive.guardrail.reason",i.reason),D(R,{code:i.passed?I.OK:I.ERROR,message:i.passed?void 0:i.reason}),w(R);}function me(i){if(i.agentId){let R=d("agent",i.agentId);if(R){q(R.entry,"constraint_evaluate",{"directive.constraint.id":i.constraintId,"directive.constraint.fired":i.fired});return}}let{entry:v}=x(`${e}.constraint.evaluate`,{"directive.service":r.serviceName,"directive.constraint.id":i.constraintId,"directive.constraint.fired":i.fired},null);D(v,{code:I.OK}),w(v);}function fe(i){let R=(i.agentId?d("agent",i.agentId)?.entry??null:null)??(l.length>0?l[l.length-1]:null),{entry:T}=x(`${e}.resolver.execute`,{"directive.service":r.serviceName,"directive.resolver.id":i.resolverId,"directive.resolver.requirement_type":i.requirementType},R),k=S("resolver",i.resolverId);f("resolver",i.resolverId,k,T);}function ye(i){let v=d("resolver",i.resolverId);v&&(M(v.entry,"directive.resolver.duration_ms",i.durationMs),D(v.entry,{code:I.OK}),w(v.entry),b(v.key));}function he(i){let v=d("resolver",i.resolverId);v&&(M(v.entry,"directive.resolver.duration_ms",i.durationMs),M(v.entry,"directive.resolver.error",i.errorMessage),D(v.entry,{code:I.ERROR,message:i.errorMessage}),w(v.entry),b(v.key));}function ve(i){let v=l.length>0?l[l.length-1]:null,{entry:R}=x(`${e}.pattern.${i.patternType}`,{"directive.service":r.serviceName,"directive.pattern.id":i.patternId,"directive.pattern.type":i.patternType},v),T=S("pattern",i.patternId);f("pattern",i.patternId,T,R),l.length<100&&l.push(R);}function Se(i){let v=d("pattern",i.patternId);if(v){M(v.entry,"directive.pattern.duration_ms",i.durationMs),i.error?(M(v.entry,"directive.pattern.error",i.error),D(v.entry,{code:I.ERROR,message:i.error})):D(v.entry,{code:I.OK}),w(v.entry),b(v.key);let R=l.indexOf(v.entry);R!==-1&&l.splice(R,1);}}return {attach(i){if(g&&g!==i)throw new Error("[Directive OTEL] Plugin already attached to a different timeline. Create a new plugin instance.");g=i;let v=i.subscribe(ue),R=setInterval(A,Math.min(n,6e4));return ()=>{v(),clearInterval(R),g=null;for(let[T,k]of p)M(k,"directive.detached",true),D(k,{code:I.ERROR,message:"Plugin detached while span was active"}),w(k);p.clear(),m.clear(),l.length=0;}},getSpans(){return c?[...c.spans]:(C||(C=true,typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[Directive OTEL] getSpans() returns [] when using an external tracer. Use the onSpanEnd callback to collect span data instead.")),[])},clearSpans(){c?.clear();},getTracer(){return o},getActiveSpanCount(){return p.size}}}function _n(r,e){let{tracer:t,serviceName:n,spanPrefix:s="directive.source",publishSampleRate:c=1}=e,o=new Map;function u(h,m){return `${m}::${h}`}function a(h,m){return {"service.name":n,"source.id":h,"source.module_id":m}}function y(h){switch(h.type){case "source.attach":{let m=h.id,l=h.moduleId,g=t.startSpan(`${s}.attached`,{attributes:{...a(m,l),"directive.attached":true}});o.set(u(m,l),{span:g,startedAt:Date.now()});break}case "source.publish":{if(c<1&&Math.random()>c)break;let m=h.id,l=h.moduleId,g=h.eventName,C=o.get(u(m,l));if(!C)break;C.span.addEvent("publish",{"source.event_name":g,"timestamp.ms":Date.now()});break}case "source.detach":{let m=h.id,l=h.moduleId,g=o.get(u(m,l));if(!g)break;g.span.setStatus({code:I.OK}),g.span.end(),o.delete(u(m,l));break}case "source.error":{let m=h.id,l=h.moduleId,g=h.phase,C=h.error,E=C instanceof Error?C.message:typeof C=="string"?C:String(C),S=t.startSpan(`${s}.error`,{attributes:{...a(m,l),"directive.phase":g,"error.message":E}});S.setStatus({code:I.ERROR,message:E}),S.end();let d=o.get(u(m,l));d&&d.span.addEvent("error",{"directive.phase":g,"error.message":E});break}}}let p=r.observe(y);return ()=>{p();for(let[,h]of o)h.span.setAttribute("directive.detached",true),h.span.setStatus({code:I.OK}),h.span.end();o.clear();}}Object.defineProperty(exports,"DEFAULT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.o}});Object.defineProperty(exports,"STRICT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.p}});Object.defineProperty(exports,"createBatchedEmbedder",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.A}});Object.defineProperty(exports,"createBruteForceIndex",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.B}});Object.defineProperty(exports,"createContentFilterGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.h}});Object.defineProperty(exports,"createEnhancedPIIGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.k}});Object.defineProperty(exports,"createFactPIIGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.i}});Object.defineProperty(exports,"createInMemoryStorage",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.w}});Object.defineProperty(exports,"createLengthGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.g}});Object.defineProperty(exports,"createModerationGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.b}});Object.defineProperty(exports,"createOutputPIIGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.l}});Object.defineProperty(exports,"createOutputSchemaGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.e}});Object.defineProperty(exports,"createOutputTypeGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.f}});Object.defineProperty(exports,"createPIIGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.a}});Object.defineProperty(exports,"createPromptInjectionGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.s}});Object.defineProperty(exports,"createRateLimitGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.c}});Object.defineProperty(exports,"createSemanticCache",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.x}});Object.defineProperty(exports,"createSemanticCacheGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.y}});Object.defineProperty(exports,"createTestEmbedder",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.z}});Object.defineProperty(exports,"createToolGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.d}});Object.defineProperty(exports,"createUntrustedContentGuardrail",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.u}});Object.defineProperty(exports,"createVPTreeIndex",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.C}});Object.defineProperty(exports,"detectAndRedactPII",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.n}});Object.defineProperty(exports,"detectPII",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.m}});Object.defineProperty(exports,"detectPromptInjection",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.q}});Object.defineProperty(exports,"markUntrustedContent",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.t}});Object.defineProperty(exports,"redactPII",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.j}});Object.defineProperty(exports,"sanitizeInjection",{enumerable:true,get:function(){return chunkMPMBFW2P_cjs.r}});Object.defineProperty(exports,"connectDevTools",{enumerable:true,get:function(){return chunk7JTR4QBA_cjs.b}});Object.defineProperty(exports,"createDevToolsServer",{enumerable:true,get:function(){return chunk7JTR4QBA_cjs.a}});Object.defineProperty(exports,"createWsTransport",{enumerable:true,get:function(){return chunk7JTR4QBA_cjs.c}});Object.defineProperty(exports,"createEvalSuite",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.k}});Object.defineProperty(exports,"evalAssert",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.l}});Object.defineProperty(exports,"evalCoherence",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.j}});Object.defineProperty(exports,"evalCost",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.a}});Object.defineProperty(exports,"evalFaithfulness",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.h}});Object.defineProperty(exports,"evalJudge",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.f}});Object.defineProperty(exports,"evalLatency",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.b}});Object.defineProperty(exports,"evalMatch",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.g}});Object.defineProperty(exports,"evalOutputLength",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.c}});Object.defineProperty(exports,"evalRelevance",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.i}});Object.defineProperty(exports,"evalSafety",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.d}});Object.defineProperty(exports,"evalStructure",{enumerable:true,get:function(){return chunkXN5LUOVS_cjs.e}});Object.defineProperty(exports,"convertToolsForLLM",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.b}});Object.defineProperty(exports,"createMCPAdapter",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.a}});Object.defineProperty(exports,"mcpCallTool",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.c}});Object.defineProperty(exports,"mcpGetPrompt",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.e}});Object.defineProperty(exports,"mcpReadResource",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.d}});Object.defineProperty(exports,"mcpSyncResources",{enumerable:true,get:function(){return chunkC6MQ4WL6_cjs.f}});Object.defineProperty(exports,"createAgentOrchestrator",{enumerable:true,get:function(){return chunkESJQSOKJ_cjs.a}});Object.defineProperty(exports,"createRunner",{enumerable:true,get:function(){return chunk3WO4MWJM_cjs.f}});Object.defineProperty(exports,"estimateCost",{enumerable:true,get:function(){return chunk3WO4MWJM_cjs.c}});Object.defineProperty(exports,"hasPendingApprovals",{enumerable:true,get:function(){return chunk3WO4MWJM_cjs.b}});Object.defineProperty(exports,"isAgentRunning",{enumerable:true,get:function(){return chunk3WO4MWJM_cjs.a}});Object.defineProperty(exports,"validateBaseURL",{enumerable:true,get:function(){return chunk3WO4MWJM_cjs.d}});Object.defineProperty(exports,"createAgentNetwork",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.c}});Object.defineProperty(exports,"createDelegator",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.e}});Object.defineProperty(exports,"createMessageBus",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.b}});Object.defineProperty(exports,"createPubSub",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.f}});Object.defineProperty(exports,"createResponder",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.d}});Object.defineProperty(exports,"explainGoal",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.j}});Object.defineProperty(exports,"getDependencyGraph",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.g}});Object.defineProperty(exports,"patternToMermaid",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.a}});Object.defineProperty(exports,"planGoal",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.i}});Object.defineProperty(exports,"validateGoal",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.h}});Object.defineProperty(exports,"InMemoryCheckpointStore",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.y}});Object.defineProperty(exports,"MAX_BREAKPOINT_HISTORY",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.s}});Object.defineProperty(exports,"ReflectionExhaustedError",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.K}});Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.N}});Object.defineProperty(exports,"adaptOutputGuardrail",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.E}});Object.defineProperty(exports,"aggregateTokens",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ia}});Object.defineProperty(exports,"allReadyStrategy",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs._}});Object.defineProperty(exports,"capabilityRoute",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.la}});Object.defineProperty(exports,"collectOutputs",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ha}});Object.defineProperty(exports,"collectTokens",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.F}});Object.defineProperty(exports,"combineStreamingGuardrails",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.D}});Object.defineProperty(exports,"composePatterns",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ja}});Object.defineProperty(exports,"concatResults",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.fa}});Object.defineProperty(exports,"costEfficientStrategy",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.aa}});Object.defineProperty(exports,"createBreakpointId",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.t}});Object.defineProperty(exports,"createCheckpointId",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.w}});Object.defineProperty(exports,"createInitialBreakpointState",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.v}});Object.defineProperty(exports,"createLengthStreamingGuardrail",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.B}});Object.defineProperty(exports,"createMultiAgentOrchestrator",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ra}});Object.defineProperty(exports,"createPatternStreamingGuardrail",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.C}});Object.defineProperty(exports,"createStreamingRunner",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.z}});Object.defineProperty(exports,"createToxicityStreamingGuardrail",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.A}});Object.defineProperty(exports,"dag",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.W}});Object.defineProperty(exports,"debate",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.na}});Object.defineProperty(exports,"derivedConstraint",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.pa}});Object.defineProperty(exports,"diffCheckpoints",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.Q}});Object.defineProperty(exports,"filterStream",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.H}});Object.defineProperty(exports,"findAgentsByCapability",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ka}});Object.defineProperty(exports,"forkFromCheckpoint",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.R}});Object.defineProperty(exports,"formatSystemMeta",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.a}});Object.defineProperty(exports,"getCheckpointProgress",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.P}});Object.defineProperty(exports,"getPatternStep",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.O}});Object.defineProperty(exports,"goal",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.Z}});Object.defineProperty(exports,"highestImpactStrategy",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.$}});Object.defineProperty(exports,"mapStream",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.I}});Object.defineProperty(exports,"matchBreakpoint",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.u}});Object.defineProperty(exports,"mergeTaggedStreams",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.J}});Object.defineProperty(exports,"parallel",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.T}});Object.defineProperty(exports,"patternFromJSON",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ca}});Object.defineProperty(exports,"patternToJSON",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ba}});Object.defineProperty(exports,"pickBestResult",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ga}});Object.defineProperty(exports,"race",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.Y}});Object.defineProperty(exports,"reflect",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.X}});Object.defineProperty(exports,"runAgentRequirement",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ea}});Object.defineProperty(exports,"runDebate",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.oa}});Object.defineProperty(exports,"selectAgent",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.da}});Object.defineProperty(exports,"sequential",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.U}});Object.defineProperty(exports,"spawnOnCondition",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ma}});Object.defineProperty(exports,"spawnPool",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.qa}});Object.defineProperty(exports,"supervisor",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.V}});Object.defineProperty(exports,"tapStream",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.G}});Object.defineProperty(exports,"toAIContext",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.b}});Object.defineProperty(exports,"validateCheckpoint",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.x}});Object.defineProperty(exports,"withReflection",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.L}});Object.defineProperty(exports,"GuardrailError",{enumerable:true,get:function(){return chunkK64WKZ22_cjs.a}});Object.defineProperty(exports,"isGuardrailError",{enumerable:true,get:function(){return chunkK64WKZ22_cjs.b}});Object.defineProperty(exports,"createDebugTimeline",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.a}});Object.defineProperty(exports,"createDebugTimelinePlugin",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.b}});Object.defineProperty(exports,"createHealthMonitor",{enumerable:true,get:function(){return chunkWOFIBIPW_cjs.c}});Object.defineProperty(exports,"PredicateFromIntentError",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.a}});Object.defineProperty(exports,"predicateFromIntent",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.b}});Object.defineProperty(exports,"predicateFromIntentRaw",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.c}});Object.defineProperty(exports,"predicateFromIntentWithProvenance",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.g}});Object.defineProperty(exports,"predicateToolSpec",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.f}});Object.defineProperty(exports,"predicateToolSpecAnthropic",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.e}});Object.defineProperty(exports,"predicateToolSpecOpenAI",{enumerable:true,get:function(){return chunkMDXDPECP_cjs.d}});Object.defineProperty(exports,"StructuredOutputError",{enumerable:true,get:function(){return chunkWCQK3JOR_cjs.c}});Object.defineProperty(exports,"extractJsonFromOutput",{enumerable:true,get:function(){return chunkWCQK3JOR_cjs.a}});Object.defineProperty(exports,"withStructuredOutput",{enumerable:true,get:function(){return chunkWCQK3JOR_cjs.b}});Object.defineProperty(exports,"CircuitBreakerOpenError",{enumerable:true,get:function(){return plugins.CircuitBreakerOpenError}});Object.defineProperty(exports,"createCircuitBreaker",{enumerable:true,get:function(){return plugins.createCircuitBreaker}});Object.defineProperty(exports,"createOTLPExporter",{enumerable:true,get:function(){return plugins.createOTLPExporter}});exports.AllProvidersFailedError=_;exports.BudgetExceededError=N;exports.OtelStatusCode=I;exports.RetryExhaustedError=F;exports.attachSourcesToOtel=_n;exports.byAgentName=Dn;exports.byInputLength=Pn;exports.byPattern=On;exports.createAgentAuditHandlers=an;exports.createAgentMemory=Kr;exports.createAuditTrail=on;exports.createBatchQueue=jn;exports.createBidirectionalStream=gn;exports.createCompliance=pn;exports.createConstraintRouter=Gn;exports.createHybridStrategy=Vr;exports.createInMemoryComplianceStorage=dn;exports.createJSONFileStore=Cn;exports.createKeyPointsSummarizer=Jr;exports.createLLMSummarizer=qr;exports.createOtelPlugin=Fn;exports.createRAGEnricher=Sn;exports.createSSETransport=Rn;exports.createSlidingWindowStrategy=X;exports.createStreamChannel=K;exports.createTokenBasedStrategy=Y;exports.createTruncationSummarizer=Wr;exports.mergeStreams=fn;exports.parseHttpStatus=W;exports.parseRetryAfter=oe;exports.pipe=Hr;exports.pipeThrough=mn;exports.withBudget=Mn;exports.withFallback=xn;exports.withModelSelection=Bn;exports.withRetry=kn;//# sourceMappingURL=index.cjs.map
41
41
  //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import {v,m,j as j$1}from'./chunk-VSVR4RFK.js';export{o as DEFAULT_INJECTION_PATTERNS,p as STRICT_INJECTION_PATTERNS,A as createBatchedEmbedder,B as createBruteForceIndex,h as createContentFilterGuardrail,k as createEnhancedPIIGuardrail,i as createFactPIIGuardrail,w as createInMemoryStorage,g as createLengthGuardrail,b as createModerationGuardrail,l as createOutputPIIGuardrail,e as createOutputSchemaGuardrail,f as createOutputTypeGuardrail,a as createPIIGuardrail,s as createPromptInjectionGuardrail,c as createRateLimitGuardrail,x as createSemanticCache,y as createSemanticCacheGuardrail,z as createTestEmbedder,d as createToolGuardrail,u as createUntrustedContentGuardrail,C as createVPTreeIndex,n as detectAndRedactPII,m as detectPII,q as detectPromptInjection,t as markUntrustedContent,j as redactPII,r as sanitizeInjection}from'./chunk-VSVR4RFK.js';export{b as connectDevTools,a as createDevToolsServer,c as createWsTransport}from'./chunk-5JQ2A3JK.js';export{k as createEvalSuite,l as evalAssert,j as evalCoherence,a as evalCost,h as evalFaithfulness,f as evalJudge,b as evalLatency,g as evalMatch,c as evalOutputLength,i as evalRelevance,d as evalSafety,e as evalStructure}from'./chunk-J2Q5KKPN.js';export{b as convertToolsForLLM,a as createMCPAdapter,c as mcpCallTool,e as mcpGetPrompt,d as mcpReadResource,f as mcpSyncResources}from'./chunk-V2FCPNPP.js';export{a as createAgentOrchestrator}from'./chunk-QRDBUGPO.js';export{f as createRunner,c as estimateCost,b as hasPendingApprovals,a as isAgentRunning,d as validateBaseURL}from'./chunk-ZFLHWJ56.js';export{c as createAgentNetwork,e as createDelegator,b as createMessageBus,f as createPubSub,d as createResponder,j as explainGoal,g as getDependencyGraph,a as patternToMermaid,i as planGoal,h as validateGoal}from'./chunk-RHJAMXLS.js';export{y as InMemoryCheckpointStore,s as MAX_BREAKPOINT_HISTORY,K as ReflectionExhaustedError,N as Semaphore,E as adaptOutputGuardrail,ia as aggregateTokens,_ as allReadyStrategy,la as capabilityRoute,ha as collectOutputs,F as collectTokens,D as combineStreamingGuardrails,ja as composePatterns,fa as concatResults,aa as costEfficientStrategy,t as createBreakpointId,w as createCheckpointId,v as createInitialBreakpointState,B as createLengthStreamingGuardrail,ra as createMultiAgentOrchestrator,C as createPatternStreamingGuardrail,z as createStreamingRunner,A as createToxicityStreamingGuardrail,W as dag,na as debate,pa as derivedConstraint,Q as diffCheckpoints,H as filterStream,ka as findAgentsByCapability,R as forkFromCheckpoint,a as formatSystemMeta,P as getCheckpointProgress,O as getPatternStep,Z as goal,$ as highestImpactStrategy,I as mapStream,u as matchBreakpoint,J as mergeTaggedStreams,T as parallel,ca as patternFromJSON,ba as patternToJSON,ga as pickBestResult,Y as race,X as reflect,ea as runAgentRequirement,oa as runDebate,da as selectAgent,U as sequential,ma as spawnOnCondition,qa as spawnPool,V as supervisor,G as tapStream,b as toAIContext,x as validateCheckpoint,L as withReflection}from'./chunk-G7CRWJT7.js';export{a as GuardrailError,b as isGuardrailError}from'./chunk-UR5BMWEN.js';export{a as createDebugTimeline,b as createDebugTimelinePlugin,c as createHealthMonitor}from'./chunk-FBT73WFY.js';export{a as PredicateFromIntentError,b as predicateFromIntent,c as predicateFromIntentRaw,g as predicateFromIntentWithProvenance,f as predicateToolSpec,e as predicateToolSpecAnthropic,d as predicateToolSpecOpenAI}from'./chunk-GTB6HTZV.js';export{c as StructuredOutputError,a as extractJsonFromOutput,b as withStructuredOutput}from'./chunk-HRR45JZX.js';export{CircuitBreakerOpenError,createCircuitBreaker,createOTLPExporter}from'@directive-run/core/plugins';import G from'path';function Hr(r,...e){let t=r;for(let n of e)t=n(t);return t}function j(r,e){let t=typeof r.content=="string"?r.content:JSON.stringify(r.content);return Math.ceil(t.length/4)}function V(r,e){return r.reduce((t,n)=>t+j(n),0)}function X(r={}){return (e,t={})=>{let n={...r,...t},s=n.maxMessages??100,c=n.preserveRecentCount??5;if(e.length<=s)return {keep:[...e],toSummarize:[],estimatedTokens:V(e)};let o=e.slice(-c),u=e.slice(0,-c),a=Math.max(0,s-c),y=u.slice(-a),p=u.slice(0,-a||void 0),h=[...y,...o];return {keep:h,toSummarize:p.length>0?p:[],estimatedTokens:V(h)}}}function Y(r={}){return (e,t={})=>{let n={...r,...t},s=n.maxTokens??4e3,c=n.preserveRecentCount??5,o=n.countSystemMessages??true,u=e.slice(-c),a=e.slice(0,-c),y=u.reduce((l,g)=>!o&&g.role==="system"?l:l+j(g),0),p=[],h=[],m=y;for(let l=a.length-1;l>=0;l--){let g=a[l],C=!o&&g.role==="system"?0:j(g);if(m+C<=s)p.unshift(g),m+=C;else {h.push(...a.slice(0,l+1));break}}return {keep:[...p,...u],toSummarize:h,estimatedTokens:m}}}function Vr(r={}){let e=X(r),t=Y(r);return (n,s={})=>{let c={...r,...s},o=e(n,c),u=t(n,c);return o.keep.length<=u.keep.length?o:u}}function Kr(r){let{strategy:e,summarizer:t,strategyConfig:n={},autoManage:s=false,onMemoryManaged:c,onManageError:o,maxContextTokens:u}=r,a={messages:[],summaries:[],totalMessagesProcessed:0,estimatedTokens:0},y=false;async function p(){if(y)return {messagesBefore:a.messages.length,messagesAfter:a.messages.length,messagesSummarized:0,estimatedTokensBefore:a.estimatedTokens,estimatedTokensAfter:a.estimatedTokens};y=true;try{let m=a.messages.length,l=a.estimatedTokens,g=e(a.messages,n);if(g.toSummarize.length===0)return {messagesBefore:m,messagesAfter:m,messagesSummarized:0,estimatedTokensBefore:l,estimatedTokensAfter:g.estimatedTokens};let C;t&&g.toSummarize.length>0&&(C=await t(g.toSummarize),a.summaries.push({content:C,messagesCount:g.toSummarize.length,createdAt:Date.now()})),a.messages=g.keep,a.estimatedTokens=g.estimatedTokens;let E={messagesBefore:m,messagesAfter:a.messages.length,messagesSummarized:g.toSummarize.length,summary:C,estimatedTokensBefore:l,estimatedTokensAfter:g.estimatedTokens};return c?.(E),E}finally{y=false;}}function h(){if(y)return;e(a.messages,n).toSummarize.length>0&&p().catch(l=>{let g=l instanceof Error?l:new Error(String(l));o?o(g):console.error("[Directive Memory] Auto-manage error:",g);});}return {getState(){return {...a,messages:[...a.messages],summaries:a.summaries.map(m=>({...m}))}},addMessage(m){a.messages.push(m),a.totalMessagesProcessed++,a.estimatedTokens+=j(m),s&&h();},addMessages(m){for(let l of m)a.messages.push(l),a.totalMessagesProcessed++,a.estimatedTokens+=j(l);s&&h();},getContextMessages(){let m=[];if(a.summaries.length>0){let l=a.summaries.map(g=>g.content).join(`
1
+ import {v,m,j as j$1}from'./chunk-TEPEQE42.js';export{o as DEFAULT_INJECTION_PATTERNS,p as STRICT_INJECTION_PATTERNS,A as createBatchedEmbedder,B as createBruteForceIndex,h as createContentFilterGuardrail,k as createEnhancedPIIGuardrail,i as createFactPIIGuardrail,w as createInMemoryStorage,g as createLengthGuardrail,b as createModerationGuardrail,l as createOutputPIIGuardrail,e as createOutputSchemaGuardrail,f as createOutputTypeGuardrail,a as createPIIGuardrail,s as createPromptInjectionGuardrail,c as createRateLimitGuardrail,x as createSemanticCache,y as createSemanticCacheGuardrail,z as createTestEmbedder,d as createToolGuardrail,u as createUntrustedContentGuardrail,C as createVPTreeIndex,n as detectAndRedactPII,m as detectPII,q as detectPromptInjection,t as markUntrustedContent,j as redactPII,r as sanitizeInjection}from'./chunk-TEPEQE42.js';export{b as connectDevTools,a as createDevToolsServer,c as createWsTransport}from'./chunk-BZB3RDI2.js';export{k as createEvalSuite,l as evalAssert,j as evalCoherence,a as evalCost,h as evalFaithfulness,f as evalJudge,b as evalLatency,g as evalMatch,c as evalOutputLength,i as evalRelevance,d as evalSafety,e as evalStructure}from'./chunk-J2Q5KKPN.js';export{b as convertToolsForLLM,a as createMCPAdapter,c as mcpCallTool,e as mcpGetPrompt,d as mcpReadResource,f as mcpSyncResources}from'./chunk-V2FCPNPP.js';export{a as createAgentOrchestrator}from'./chunk-LOHC2KP5.js';export{f as createRunner,c as estimateCost,b as hasPendingApprovals,a as isAgentRunning,d as validateBaseURL}from'./chunk-ZFLHWJ56.js';export{c as createAgentNetwork,e as createDelegator,b as createMessageBus,f as createPubSub,d as createResponder,j as explainGoal,g as getDependencyGraph,a as patternToMermaid,i as planGoal,h as validateGoal}from'./chunk-CXWHLEBQ.js';export{y as InMemoryCheckpointStore,s as MAX_BREAKPOINT_HISTORY,K as ReflectionExhaustedError,N as Semaphore,E as adaptOutputGuardrail,ia as aggregateTokens,_ as allReadyStrategy,la as capabilityRoute,ha as collectOutputs,F as collectTokens,D as combineStreamingGuardrails,ja as composePatterns,fa as concatResults,aa as costEfficientStrategy,t as createBreakpointId,w as createCheckpointId,v as createInitialBreakpointState,B as createLengthStreamingGuardrail,ra as createMultiAgentOrchestrator,C as createPatternStreamingGuardrail,z as createStreamingRunner,A as createToxicityStreamingGuardrail,W as dag,na as debate,pa as derivedConstraint,Q as diffCheckpoints,H as filterStream,ka as findAgentsByCapability,R as forkFromCheckpoint,a as formatSystemMeta,P as getCheckpointProgress,O as getPatternStep,Z as goal,$ as highestImpactStrategy,I as mapStream,u as matchBreakpoint,J as mergeTaggedStreams,T as parallel,ca as patternFromJSON,ba as patternToJSON,ga as pickBestResult,Y as race,X as reflect,ea as runAgentRequirement,oa as runDebate,da as selectAgent,U as sequential,ma as spawnOnCondition,qa as spawnPool,V as supervisor,G as tapStream,b as toAIContext,x as validateCheckpoint,L as withReflection}from'./chunk-7KCLEIAG.js';export{a as GuardrailError,b as isGuardrailError}from'./chunk-UR5BMWEN.js';export{a as createDebugTimeline,b as createDebugTimelinePlugin,c as createHealthMonitor}from'./chunk-FBT73WFY.js';export{a as PredicateFromIntentError,b as predicateFromIntent,c as predicateFromIntentRaw,g as predicateFromIntentWithProvenance,f as predicateToolSpec,e as predicateToolSpecAnthropic,d as predicateToolSpecOpenAI}from'./chunk-GTB6HTZV.js';export{c as StructuredOutputError,a as extractJsonFromOutput,b as withStructuredOutput}from'./chunk-HRR45JZX.js';export{CircuitBreakerOpenError,createCircuitBreaker,createOTLPExporter}from'@directive-run/core/plugins';import G from'path';function Hr(r,...e){let t=r;for(let n of e)t=n(t);return t}function j(r,e){let t=typeof r.content=="string"?r.content:JSON.stringify(r.content);return Math.ceil(t.length/4)}function V(r,e){return r.reduce((t,n)=>t+j(n),0)}function X(r={}){return (e,t={})=>{let n={...r,...t},s=n.maxMessages??100,c=n.preserveRecentCount??5;if(e.length<=s)return {keep:[...e],toSummarize:[],estimatedTokens:V(e)};let o=e.slice(-c),u=e.slice(0,-c),a=Math.max(0,s-c),y=u.slice(-a),p=u.slice(0,-a||void 0),h=[...y,...o];return {keep:h,toSummarize:p.length>0?p:[],estimatedTokens:V(h)}}}function Y(r={}){return (e,t={})=>{let n={...r,...t},s=n.maxTokens??4e3,c=n.preserveRecentCount??5,o=n.countSystemMessages??true,u=e.slice(-c),a=e.slice(0,-c),y=u.reduce((l,g)=>!o&&g.role==="system"?l:l+j(g),0),p=[],h=[],m=y;for(let l=a.length-1;l>=0;l--){let g=a[l],C=!o&&g.role==="system"?0:j(g);if(m+C<=s)p.unshift(g),m+=C;else {h.push(...a.slice(0,l+1));break}}return {keep:[...p,...u],toSummarize:h,estimatedTokens:m}}}function Vr(r={}){let e=X(r),t=Y(r);return (n,s={})=>{let c={...r,...s},o=e(n,c),u=t(n,c);return o.keep.length<=u.keep.length?o:u}}function Kr(r){let{strategy:e,summarizer:t,strategyConfig:n={},autoManage:s=false,onMemoryManaged:c,onManageError:o,maxContextTokens:u}=r,a={messages:[],summaries:[],totalMessagesProcessed:0,estimatedTokens:0},y=false;async function p(){if(y)return {messagesBefore:a.messages.length,messagesAfter:a.messages.length,messagesSummarized:0,estimatedTokensBefore:a.estimatedTokens,estimatedTokensAfter:a.estimatedTokens};y=true;try{let m=a.messages.length,l=a.estimatedTokens,g=e(a.messages,n);if(g.toSummarize.length===0)return {messagesBefore:m,messagesAfter:m,messagesSummarized:0,estimatedTokensBefore:l,estimatedTokensAfter:g.estimatedTokens};let C;t&&g.toSummarize.length>0&&(C=await t(g.toSummarize),a.summaries.push({content:C,messagesCount:g.toSummarize.length,createdAt:Date.now()})),a.messages=g.keep,a.estimatedTokens=g.estimatedTokens;let E={messagesBefore:m,messagesAfter:a.messages.length,messagesSummarized:g.toSummarize.length,summary:C,estimatedTokensBefore:l,estimatedTokensAfter:g.estimatedTokens};return c?.(E),E}finally{y=false;}}function h(){if(y)return;e(a.messages,n).toSummarize.length>0&&p().catch(l=>{let g=l instanceof Error?l:new Error(String(l));o?o(g):console.error("[Directive Memory] Auto-manage error:",g);});}return {getState(){return {...a,messages:[...a.messages],summaries:a.summaries.map(m=>({...m}))}},addMessage(m){a.messages.push(m),a.totalMessagesProcessed++,a.estimatedTokens+=j(m),s&&h();},addMessages(m){for(let l of m)a.messages.push(l),a.totalMessagesProcessed++,a.estimatedTokens+=j(l);s&&h();},getContextMessages(){let m=[];if(a.summaries.length>0){let l=a.summaries.map(g=>g.content).join(`
2
2
 
3
3
  ---
4
4
 
@@ -1,2 +1,2 @@
1
- export{N as Semaphore,ia as aggregateTokens,_ as allReadyStrategy,la as capabilityRoute,ha as collectOutputs,ja as composePatterns,fa as concatResults,aa as costEfficientStrategy,ra as createMultiAgentOrchestrator,W as dag,na as debate,pa as derivedConstraint,Q as diffCheckpoints,ka as findAgentsByCapability,R as forkFromCheckpoint,P as getCheckpointProgress,O as getPatternStep,Z as goal,$ as highestImpactStrategy,T as parallel,ca as patternFromJSON,ba as patternToJSON,ga as pickBestResult,Y as race,X as reflect,ea as runAgentRequirement,oa as runDebate,da as selectAgent,U as sequential,M as shallowEqual,ma as spawnOnCondition,qa as spawnPool,V as supervisor,S as validateDagAcyclic}from'./chunk-G7CRWJT7.js';import'./chunk-UR5BMWEN.js';import'./chunk-FBT73WFY.js';import'./chunk-HRR45JZX.js';//# sourceMappingURL=multi-agent-orchestrator-RMTLPKB4.js.map
2
- //# sourceMappingURL=multi-agent-orchestrator-RMTLPKB4.js.map
1
+ export{N as Semaphore,ia as aggregateTokens,_ as allReadyStrategy,la as capabilityRoute,ha as collectOutputs,ja as composePatterns,fa as concatResults,aa as costEfficientStrategy,ra as createMultiAgentOrchestrator,W as dag,na as debate,pa as derivedConstraint,Q as diffCheckpoints,ka as findAgentsByCapability,R as forkFromCheckpoint,P as getCheckpointProgress,O as getPatternStep,Z as goal,$ as highestImpactStrategy,T as parallel,ca as patternFromJSON,ba as patternToJSON,ga as pickBestResult,Y as race,X as reflect,ea as runAgentRequirement,oa as runDebate,da as selectAgent,U as sequential,M as shallowEqual,ma as spawnOnCondition,qa as spawnPool,V as supervisor,S as validateDagAcyclic}from'./chunk-7KCLEIAG.js';import'./chunk-UR5BMWEN.js';import'./chunk-FBT73WFY.js';import'./chunk-HRR45JZX.js';//# sourceMappingURL=multi-agent-orchestrator-FIF4GLVR.js.map
2
+ //# sourceMappingURL=multi-agent-orchestrator-FIF4GLVR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"multi-agent-orchestrator-RMTLPKB4.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"multi-agent-orchestrator-FIF4GLVR.js"}
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkGWWZXJOG_cjs=require('./chunk-GWWZXJOG.cjs');require('./chunk-K64WKZ22.cjs'),require('./chunk-WOFIBIPW.cjs'),require('./chunk-WCQK3JOR.cjs');Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.N}});Object.defineProperty(exports,"aggregateTokens",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ia}});Object.defineProperty(exports,"allReadyStrategy",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs._}});Object.defineProperty(exports,"capabilityRoute",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.la}});Object.defineProperty(exports,"collectOutputs",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ha}});Object.defineProperty(exports,"composePatterns",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ja}});Object.defineProperty(exports,"concatResults",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.fa}});Object.defineProperty(exports,"costEfficientStrategy",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.aa}});Object.defineProperty(exports,"createMultiAgentOrchestrator",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ra}});Object.defineProperty(exports,"dag",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.W}});Object.defineProperty(exports,"debate",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.na}});Object.defineProperty(exports,"derivedConstraint",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.pa}});Object.defineProperty(exports,"diffCheckpoints",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.Q}});Object.defineProperty(exports,"findAgentsByCapability",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ka}});Object.defineProperty(exports,"forkFromCheckpoint",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.R}});Object.defineProperty(exports,"getCheckpointProgress",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.P}});Object.defineProperty(exports,"getPatternStep",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.O}});Object.defineProperty(exports,"goal",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.Z}});Object.defineProperty(exports,"highestImpactStrategy",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.$}});Object.defineProperty(exports,"parallel",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.T}});Object.defineProperty(exports,"patternFromJSON",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ca}});Object.defineProperty(exports,"patternToJSON",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ba}});Object.defineProperty(exports,"pickBestResult",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ga}});Object.defineProperty(exports,"race",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.Y}});Object.defineProperty(exports,"reflect",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.X}});Object.defineProperty(exports,"runAgentRequirement",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ea}});Object.defineProperty(exports,"runDebate",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.oa}});Object.defineProperty(exports,"selectAgent",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.da}});Object.defineProperty(exports,"sequential",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.U}});Object.defineProperty(exports,"shallowEqual",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.M}});Object.defineProperty(exports,"spawnOnCondition",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ma}});Object.defineProperty(exports,"spawnPool",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.qa}});Object.defineProperty(exports,"supervisor",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.V}});Object.defineProperty(exports,"validateDagAcyclic",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.S}});//# sourceMappingURL=multi-agent-orchestrator-PHDHFCW3.cjs.map
2
+ //# sourceMappingURL=multi-agent-orchestrator-PHDHFCW3.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"multi-agent-orchestrator-OX2TKD5Y.cjs"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"multi-agent-orchestrator-PHDHFCW3.cjs"}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkXGHNOSXT_cjs=require('./chunk-XGHNOSXT.cjs'),chunk7EJN6TYX_cjs=require('./chunk-7EJN6TYX.cjs');require('./chunk-K64WKZ22.cjs'),require('./chunk-WOFIBIPW.cjs'),require('./chunk-WCQK3JOR.cjs');Object.defineProperty(exports,"createAgentNetwork",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.c}});Object.defineProperty(exports,"createDelegator",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.e}});Object.defineProperty(exports,"createMessageBus",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.b}});Object.defineProperty(exports,"createPubSub",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.f}});Object.defineProperty(exports,"createResponder",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.d}});Object.defineProperty(exports,"explainGoal",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.j}});Object.defineProperty(exports,"getDependencyGraph",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.g}});Object.defineProperty(exports,"patternToMermaid",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.a}});Object.defineProperty(exports,"planGoal",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.i}});Object.defineProperty(exports,"validateGoal",{enumerable:true,get:function(){return chunkXGHNOSXT_cjs.h}});Object.defineProperty(exports,"InMemoryCheckpointStore",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.y}});Object.defineProperty(exports,"MAX_BREAKPOINT_HISTORY",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.s}});Object.defineProperty(exports,"ReflectionExhaustedError",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.K}});Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.N}});Object.defineProperty(exports,"aggregateTokens",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ia}});Object.defineProperty(exports,"allReadyStrategy",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs._}});Object.defineProperty(exports,"capabilityRoute",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.la}});Object.defineProperty(exports,"collectOutputs",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ha}});Object.defineProperty(exports,"composePatterns",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ja}});Object.defineProperty(exports,"concatResults",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.fa}});Object.defineProperty(exports,"costEfficientStrategy",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.aa}});Object.defineProperty(exports,"createBreakpointId",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.t}});Object.defineProperty(exports,"createCheckpointId",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.w}});Object.defineProperty(exports,"createInitialBreakpointState",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.v}});Object.defineProperty(exports,"createMultiAgentOrchestrator",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ra}});Object.defineProperty(exports,"dag",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.W}});Object.defineProperty(exports,"debate",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.na}});Object.defineProperty(exports,"derivedConstraint",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.pa}});Object.defineProperty(exports,"diffCheckpoints",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.Q}});Object.defineProperty(exports,"findAgentsByCapability",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ka}});Object.defineProperty(exports,"forkFromCheckpoint",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.R}});Object.defineProperty(exports,"getCheckpointProgress",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.P}});Object.defineProperty(exports,"getPatternStep",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.O}});Object.defineProperty(exports,"goal",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.Z}});Object.defineProperty(exports,"highestImpactStrategy",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.$}});Object.defineProperty(exports,"matchBreakpoint",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.u}});Object.defineProperty(exports,"parallel",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.T}});Object.defineProperty(exports,"patternFromJSON",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ca}});Object.defineProperty(exports,"patternToJSON",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ba}});Object.defineProperty(exports,"pickBestResult",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ga}});Object.defineProperty(exports,"race",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.Y}});Object.defineProperty(exports,"reflect",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.X}});Object.defineProperty(exports,"runAgentRequirement",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ea}});Object.defineProperty(exports,"runDebate",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.oa}});Object.defineProperty(exports,"selectAgent",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.da}});Object.defineProperty(exports,"sequential",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.U}});Object.defineProperty(exports,"spawnOnCondition",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.ma}});Object.defineProperty(exports,"spawnPool",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.qa}});Object.defineProperty(exports,"supervisor",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.V}});Object.defineProperty(exports,"validateCheckpoint",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.x}});Object.defineProperty(exports,"withReflection",{enumerable:true,get:function(){return chunk7EJN6TYX_cjs.L}});//# sourceMappingURL=multi-agent.cjs.map
1
+ 'use strict';var chunkPEM2LPOC_cjs=require('./chunk-PEM2LPOC.cjs'),chunkGWWZXJOG_cjs=require('./chunk-GWWZXJOG.cjs');require('./chunk-K64WKZ22.cjs'),require('./chunk-WOFIBIPW.cjs'),require('./chunk-WCQK3JOR.cjs');Object.defineProperty(exports,"createAgentNetwork",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.c}});Object.defineProperty(exports,"createDelegator",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.e}});Object.defineProperty(exports,"createMessageBus",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.b}});Object.defineProperty(exports,"createPubSub",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.f}});Object.defineProperty(exports,"createResponder",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.d}});Object.defineProperty(exports,"explainGoal",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.j}});Object.defineProperty(exports,"getDependencyGraph",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.g}});Object.defineProperty(exports,"patternToMermaid",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.a}});Object.defineProperty(exports,"planGoal",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.i}});Object.defineProperty(exports,"validateGoal",{enumerable:true,get:function(){return chunkPEM2LPOC_cjs.h}});Object.defineProperty(exports,"InMemoryCheckpointStore",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.y}});Object.defineProperty(exports,"MAX_BREAKPOINT_HISTORY",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.s}});Object.defineProperty(exports,"ReflectionExhaustedError",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.K}});Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.N}});Object.defineProperty(exports,"aggregateTokens",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ia}});Object.defineProperty(exports,"allReadyStrategy",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs._}});Object.defineProperty(exports,"capabilityRoute",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.la}});Object.defineProperty(exports,"collectOutputs",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ha}});Object.defineProperty(exports,"composePatterns",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ja}});Object.defineProperty(exports,"concatResults",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.fa}});Object.defineProperty(exports,"costEfficientStrategy",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.aa}});Object.defineProperty(exports,"createBreakpointId",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.t}});Object.defineProperty(exports,"createCheckpointId",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.w}});Object.defineProperty(exports,"createInitialBreakpointState",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.v}});Object.defineProperty(exports,"createMultiAgentOrchestrator",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ra}});Object.defineProperty(exports,"dag",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.W}});Object.defineProperty(exports,"debate",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.na}});Object.defineProperty(exports,"derivedConstraint",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.pa}});Object.defineProperty(exports,"diffCheckpoints",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.Q}});Object.defineProperty(exports,"findAgentsByCapability",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ka}});Object.defineProperty(exports,"forkFromCheckpoint",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.R}});Object.defineProperty(exports,"getCheckpointProgress",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.P}});Object.defineProperty(exports,"getPatternStep",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.O}});Object.defineProperty(exports,"goal",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.Z}});Object.defineProperty(exports,"highestImpactStrategy",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.$}});Object.defineProperty(exports,"matchBreakpoint",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.u}});Object.defineProperty(exports,"parallel",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.T}});Object.defineProperty(exports,"patternFromJSON",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ca}});Object.defineProperty(exports,"patternToJSON",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ba}});Object.defineProperty(exports,"pickBestResult",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ga}});Object.defineProperty(exports,"race",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.Y}});Object.defineProperty(exports,"reflect",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.X}});Object.defineProperty(exports,"runAgentRequirement",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ea}});Object.defineProperty(exports,"runDebate",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.oa}});Object.defineProperty(exports,"selectAgent",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.da}});Object.defineProperty(exports,"sequential",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.U}});Object.defineProperty(exports,"spawnOnCondition",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.ma}});Object.defineProperty(exports,"spawnPool",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.qa}});Object.defineProperty(exports,"supervisor",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.V}});Object.defineProperty(exports,"validateCheckpoint",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.x}});Object.defineProperty(exports,"withReflection",{enumerable:true,get:function(){return chunkGWWZXJOG_cjs.L}});//# sourceMappingURL=multi-agent.cjs.map
2
2
  //# sourceMappingURL=multi-agent.cjs.map
@@ -1,2 +1,2 @@
1
- export{c as createAgentNetwork,e as createDelegator,b as createMessageBus,f as createPubSub,d as createResponder,j as explainGoal,g as getDependencyGraph,a as patternToMermaid,i as planGoal,h as validateGoal}from'./chunk-RHJAMXLS.js';export{y as InMemoryCheckpointStore,s as MAX_BREAKPOINT_HISTORY,K as ReflectionExhaustedError,N as Semaphore,ia as aggregateTokens,_ as allReadyStrategy,la as capabilityRoute,ha as collectOutputs,ja as composePatterns,fa as concatResults,aa as costEfficientStrategy,t as createBreakpointId,w as createCheckpointId,v as createInitialBreakpointState,ra as createMultiAgentOrchestrator,W as dag,na as debate,pa as derivedConstraint,Q as diffCheckpoints,ka as findAgentsByCapability,R as forkFromCheckpoint,P as getCheckpointProgress,O as getPatternStep,Z as goal,$ as highestImpactStrategy,u as matchBreakpoint,T as parallel,ca as patternFromJSON,ba as patternToJSON,ga as pickBestResult,Y as race,X as reflect,ea as runAgentRequirement,oa as runDebate,da as selectAgent,U as sequential,ma as spawnOnCondition,qa as spawnPool,V as supervisor,x as validateCheckpoint,L as withReflection}from'./chunk-G7CRWJT7.js';import'./chunk-UR5BMWEN.js';import'./chunk-FBT73WFY.js';import'./chunk-HRR45JZX.js';//# sourceMappingURL=multi-agent.js.map
1
+ export{c as createAgentNetwork,e as createDelegator,b as createMessageBus,f as createPubSub,d as createResponder,j as explainGoal,g as getDependencyGraph,a as patternToMermaid,i as planGoal,h as validateGoal}from'./chunk-CXWHLEBQ.js';export{y as InMemoryCheckpointStore,s as MAX_BREAKPOINT_HISTORY,K as ReflectionExhaustedError,N as Semaphore,ia as aggregateTokens,_ as allReadyStrategy,la as capabilityRoute,ha as collectOutputs,ja as composePatterns,fa as concatResults,aa as costEfficientStrategy,t as createBreakpointId,w as createCheckpointId,v as createInitialBreakpointState,ra as createMultiAgentOrchestrator,W as dag,na as debate,pa as derivedConstraint,Q as diffCheckpoints,ka as findAgentsByCapability,R as forkFromCheckpoint,P as getCheckpointProgress,O as getPatternStep,Z as goal,$ as highestImpactStrategy,u as matchBreakpoint,T as parallel,ca as patternFromJSON,ba as patternToJSON,ga as pickBestResult,Y as race,X as reflect,ea as runAgentRequirement,oa as runDebate,da as selectAgent,U as sequential,ma as spawnOnCondition,qa as spawnPool,V as supervisor,x as validateCheckpoint,L as withReflection}from'./chunk-7KCLEIAG.js';import'./chunk-UR5BMWEN.js';import'./chunk-FBT73WFY.js';import'./chunk-HRR45JZX.js';//# sourceMappingURL=multi-agent.js.map
2
2
  //# sourceMappingURL=multi-agent.js.map
package/dist/testing.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkTH2D22JP_cjs=require('./chunk-TH2D22JP.cjs'),chunk7EJN6TYX_cjs=require('./chunk-7EJN6TYX.cjs');require('./chunk-K64WKZ22.cjs');var chunkWOFIBIPW_cjs=require('./chunk-WOFIBIPW.cjs');require('./chunk-WCQK3JOR.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=chunkTH2D22JP_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=chunk7EJN6TYX_cjs.ra({...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 chunk7EJN6TYX_cjs.W(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=chunkWOFIBIPW_cjs.a({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 chunk7EJN6TYX_cjs.y({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 chunkESJQSOKJ_cjs=require('./chunk-ESJQSOKJ.cjs'),chunkGWWZXJOG_cjs=require('./chunk-GWWZXJOG.cjs');require('./chunk-K64WKZ22.cjs');var chunkWOFIBIPW_cjs=require('./chunk-WOFIBIPW.cjs');require('./chunk-WCQK3JOR.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=chunkESJQSOKJ_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=chunkGWWZXJOG_cjs.ra({...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 chunkGWWZXJOG_cjs.W(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=chunkWOFIBIPW_cjs.a({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 chunkGWWZXJOG_cjs.y({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