@directive-run/ai 1.14.0 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-DN5NAJM6.js → chunk-56LYSE63.js} +6 -6
- package/dist/chunk-56LYSE63.js.map +1 -0
- package/dist/{chunk-A22KLB23.cjs → chunk-7DPTXZZI.cjs} +22 -22
- package/dist/chunk-7DPTXZZI.cjs.map +1 -0
- package/dist/{chunk-QRXWLD6H.js → chunk-BFSRYCOS.js} +2 -2
- package/dist/{chunk-QRXWLD6H.js.map → chunk-BFSRYCOS.js.map} +1 -1
- package/dist/{chunk-LKY4K5TV.cjs → chunk-C6MQ4WL6.cjs} +2 -2
- package/dist/{chunk-LKY4K5TV.cjs.map → chunk-C6MQ4WL6.cjs.map} +1 -1
- package/dist/{chunk-A5K77UDX.cjs → chunk-CAA6Q4YY.cjs} +2 -2
- package/dist/{chunk-A5K77UDX.cjs.map → chunk-CAA6Q4YY.cjs.map} +1 -1
- package/dist/chunk-D5APTMCT.cjs +16 -0
- package/dist/chunk-D5APTMCT.cjs.map +1 -0
- package/dist/{chunk-LXUMJKGJ.js → chunk-FN4GUZAI.js} +22 -22
- package/dist/chunk-FN4GUZAI.js.map +1 -0
- package/dist/{chunk-POBEEJR6.js → chunk-GTB6HTZV.js} +7 -7
- package/dist/chunk-GTB6HTZV.js.map +1 -0
- package/dist/{chunk-UR4ZGO7V.js → chunk-HRR45JZX.js} +4 -4
- package/dist/chunk-HRR45JZX.js.map +1 -0
- package/dist/{chunk-PD772MSE.cjs → chunk-MDXDPECP.cjs} +7 -7
- package/dist/chunk-MDXDPECP.cjs.map +1 -0
- package/dist/{chunk-FABDFT74.cjs → chunk-PB276BX2.cjs} +6 -6
- package/dist/chunk-PB276BX2.cjs.map +1 -0
- package/dist/{chunk-NNAQ4ZH2.js → chunk-V2FCPNPP.js} +2 -2
- package/dist/{chunk-NNAQ4ZH2.js.map → chunk-V2FCPNPP.js.map} +1 -1
- package/dist/{chunk-FFRWQNK7.cjs → chunk-WCQK3JOR.cjs} +4 -4
- package/dist/chunk-WCQK3JOR.cjs.map +1 -0
- package/dist/{chunk-IUGSMTBE.js → chunk-YT4QN3KO.js} +8 -8
- package/dist/chunk-YT4QN3KO.js.map +1 -0
- package/dist/gemini.cjs +1 -1
- package/dist/gemini.cjs.map +1 -1
- package/dist/gemini.js +1 -1
- package/dist/gemini.js.map +1 -1
- package/dist/guardrails.cjs +1 -1
- package/dist/guardrails.js +1 -1
- package/dist/index.cjs +5 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +1 -1
- package/dist/mcp.js +1 -1
- package/dist/multi-agent-orchestrator-KFYIDKTF.cjs +2 -0
- package/dist/{multi-agent-orchestrator-Y5U4JCFO.cjs.map → multi-agent-orchestrator-KFYIDKTF.cjs.map} +1 -1
- package/dist/{multi-agent-orchestrator-QWWQKKGX.js → multi-agent-orchestrator-ZHSMWIKP.js} +2 -2
- package/dist/{multi-agent-orchestrator-QWWQKKGX.js.map → multi-agent-orchestrator-ZHSMWIKP.js.map} +1 -1
- package/dist/multi-agent.cjs +1 -1
- package/dist/multi-agent.d.cts +2 -2
- package/dist/multi-agent.d.ts +2 -2
- package/dist/multi-agent.js +1 -1
- package/dist/openai.cjs +1 -1
- package/dist/openai.cjs.map +1 -1
- package/dist/openai.js +1 -1
- package/dist/openai.js.map +1 -1
- package/dist/{orchestrator-types-DeIMRLR7.d.cts → orchestrator-types-CbNE7Rjp.d.cts} +1 -1
- package/dist/{orchestrator-types-DGBhL6mc.d.ts → orchestrator-types-ZK9lv5Sm.d.ts} +1 -1
- package/dist/predicate.cjs +1 -1
- package/dist/predicate.js +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-2TD4ZSGZ.cjs +0 -16
- package/dist/chunk-2TD4ZSGZ.cjs.map +0 -1
- package/dist/chunk-A22KLB23.cjs.map +0 -1
- package/dist/chunk-DN5NAJM6.js.map +0 -1
- package/dist/chunk-FABDFT74.cjs.map +0 -1
- package/dist/chunk-FFRWQNK7.cjs.map +0 -1
- package/dist/chunk-IUGSMTBE.js.map +0 -1
- package/dist/chunk-LXUMJKGJ.js.map +0 -1
- package/dist/chunk-PD772MSE.cjs.map +0 -1
- package/dist/chunk-POBEEJR6.js.map +0 -1
- package/dist/chunk-UR4ZGO7V.js.map +0 -1
- package/dist/multi-agent-orchestrator-Y5U4JCFO.cjs +0 -2
package/dist/mcp.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkC6MQ4WL6_cjs=require('./chunk-C6MQ4WL6.cjs');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}});//# sourceMappingURL=mcp.cjs.map
|
|
2
2
|
//# sourceMappingURL=mcp.cjs.map
|
package/dist/mcp.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as convertToolsForLLM,a as createMCPAdapter,c as mcpCallTool,e as mcpGetPrompt,d as mcpReadResource,f as mcpSyncResources}from'./chunk-
|
|
1
|
+
export{b as convertToolsForLLM,a as createMCPAdapter,c as mcpCallTool,e as mcpGetPrompt,d as mcpReadResource,f as mcpSyncResources}from'./chunk-V2FCPNPP.js';//# sourceMappingURL=mcp.js.map
|
|
2
2
|
//# sourceMappingURL=mcp.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunk7DPTXZZI_cjs=require('./chunk-7DPTXZZI.cjs');require('./chunk-K64WKZ22.cjs'),require('./chunk-WOFIBIPW.cjs'),require('./chunk-WCQK3JOR.cjs');Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.N}});Object.defineProperty(exports,"aggregateTokens",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ia}});Object.defineProperty(exports,"allReadyStrategy",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs._}});Object.defineProperty(exports,"capabilityRoute",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.la}});Object.defineProperty(exports,"collectOutputs",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ha}});Object.defineProperty(exports,"composePatterns",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ja}});Object.defineProperty(exports,"concatResults",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.fa}});Object.defineProperty(exports,"costEfficientStrategy",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.aa}});Object.defineProperty(exports,"createMultiAgentOrchestrator",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ra}});Object.defineProperty(exports,"dag",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.W}});Object.defineProperty(exports,"debate",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.na}});Object.defineProperty(exports,"derivedConstraint",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.pa}});Object.defineProperty(exports,"diffCheckpoints",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.Q}});Object.defineProperty(exports,"findAgentsByCapability",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ka}});Object.defineProperty(exports,"forkFromCheckpoint",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.R}});Object.defineProperty(exports,"getCheckpointProgress",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.P}});Object.defineProperty(exports,"getPatternStep",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.O}});Object.defineProperty(exports,"goal",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.Z}});Object.defineProperty(exports,"highestImpactStrategy",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.$}});Object.defineProperty(exports,"parallel",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.T}});Object.defineProperty(exports,"patternFromJSON",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ca}});Object.defineProperty(exports,"patternToJSON",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ba}});Object.defineProperty(exports,"pickBestResult",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ga}});Object.defineProperty(exports,"race",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.Y}});Object.defineProperty(exports,"reflect",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.X}});Object.defineProperty(exports,"runAgentRequirement",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ea}});Object.defineProperty(exports,"runDebate",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.oa}});Object.defineProperty(exports,"selectAgent",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.da}});Object.defineProperty(exports,"sequential",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.U}});Object.defineProperty(exports,"shallowEqual",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.M}});Object.defineProperty(exports,"spawnOnCondition",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ma}});Object.defineProperty(exports,"spawnPool",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.qa}});Object.defineProperty(exports,"supervisor",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.V}});Object.defineProperty(exports,"validateDagAcyclic",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.S}});//# sourceMappingURL=multi-agent-orchestrator-KFYIDKTF.cjs.map
|
|
2
|
+
//# sourceMappingURL=multi-agent-orchestrator-KFYIDKTF.cjs.map
|
package/dist/{multi-agent-orchestrator-Y5U4JCFO.cjs.map → multi-agent-orchestrator-KFYIDKTF.cjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"multi-agent-orchestrator-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"multi-agent-orchestrator-KFYIDKTF.cjs"}
|
|
@@ -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-
|
|
2
|
-
//# sourceMappingURL=multi-agent-orchestrator-
|
|
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-FN4GUZAI.js';import'./chunk-UR5BMWEN.js';import'./chunk-FBT73WFY.js';import'./chunk-HRR45JZX.js';//# sourceMappingURL=multi-agent-orchestrator-ZHSMWIKP.js.map
|
|
2
|
+
//# sourceMappingURL=multi-agent-orchestrator-ZHSMWIKP.js.map
|
package/dist/{multi-agent-orchestrator-QWWQKKGX.js.map → multi-agent-orchestrator-ZHSMWIKP.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"multi-agent-orchestrator-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"multi-agent-orchestrator-ZHSMWIKP.js"}
|
package/dist/multi-agent.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkPB276BX2_cjs=require('./chunk-PB276BX2.cjs'),chunk7DPTXZZI_cjs=require('./chunk-7DPTXZZI.cjs');require('./chunk-K64WKZ22.cjs'),require('./chunk-WOFIBIPW.cjs'),require('./chunk-WCQK3JOR.cjs');Object.defineProperty(exports,"createAgentNetwork",{enumerable:true,get:function(){return chunkPB276BX2_cjs.c}});Object.defineProperty(exports,"createDelegator",{enumerable:true,get:function(){return chunkPB276BX2_cjs.e}});Object.defineProperty(exports,"createMessageBus",{enumerable:true,get:function(){return chunkPB276BX2_cjs.b}});Object.defineProperty(exports,"createPubSub",{enumerable:true,get:function(){return chunkPB276BX2_cjs.f}});Object.defineProperty(exports,"createResponder",{enumerable:true,get:function(){return chunkPB276BX2_cjs.d}});Object.defineProperty(exports,"explainGoal",{enumerable:true,get:function(){return chunkPB276BX2_cjs.j}});Object.defineProperty(exports,"getDependencyGraph",{enumerable:true,get:function(){return chunkPB276BX2_cjs.g}});Object.defineProperty(exports,"patternToMermaid",{enumerable:true,get:function(){return chunkPB276BX2_cjs.a}});Object.defineProperty(exports,"planGoal",{enumerable:true,get:function(){return chunkPB276BX2_cjs.i}});Object.defineProperty(exports,"validateGoal",{enumerable:true,get:function(){return chunkPB276BX2_cjs.h}});Object.defineProperty(exports,"InMemoryCheckpointStore",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.y}});Object.defineProperty(exports,"MAX_BREAKPOINT_HISTORY",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.s}});Object.defineProperty(exports,"ReflectionExhaustedError",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.K}});Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.N}});Object.defineProperty(exports,"aggregateTokens",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ia}});Object.defineProperty(exports,"allReadyStrategy",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs._}});Object.defineProperty(exports,"capabilityRoute",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.la}});Object.defineProperty(exports,"collectOutputs",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ha}});Object.defineProperty(exports,"composePatterns",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ja}});Object.defineProperty(exports,"concatResults",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.fa}});Object.defineProperty(exports,"costEfficientStrategy",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.aa}});Object.defineProperty(exports,"createBreakpointId",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.t}});Object.defineProperty(exports,"createCheckpointId",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.w}});Object.defineProperty(exports,"createInitialBreakpointState",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.v}});Object.defineProperty(exports,"createMultiAgentOrchestrator",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ra}});Object.defineProperty(exports,"dag",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.W}});Object.defineProperty(exports,"debate",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.na}});Object.defineProperty(exports,"derivedConstraint",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.pa}});Object.defineProperty(exports,"diffCheckpoints",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.Q}});Object.defineProperty(exports,"findAgentsByCapability",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ka}});Object.defineProperty(exports,"forkFromCheckpoint",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.R}});Object.defineProperty(exports,"getCheckpointProgress",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.P}});Object.defineProperty(exports,"getPatternStep",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.O}});Object.defineProperty(exports,"goal",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.Z}});Object.defineProperty(exports,"highestImpactStrategy",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.$}});Object.defineProperty(exports,"matchBreakpoint",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.u}});Object.defineProperty(exports,"parallel",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.T}});Object.defineProperty(exports,"patternFromJSON",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ca}});Object.defineProperty(exports,"patternToJSON",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ba}});Object.defineProperty(exports,"pickBestResult",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ga}});Object.defineProperty(exports,"race",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.Y}});Object.defineProperty(exports,"reflect",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.X}});Object.defineProperty(exports,"runAgentRequirement",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ea}});Object.defineProperty(exports,"runDebate",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.oa}});Object.defineProperty(exports,"selectAgent",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.da}});Object.defineProperty(exports,"sequential",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.U}});Object.defineProperty(exports,"spawnOnCondition",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.ma}});Object.defineProperty(exports,"spawnPool",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.qa}});Object.defineProperty(exports,"supervisor",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.V}});Object.defineProperty(exports,"validateCheckpoint",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.x}});Object.defineProperty(exports,"withReflection",{enumerable:true,get:function(){return chunk7DPTXZZI_cjs.L}});//# sourceMappingURL=multi-agent.cjs.map
|
|
2
2
|
//# sourceMappingURL=multi-agent.cjs.map
|
package/dist/multi-agent.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as MultiAgentOrchestratorOptions, M as MultiAgentOrchestrator, P as ParallelPattern, y as RacePattern, L as ReflectionEvaluation, F as ReflectIterationRecord, I as ReflectPattern, W as SequentialPattern, a3 as SupervisorPattern, i as ExecutionPattern, D as DebatePattern, f as AgentRegistry, Q as RunAgentRequirement, g as DebateResult } from './orchestrator-types-
|
|
2
|
-
export { e as AgentRegistration, H as HandoffRequest, j as HandoffResult, s as MultiAgentRunCallOptions, t as MultiAgentState, z as RaceResult, C as RaceSuccessEntry, J as ReflectionConfig, K as ReflectionContext, R as ReflectionEvaluator, N as ReflectionExhaustedError, a4 as TaskContext, T as TaskRegistration, as as withReflection } from './orchestrator-types-
|
|
1
|
+
import { a as MultiAgentOrchestratorOptions, M as MultiAgentOrchestrator, P as ParallelPattern, y as RacePattern, L as ReflectionEvaluation, F as ReflectIterationRecord, I as ReflectPattern, W as SequentialPattern, a3 as SupervisorPattern, i as ExecutionPattern, D as DebatePattern, f as AgentRegistry, Q as RunAgentRequirement, g as DebateResult } from './orchestrator-types-CbNE7Rjp.cjs';
|
|
2
|
+
export { e as AgentRegistration, H as HandoffRequest, j as HandoffResult, s as MultiAgentRunCallOptions, t as MultiAgentState, z as RaceResult, C as RaceSuccessEntry, J as ReflectionConfig, K as ReflectionContext, R as ReflectionEvaluator, N as ReflectionExhaustedError, a4 as TaskContext, T as TaskRegistration, as as withReflection } from './orchestrator-types-CbNE7Rjp.cjs';
|
|
3
3
|
import { aG as PatternCheckpointState, ah as CheckpointDiff, h as CheckpointStore, aj as CheckpointProgress, J as AgentSelectionStrategy, j as DagNode, D as DagExecutionContext, k as DagPattern, F as GoalNode, K as RelaxationTier, at as GoalMetrics, P as PatternCheckpointConfig, E as GoalPattern, q as RunResult, s as OrchestratorConstraint, L as GoalResult } from './types-DJ09LjZX.cjs';
|
|
4
4
|
export { z as BreakpointConfig, ab as BreakpointContext, B as BreakpointModifications, d as BreakpointRequest, ae as BreakpointState, af as BreakpointType, C as Checkpoint, ai as CheckpointLocalState, au as GoalStepMetrics, i as InMemoryCheckpointStore, aB as InMemoryCheckpointStoreOptions, aC as MAX_BREAKPOINT_HISTORY, $ as MultiAgentBreakpointType, aD as MultiAgentCheckpointLocalState, aO as RelaxationContext, aP as RelaxationRecord, aQ as RelaxationStrategy, aY as SingleAgentCheckpointLocalState, b2 as createBreakpointId, b3 as createCheckpointId, b4 as createInitialBreakpointState, b6 as matchBreakpoint, b7 as validateCheckpoint } from './types-DJ09LjZX.cjs';
|
|
5
5
|
import '@directive-run/core';
|
package/dist/multi-agent.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as MultiAgentOrchestratorOptions, M as MultiAgentOrchestrator, P as ParallelPattern, y as RacePattern, L as ReflectionEvaluation, F as ReflectIterationRecord, I as ReflectPattern, W as SequentialPattern, a3 as SupervisorPattern, i as ExecutionPattern, D as DebatePattern, f as AgentRegistry, Q as RunAgentRequirement, g as DebateResult } from './orchestrator-types-
|
|
2
|
-
export { e as AgentRegistration, H as HandoffRequest, j as HandoffResult, s as MultiAgentRunCallOptions, t as MultiAgentState, z as RaceResult, C as RaceSuccessEntry, J as ReflectionConfig, K as ReflectionContext, R as ReflectionEvaluator, N as ReflectionExhaustedError, a4 as TaskContext, T as TaskRegistration, as as withReflection } from './orchestrator-types-
|
|
1
|
+
import { a as MultiAgentOrchestratorOptions, M as MultiAgentOrchestrator, P as ParallelPattern, y as RacePattern, L as ReflectionEvaluation, F as ReflectIterationRecord, I as ReflectPattern, W as SequentialPattern, a3 as SupervisorPattern, i as ExecutionPattern, D as DebatePattern, f as AgentRegistry, Q as RunAgentRequirement, g as DebateResult } from './orchestrator-types-ZK9lv5Sm.js';
|
|
2
|
+
export { e as AgentRegistration, H as HandoffRequest, j as HandoffResult, s as MultiAgentRunCallOptions, t as MultiAgentState, z as RaceResult, C as RaceSuccessEntry, J as ReflectionConfig, K as ReflectionContext, R as ReflectionEvaluator, N as ReflectionExhaustedError, a4 as TaskContext, T as TaskRegistration, as as withReflection } from './orchestrator-types-ZK9lv5Sm.js';
|
|
3
3
|
import { aG as PatternCheckpointState, ah as CheckpointDiff, h as CheckpointStore, aj as CheckpointProgress, J as AgentSelectionStrategy, j as DagNode, D as DagExecutionContext, k as DagPattern, F as GoalNode, K as RelaxationTier, at as GoalMetrics, P as PatternCheckpointConfig, E as GoalPattern, q as RunResult, s as OrchestratorConstraint, L as GoalResult } from './types-DJ09LjZX.js';
|
|
4
4
|
export { z as BreakpointConfig, ab as BreakpointContext, B as BreakpointModifications, d as BreakpointRequest, ae as BreakpointState, af as BreakpointType, C as Checkpoint, ai as CheckpointLocalState, au as GoalStepMetrics, i as InMemoryCheckpointStore, aB as InMemoryCheckpointStoreOptions, aC as MAX_BREAKPOINT_HISTORY, $ as MultiAgentBreakpointType, aD as MultiAgentCheckpointLocalState, aO as RelaxationContext, aP as RelaxationRecord, aQ as RelaxationStrategy, aY as SingleAgentCheckpointLocalState, b2 as createBreakpointId, b3 as createCheckpointId, b4 as createInitialBreakpointState, b6 as matchBreakpoint, b7 as validateCheckpoint } from './types-DJ09LjZX.js';
|
|
5
5
|
import '@directive-run/core';
|
package/dist/multi-agent.js
CHANGED
|
@@ -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-
|
|
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-56LYSE63.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-FN4GUZAI.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/openai.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var chunkKP3G32S7_cjs=require('./chunk-KP3G32S7.cjs'),chunk3WO4MWJM_cjs=require('./chunk-3WO4MWJM.cjs');var L={"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"o4-mini":{input:1.1,output:4.4},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4}};function B(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i,hooks:c,temperature:n,topP:l,stop:a,responseFormat:p}=g;chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIRunner");let o=p==="json"?{type:"json_object"}:p??void 0;return chunk3WO4MWJM_cjs.f({fetch:b,hooks:c,buildRequest:(t,u,d)=>({url:`${r}/chat/completions`,init:{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:t.model??h,...m!=null?{max_tokens:m}:{},...n!=null?{temperature:n}:{},...l!=null?{top_p:l}:{},...a!=null?{stop:a}:{},...o!=null?{response_format:o}:{},messages:[...t.instructions?[{role:"system",content:t.instructions}]:[],...d.map(e=>({role:e.role,content:e.content}))]}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let u=await t.json(),d=u.choices?.[0]?.message?.content??"",e=u.usage?.prompt_tokens??0,f=u.usage?.completion_tokens??0;return {text:d,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function M(g){let{apiKey:s,model:h="text-embedding-3-small",dimensions:m=1536,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i}=g;return chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIEmbedder"),async c=>{let n=await b(`${r}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:h,input:c,dimensions:m}),signal:AbortSignal.timeout(i??3e4)});if(!n.ok){let p=await n.text().catch(()=>"");throw new Error(`[Directive] OpenAI embedding failed: ${n.status}${p?` \u2013 ${p.slice(0,200)}`:""}`)}let a=(await n.json()).data[0];if(!a)throw new Error("[Directive] OpenAI embedding response contained no data entries");return a.embedding}}function v(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,hooks:i,temperature:c,topP:n,stop:l,responseFormat:a}=g;chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIStreamingRunner");let p=a==="json"?{type:"json_object"}:a??void 0;return async(o,t,u)=>{let d=chunkKP3G32S7_cjs.e(i,o,t);try{let e=await b(`${r}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:o.model??h,...m!=null?{max_tokens:m}:{},...c!=null?{temperature:c}:{},...n!=null?{top_p:n}:{},...l!=null?{stop:l}:{},...p!=null?{response_format:p}:{},messages:[...o.instructions?[{role:"system",content:o.instructions}]:[],{role:"user",content:t}],stream:!0,stream_options:{include_usage:!0}}),signal:u.signal});e.ok||await chunkKP3G32S7_cjs.a(e,"OpenAI");let f=chunkKP3G32S7_cjs.b(e),{fullText:
|
|
1
|
+
'use strict';var chunkKP3G32S7_cjs=require('./chunk-KP3G32S7.cjs'),chunk3WO4MWJM_cjs=require('./chunk-3WO4MWJM.cjs');var L={"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"o4-mini":{input:1.1,output:4.4},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4}};function B(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i,hooks:c,temperature:n,topP:l,stop:a,responseFormat:p}=g;chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIRunner");let o=p==="json"?{type:"json_object"}:p??void 0;return chunk3WO4MWJM_cjs.f({fetch:b,hooks:c,buildRequest:(t,u,d)=>({url:`${r}/chat/completions`,init:{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:t.model??h,...m!=null?{max_tokens:m}:{},...n!=null?{temperature:n}:{},...l!=null?{top_p:l}:{},...a!=null?{stop:a}:{},...o!=null?{response_format:o}:{},messages:[...t.instructions?[{role:"system",content:t.instructions}]:[],...d.map(e=>({role:e.role,content:e.content}))]}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let u=await t.json(),d=u.choices?.[0]?.message?.content??"",e=u.usage?.prompt_tokens??0,f=u.usage?.completion_tokens??0;return {text:d,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function M(g){let{apiKey:s,model:h="text-embedding-3-small",dimensions:m=1536,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i}=g;return chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIEmbedder"),async c=>{let n=await b(`${r}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:h,input:c,dimensions:m}),signal:AbortSignal.timeout(i??3e4)});if(!n.ok){let p=await n.text().catch(()=>"");throw new Error(`[Directive] OpenAI embedding failed: ${n.status}${p?` \u2013 ${p.slice(0,200)}`:""}`)}let a=(await n.json()).data[0];if(!a)throw new Error("[Directive] OpenAI embedding response contained no data entries");return a.embedding}}function v(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,hooks:i,temperature:c,topP:n,stop:l,responseFormat:a}=g;chunk3WO4MWJM_cjs.d(r),chunkKP3G32S7_cjs.c(s,"createOpenAIStreamingRunner");let p=a==="json"?{type:"json_object"}:a??void 0;return async(o,t,u)=>{let d=chunkKP3G32S7_cjs.e(i,o,t);try{let e=await b(`${r}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:o.model??h,...m!=null?{max_tokens:m}:{},...c!=null?{temperature:c}:{},...n!=null?{top_p:n}:{},...l!=null?{stop:l}:{},...p!=null?{response_format:p}:{},messages:[...o.instructions?[{role:"system",content:o.instructions}]:[],{role:"user",content:t}],stream:!0,stream_options:{include_usage:!0}}),signal:u.signal});e.ok||await chunkKP3G32S7_cjs.a(e,"OpenAI");let f=chunkKP3G32S7_cjs.b(e),{fullText:A,inputTokens:O,outputTokens:S}=await chunkKP3G32S7_cjs.d(f,u.onToken,k=>{let y={},w=k.choices?.[0]?.delta;return w?.content&&(y.text=w.content),k.usage&&(y.inputTokens=k.usage.prompt_tokens??0,y.outputTokens=k.usage.completion_tokens??0),y},"OpenAI"),_={inputTokens:O,outputTokens:S},j=O+S;return u.onMessage?.({role:"assistant",content:A}),chunkKP3G32S7_cjs.f(i,o,t,A,j,_,d),chunkKP3G32S7_cjs.h(t,A,j,_)}catch(e){throw chunkKP3G32S7_cjs.g(i,o,t,e,d),e}}}
|
|
2
2
|
exports.OPENAI_PRICING=L;exports.createOpenAIEmbedder=M;exports.createOpenAIRunner=B;exports.createOpenAIStreamingRunner=v;//# sourceMappingURL=openai.cjs.map
|
|
3
3
|
//# sourceMappingURL=openai.cjs.map
|
package/dist/openai.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/openai.ts"],"names":["OPENAI_PRICING","createOpenAIRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stop","responseFormat","validateBaseURL","warnIfMissingApiKey","resolvedResponseFormat","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createOpenAIEmbedder","dimensions","response","errBody","entry","createOpenAIStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","delta","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"qHAkDO,IAAMA,EACX,CACE,SAAA,CAAW,CAAE,KAAA,CAAO,CAAA,CAAG,OAAQ,CAAE,CAAA,CACjC,cAAA,CAAgB,CAAE,MAAO,EAAA,CAAK,MAAA,CAAQ,GAAI,CAA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AAcrB,CAAAA,CAAcC,CAAAA,CAElC,OAAAQ,CAAAA,CAAU,SAAA,GAAY,CAAE,IAAA,CAAM,WAAA,CAAa,OAAA,CAASM,CAAS,CAAC,CAAA,CAC9DO,mBAAAA,CACEtC,EACAS,CAAAA,CACAe,CAAAA,CACAO,EACAM,CAAAA,CACAD,CAAAA,CACAV,CACF,CAAA,CAEOa,oBAAqBf,CAAAA,CAAOO,CAAAA,CAAUM,EAAaD,CAAU,CACtE,OAASI,CAAAA,CAAK,CACZ,MAAAC,mBAAAA,CAAczC,CAAAA,CAAOS,EAAOe,CAAAA,CAAOgB,CAAAA,CAAKd,CAAS,CAAA,CAE3Cc,CACR,CACF,CACF","file":"openai.cjs","sourcesContent":["/**\n * @directive-run/ai/openai\n *\n * OpenAI adapter for Directive AI. Provides runners and embedders\n * for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * @example\n * ```typescript\n * import { createOpenAIRunner, createOpenAIEmbedder } from '@directive-run/ai/openai';\n *\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * ```\n */\n\nimport { createRunner, validateBaseURL } from \"../agent-utils.js\";\nimport type { EmbedderFn, Embedding } from \"../guardrails/semantic-cache.js\";\nimport type { AdapterHooks, AgentRunner } from \"../types.js\";\nimport type { StreamingCallbackRunner } from \"../types.js\";\nimport {\n buildStreamingResult,\n fireAfterCallHook,\n fireBeforeCallHook,\n fireErrorHook,\n getSSEReader,\n parseSSEStream,\n throwStreamingHTTPError,\n warnIfMissingApiKey,\n} from \"./shared.js\";\n\n// ============================================================================\n// Pricing Constants\n// ============================================================================\n\n/**\n * OpenAI model pricing (USD per million tokens).\n *\n * Use with `estimateCost()` for per-call cost tracking:\n * ```typescript\n * import { estimateCost } from '@directive-run/ai';\n * import { OPENAI_PRICING } from '@directive-run/ai/openai';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, OPENAI_PRICING[\"gpt-4o\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, OPENAI_PRICING[\"gpt-4o\"].output);\n * ```\n *\n * **Note:** Pricing changes over time. These values are provided as a convenience\n * and may not reflect the latest rates. Always verify at https://openai.com/pricing\n */\nexport const OPENAI_PRICING: Record<string, { input: number; output: number }> =\n {\n \"gpt-4.1\": { input: 2, output: 8 },\n \"gpt-4.1-mini\": { input: 0.4, output: 1.6 },\n \"gpt-4.1-nano\": { input: 0.1, output: 0.4 },\n \"gpt-4o\": { input: 2.5, output: 10 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6 },\n \"gpt-4-turbo\": { input: 10, output: 30 },\n \"o4-mini\": { input: 1.1, output: 4.4 },\n o3: { input: 10, output: 40 },\n \"o3-mini\": { input: 1.1, output: 4.4 },\n };\n\n// ============================================================================\n// OpenAI Runner\n// ============================================================================\n\n/** Options for createOpenAIRunner */\nexport interface OpenAIRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default undefined */\n timeoutMs?: number;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create an AgentRunner for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * // OpenAI\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n *\n * // Azure OpenAI\n * const azure = createOpenAIRunner({\n * apiKey: process.env.AZURE_KEY!,\n * baseURL: \"https://your-resource.openai.azure.com/v1\",\n * });\n *\n * // Together.ai (OpenAI-compatible)\n * const together = createOpenAIRunner({\n * apiKey: process.env.TOGETHER_KEY!,\n * baseURL: \"https://api.together.xyz/v1\",\n * });\n * ```\n */\nexport function createOpenAIRunner(options: OpenAIRunnerOptions): AgentRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/chat/completions`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n ...messages.map((m) => ({ role: m.role, content: m.content })),\n ],\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n }),\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.choices?.[0]?.message?.content ?? \"\";\n const inputTokens = data.usage?.prompt_tokens ?? 0;\n const outputTokens = data.usage?.completion_tokens ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// OpenAI Embedder\n// ============================================================================\n\n/** Options for createOpenAIEmbedder */\nexport interface OpenAIEmbedderOptions {\n apiKey: string;\n model?: string;\n dimensions?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default 30000 */\n timeoutMs?: number;\n}\n\n/**\n * Create an EmbedderFn that calls the OpenAI embeddings API.\n *\n * @example\n * ```typescript\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedding = await embedder('How do constraints work?');\n * ```\n */\nexport function createOpenAIEmbedder(\n options: OpenAIEmbedderOptions,\n): EmbedderFn {\n const {\n apiKey,\n model = \"text-embedding-3-small\",\n dimensions = 1536,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIEmbedder\");\n\n return async (text: string): Promise<Embedding> => {\n const response = await fetchFn(`${baseURL}/embeddings`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ model, input: text, dimensions }),\n signal: AbortSignal.timeout(timeoutMs ?? 30_000),\n });\n\n if (!response.ok) {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] OpenAI embedding failed: ${response.status}${errBody ? ` – ${errBody.slice(0, 200)}` : \"\"}`,\n );\n }\n\n const data = (await response.json()) as {\n data: Array<{ embedding: number[] }>;\n };\n\n const entry = data.data[0];\n if (!entry) {\n throw new Error(\n \"[Directive] OpenAI embedding response contained no data entries\",\n );\n }\n\n return entry.embedding;\n };\n}\n\n// ============================================================================\n// OpenAI Streaming Runner\n// ============================================================================\n\n/** Options for createOpenAIStreamingRunner */\nexport interface OpenAIStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create a StreamingCallbackRunner for OpenAI-compatible chat completions\n * with server-sent events. Can be used standalone or paired with `createOpenAIRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createOpenAIStreamingRunner({\n * apiKey: process.env.OPENAI_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createOpenAIStreamingRunner(\n options: OpenAIStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIStreamingRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n { role: \"user\", content: input },\n ],\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"OpenAI\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n\n const delta = (event.choices as Array<Record<string, unknown>>)?.[0]\n ?.delta as Record<string, unknown> | undefined;\n if (delta?.content) {\n result.text = delta.content as string;\n }\n\n if (event.usage) {\n result.inputTokens =\n ((event.usage as Record<string, unknown>)\n .prompt_tokens as number) ?? 0;\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .completion_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"OpenAI\",\n );\n\n const tokenUsage = { inputTokens, outputTokens };\n const totalTokens = inputTokens + outputTokens;\n\n callbacks.onMessage?.({ role: \"assistant\", content: fullText });\n fireAfterCallHook(\n hooks,\n agent,\n input,\n fullText,\n totalTokens,\n tokenUsage,\n startTime,\n );\n\n return buildStreamingResult(input, fullText, totalTokens, tokenUsage);\n } catch (err) {\n fireErrorHook(hooks, agent, input, err, startTime);\n\n throw err;\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapters/openai.ts"],"names":["OPENAI_PRICING","createOpenAIRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stop","responseFormat","validateBaseURL","warnIfMissingApiKey","resolvedResponseFormat","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createOpenAIEmbedder","dimensions","response","errBody","entry","createOpenAIStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","delta","tokenUsage","totalTokens","f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B,CAAA,CACjCC,CAAAA,CAAO,aACHD,CAAAA,CAAM,KAAA,CACL,iBAAA,EAAgC,CAAA,CAAA,CAGhCC,CACT,CAAA,CACA,QACF,EAEME,CAAAA,CAAa,CAAE,YAAApB,CAAAA,CAAa,YAAA,CAAAC,CAAa,CAAA,CACzCoB,EAAcrB,CAAAA,CAAcC,CAAAA,CAElC,OAAAQ,CAAAA,CAAU,SAAA,GAAY,CAAE,IAAA,CAAM,WAAA,CAAa,OAAA,CAASM,CAAS,CAAC,CAAA,CAC9DO,mBAAAA,CACEtC,EACAS,CAAAA,CACAe,CAAAA,CACAO,EACAM,CAAAA,CACAD,CAAAA,CACAV,CACF,CAAA,CAEOa,oBAAqBf,CAAAA,CAAOO,CAAAA,CAAUM,EAAaD,CAAU,CACtE,OAASI,CAAAA,CAAK,CACZ,MAAAC,mBAAAA,CAAczC,CAAAA,CAAOS,EAAOe,CAAAA,CAAOgB,CAAAA,CAAKd,CAAS,CAAA,CAE3Cc,CACR,CACF,CACF","file":"openai.cjs","sourcesContent":["/**\n * @directive-run/ai/openai\n *\n * OpenAI adapter for Directive AI. Provides runners and embedders\n * for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * @example\n * ```typescript\n * import { createOpenAIRunner, createOpenAIEmbedder } from '@directive-run/ai/openai';\n *\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * ```\n */\n\nimport { createRunner, validateBaseURL } from \"../agent-utils.js\";\nimport type { EmbedderFn, Embedding } from \"../guardrails/semantic-cache.js\";\nimport type { AdapterHooks, AgentRunner } from \"../types.js\";\nimport type { StreamingCallbackRunner } from \"../types.js\";\nimport {\n buildStreamingResult,\n fireAfterCallHook,\n fireBeforeCallHook,\n fireErrorHook,\n getSSEReader,\n parseSSEStream,\n throwStreamingHTTPError,\n warnIfMissingApiKey,\n} from \"./shared.js\";\n\n// ============================================================================\n// Pricing Constants\n// ============================================================================\n\n/**\n * OpenAI model pricing (USD per million tokens).\n *\n * Use with `estimateCost()` for per-call cost tracking:\n * ```typescript\n * import { estimateCost } from '@directive-run/ai';\n * import { OPENAI_PRICING } from '@directive-run/ai/openai';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, OPENAI_PRICING[\"gpt-4o\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, OPENAI_PRICING[\"gpt-4o\"].output);\n * ```\n *\n * **Note:** Pricing changes over time. These values are provided as a convenience\n * and may not reflect the latest rates. Always verify at https://openai.com/pricing\n */\nexport const OPENAI_PRICING: Record<string, { input: number; output: number }> =\n {\n \"gpt-4.1\": { input: 2, output: 8 },\n \"gpt-4.1-mini\": { input: 0.4, output: 1.6 },\n \"gpt-4.1-nano\": { input: 0.1, output: 0.4 },\n \"gpt-4o\": { input: 2.5, output: 10 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6 },\n \"gpt-4-turbo\": { input: 10, output: 30 },\n \"o4-mini\": { input: 1.1, output: 4.4 },\n o3: { input: 10, output: 40 },\n \"o3-mini\": { input: 1.1, output: 4.4 },\n };\n\n// ============================================================================\n// OpenAI Runner\n// ============================================================================\n\n/** Options for createOpenAIRunner */\nexport interface OpenAIRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default undefined */\n timeoutMs?: number;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create an AgentRunner for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * // OpenAI\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n *\n * // Azure OpenAI\n * const azure = createOpenAIRunner({\n * apiKey: process.env.AZURE_KEY!,\n * baseURL: \"https://your-resource.openai.azure.com/v1\",\n * });\n *\n * // Together.ai (OpenAI-compatible)\n * const together = createOpenAIRunner({\n * apiKey: process.env.TOGETHER_KEY!,\n * baseURL: \"https://api.together.xyz/v1\",\n * });\n * ```\n */\nexport function createOpenAIRunner(options: OpenAIRunnerOptions): AgentRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/chat/completions`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n ...messages.map((m) => ({ role: m.role, content: m.content })),\n ],\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n }),\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.choices?.[0]?.message?.content ?? \"\";\n const inputTokens = data.usage?.prompt_tokens ?? 0;\n const outputTokens = data.usage?.completion_tokens ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// OpenAI Embedder\n// ============================================================================\n\n/** Options for createOpenAIEmbedder */\nexport interface OpenAIEmbedderOptions {\n apiKey: string;\n model?: string;\n dimensions?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default 30000 */\n timeoutMs?: number;\n}\n\n/**\n * Create an EmbedderFn that calls the OpenAI embeddings API.\n *\n * @example\n * ```typescript\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedding = await embedder('How do constraints work?');\n * ```\n */\nexport function createOpenAIEmbedder(\n options: OpenAIEmbedderOptions,\n): EmbedderFn {\n const {\n apiKey,\n model = \"text-embedding-3-small\",\n dimensions = 1536,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIEmbedder\");\n\n return async (text: string): Promise<Embedding> => {\n const response = await fetchFn(`${baseURL}/embeddings`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ model, input: text, dimensions }),\n signal: AbortSignal.timeout(timeoutMs ?? 30_000),\n });\n\n if (!response.ok) {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] OpenAI embedding failed: ${response.status}${errBody ? ` – ${errBody.slice(0, 200)}` : \"\"}`,\n );\n }\n\n const data = (await response.json()) as {\n data: Array<{ embedding: number[] }>;\n };\n\n const entry = data.data[0];\n if (!entry) {\n throw new Error(\n \"[Directive] OpenAI embedding response contained no data entries\",\n );\n }\n\n return entry.embedding;\n };\n}\n\n// ============================================================================\n// OpenAI Streaming Runner\n// ============================================================================\n\n/** Options for createOpenAIStreamingRunner */\nexport interface OpenAIStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create a StreamingCallbackRunner for OpenAI-compatible chat completions\n * with server-sent events. Can be used standalone or paired with `createOpenAIRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createOpenAIStreamingRunner({\n * apiKey: process.env.OPENAI_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createOpenAIStreamingRunner(\n options: OpenAIStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIStreamingRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n { role: \"user\", content: input },\n ],\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"OpenAI\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n\n const delta = (event.choices as Record<string, unknown>[])?.[0]\n ?.delta as Record<string, unknown> | undefined;\n if (delta?.content) {\n result.text = delta.content as string;\n }\n\n if (event.usage) {\n result.inputTokens =\n ((event.usage as Record<string, unknown>)\n .prompt_tokens as number) ?? 0;\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .completion_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"OpenAI\",\n );\n\n const tokenUsage = { inputTokens, outputTokens };\n const totalTokens = inputTokens + outputTokens;\n\n callbacks.onMessage?.({ role: \"assistant\", content: fullText });\n fireAfterCallHook(\n hooks,\n agent,\n input,\n fullText,\n totalTokens,\n tokenUsage,\n startTime,\n );\n\n return buildStreamingResult(input, fullText, totalTokens, tokenUsage);\n } catch (err) {\n fireErrorHook(hooks, agent, input, err, startTime);\n\n throw err;\n }\n };\n}\n"]}
|
package/dist/openai.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {c,e,a,b,d as d$1,f as f$1,h,g}from'./chunk-3PGRBK4E.js';import {d,f}from'./chunk-ZFLHWJ56.js';var L={"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"o4-mini":{input:1.1,output:4.4},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4}};function B(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i,hooks:c$1,temperature:n,topP:l,stop:a,responseFormat:p}=g;d(r),c(s,"createOpenAIRunner");let o=p==="json"?{type:"json_object"}:p??void 0;return f({fetch:b,hooks:c$1,buildRequest:(t,u,d)=>({url:`${r}/chat/completions`,init:{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:t.model??h,...m!=null?{max_tokens:m}:{},...n!=null?{temperature:n}:{},...l!=null?{top_p:l}:{},...a!=null?{stop:a}:{},...o!=null?{response_format:o}:{},messages:[...t.instructions?[{role:"system",content:t.instructions}]:[],...d.map(e=>({role:e.role,content:e.content}))]}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let u=await t.json(),d=u.choices?.[0]?.message?.content??"",e=u.usage?.prompt_tokens??0,f=u.usage?.completion_tokens??0;return {text:d,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function M(g){let{apiKey:s,model:h="text-embedding-3-small",dimensions:m=1536,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i}=g;return d(r),c(s,"createOpenAIEmbedder"),async c=>{let n=await b(`${r}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:h,input:c,dimensions:m}),signal:AbortSignal.timeout(i??3e4)});if(!n.ok){let p=await n.text().catch(()=>"");throw new Error(`[Directive] OpenAI embedding failed: ${n.status}${p?` \u2013 ${p.slice(0,200)}`:""}`)}let a=(await n.json()).data[0];if(!a)throw new Error("[Directive] OpenAI embedding response contained no data entries");return a.embedding}}function v(g$1){let{apiKey:s,model:h$1="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b$1=globalThis.fetch,hooks:i,temperature:c$1,topP:n,stop:l,responseFormat:a$1}=g$1;d(r),c(s,"createOpenAIStreamingRunner");let p=a$1==="json"?{type:"json_object"}:a$1??void 0;return async(o,t,u)=>{let d=e(i,o,t);try{let e=await b$1(`${r}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:o.model??h$1,...m!=null?{max_tokens:m}:{},...c$1!=null?{temperature:c$1}:{},...n!=null?{top_p:n}:{},...l!=null?{stop:l}:{},...p!=null?{response_format:p}:{},messages:[...o.instructions?[{role:"system",content:o.instructions}]:[],{role:"user",content:t}],stream:!0,stream_options:{include_usage:!0}}),signal:u.signal});e.ok||await a(e,"OpenAI");let f=b(e),{fullText:
|
|
1
|
+
import {c,e,a,b,d as d$1,f as f$1,h,g}from'./chunk-3PGRBK4E.js';import {d,f}from'./chunk-ZFLHWJ56.js';var L={"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"o4-mini":{input:1.1,output:4.4},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4}};function B(g){let{apiKey:s,model:h="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i,hooks:c$1,temperature:n,topP:l,stop:a,responseFormat:p}=g;d(r),c(s,"createOpenAIRunner");let o=p==="json"?{type:"json_object"}:p??void 0;return f({fetch:b,hooks:c$1,buildRequest:(t,u,d)=>({url:`${r}/chat/completions`,init:{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:t.model??h,...m!=null?{max_tokens:m}:{},...n!=null?{temperature:n}:{},...l!=null?{top_p:l}:{},...a!=null?{stop:a}:{},...o!=null?{response_format:o}:{},messages:[...t.instructions?[{role:"system",content:t.instructions}]:[],...d.map(e=>({role:e.role,content:e.content}))]}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let u=await t.json(),d=u.choices?.[0]?.message?.content??"",e=u.usage?.prompt_tokens??0,f=u.usage?.completion_tokens??0;return {text:d,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function M(g){let{apiKey:s,model:h="text-embedding-3-small",dimensions:m=1536,baseURL:r="https://api.openai.com/v1",fetch:b=globalThis.fetch,timeoutMs:i}=g;return d(r),c(s,"createOpenAIEmbedder"),async c=>{let n=await b(`${r}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:h,input:c,dimensions:m}),signal:AbortSignal.timeout(i??3e4)});if(!n.ok){let p=await n.text().catch(()=>"");throw new Error(`[Directive] OpenAI embedding failed: ${n.status}${p?` \u2013 ${p.slice(0,200)}`:""}`)}let a=(await n.json()).data[0];if(!a)throw new Error("[Directive] OpenAI embedding response contained no data entries");return a.embedding}}function v(g$1){let{apiKey:s,model:h$1="gpt-4o",maxTokens:m,baseURL:r="https://api.openai.com/v1",fetch:b$1=globalThis.fetch,hooks:i,temperature:c$1,topP:n,stop:l,responseFormat:a$1}=g$1;d(r),c(s,"createOpenAIStreamingRunner");let p=a$1==="json"?{type:"json_object"}:a$1??void 0;return async(o,t,u)=>{let d=e(i,o,t);try{let e=await b$1(`${r}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({model:o.model??h$1,...m!=null?{max_tokens:m}:{},...c$1!=null?{temperature:c$1}:{},...n!=null?{top_p:n}:{},...l!=null?{stop:l}:{},...p!=null?{response_format:p}:{},messages:[...o.instructions?[{role:"system",content:o.instructions}]:[],{role:"user",content:t}],stream:!0,stream_options:{include_usage:!0}}),signal:u.signal});e.ok||await a(e,"OpenAI");let f=b(e),{fullText:A,inputTokens:O,outputTokens:S}=await d$1(f,u.onToken,k=>{let y={},w=k.choices?.[0]?.delta;return w?.content&&(y.text=w.content),k.usage&&(y.inputTokens=k.usage.prompt_tokens??0,y.outputTokens=k.usage.completion_tokens??0),y},"OpenAI"),_={inputTokens:O,outputTokens:S},j=O+S;return u.onMessage?.({role:"assistant",content:A}),f$1(i,o,t,A,j,_,d),h(t,A,j,_)}catch(e){throw g(i,o,t,e,d),e}}}
|
|
2
2
|
export{L as OPENAI_PRICING,M as createOpenAIEmbedder,B as createOpenAIRunner,v as createOpenAIStreamingRunner};//# sourceMappingURL=openai.js.map
|
|
3
3
|
//# sourceMappingURL=openai.js.map
|
package/dist/openai.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/openai.ts"],"names":["OPENAI_PRICING","createOpenAIRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stop","responseFormat","validateBaseURL","warnIfMissingApiKey","resolvedResponseFormat","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createOpenAIEmbedder","dimensions","response","errBody","entry","createOpenAIStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","delta","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"sGAkDO,IAAMA,EACX,CACE,SAAA,CAAW,CAAE,KAAA,CAAO,CAAA,CAAG,OAAQ,CAAE,CAAA,CACjC,cAAA,CAAgB,CAAE,MAAO,EAAA,CAAK,MAAA,CAAQ,GAAI,CAAA,CAC1C,cAAA,CAAgB,CAAE,KAAA,CAAO,EAAA,CAAK,MAAA,CAAQ,EAAI,EAC1C,QAAA,CAAU,CAAE,MAAO,GAAA,CAAK,MAAA,CAAQ,EAAG,CAAA,CACnC,aAAA,CAAe,CAAE,KAAA,CAAO,IAAM,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,CACAD,CAAAA,CACAV,CACF,CAAA,CAEOa,EAAqBf,CAAAA,CAAOO,CAAAA,CAAUM,EAAaD,CAAU,CACtE,OAASI,CAAAA,CAAK,CACZ,MAAAC,CAAAA,CAAczC,CAAAA,CAAOS,EAAOe,CAAAA,CAAOgB,CAAAA,CAAKd,CAAS,CAAA,CAE3Cc,CACR,CACF,CACF","file":"openai.js","sourcesContent":["/**\n * @directive-run/ai/openai\n *\n * OpenAI adapter for Directive AI. Provides runners and embedders\n * for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * @example\n * ```typescript\n * import { createOpenAIRunner, createOpenAIEmbedder } from '@directive-run/ai/openai';\n *\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * ```\n */\n\nimport { createRunner, validateBaseURL } from \"../agent-utils.js\";\nimport type { EmbedderFn, Embedding } from \"../guardrails/semantic-cache.js\";\nimport type { AdapterHooks, AgentRunner } from \"../types.js\";\nimport type { StreamingCallbackRunner } from \"../types.js\";\nimport {\n buildStreamingResult,\n fireAfterCallHook,\n fireBeforeCallHook,\n fireErrorHook,\n getSSEReader,\n parseSSEStream,\n throwStreamingHTTPError,\n warnIfMissingApiKey,\n} from \"./shared.js\";\n\n// ============================================================================\n// Pricing Constants\n// ============================================================================\n\n/**\n * OpenAI model pricing (USD per million tokens).\n *\n * Use with `estimateCost()` for per-call cost tracking:\n * ```typescript\n * import { estimateCost } from '@directive-run/ai';\n * import { OPENAI_PRICING } from '@directive-run/ai/openai';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, OPENAI_PRICING[\"gpt-4o\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, OPENAI_PRICING[\"gpt-4o\"].output);\n * ```\n *\n * **Note:** Pricing changes over time. These values are provided as a convenience\n * and may not reflect the latest rates. Always verify at https://openai.com/pricing\n */\nexport const OPENAI_PRICING: Record<string, { input: number; output: number }> =\n {\n \"gpt-4.1\": { input: 2, output: 8 },\n \"gpt-4.1-mini\": { input: 0.4, output: 1.6 },\n \"gpt-4.1-nano\": { input: 0.1, output: 0.4 },\n \"gpt-4o\": { input: 2.5, output: 10 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6 },\n \"gpt-4-turbo\": { input: 10, output: 30 },\n \"o4-mini\": { input: 1.1, output: 4.4 },\n o3: { input: 10, output: 40 },\n \"o3-mini\": { input: 1.1, output: 4.4 },\n };\n\n// ============================================================================\n// OpenAI Runner\n// ============================================================================\n\n/** Options for createOpenAIRunner */\nexport interface OpenAIRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default undefined */\n timeoutMs?: number;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create an AgentRunner for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * // OpenAI\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n *\n * // Azure OpenAI\n * const azure = createOpenAIRunner({\n * apiKey: process.env.AZURE_KEY!,\n * baseURL: \"https://your-resource.openai.azure.com/v1\",\n * });\n *\n * // Together.ai (OpenAI-compatible)\n * const together = createOpenAIRunner({\n * apiKey: process.env.TOGETHER_KEY!,\n * baseURL: \"https://api.together.xyz/v1\",\n * });\n * ```\n */\nexport function createOpenAIRunner(options: OpenAIRunnerOptions): AgentRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/chat/completions`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n ...messages.map((m) => ({ role: m.role, content: m.content })),\n ],\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n }),\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.choices?.[0]?.message?.content ?? \"\";\n const inputTokens = data.usage?.prompt_tokens ?? 0;\n const outputTokens = data.usage?.completion_tokens ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// OpenAI Embedder\n// ============================================================================\n\n/** Options for createOpenAIEmbedder */\nexport interface OpenAIEmbedderOptions {\n apiKey: string;\n model?: string;\n dimensions?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default 30000 */\n timeoutMs?: number;\n}\n\n/**\n * Create an EmbedderFn that calls the OpenAI embeddings API.\n *\n * @example\n * ```typescript\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedding = await embedder('How do constraints work?');\n * ```\n */\nexport function createOpenAIEmbedder(\n options: OpenAIEmbedderOptions,\n): EmbedderFn {\n const {\n apiKey,\n model = \"text-embedding-3-small\",\n dimensions = 1536,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIEmbedder\");\n\n return async (text: string): Promise<Embedding> => {\n const response = await fetchFn(`${baseURL}/embeddings`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ model, input: text, dimensions }),\n signal: AbortSignal.timeout(timeoutMs ?? 30_000),\n });\n\n if (!response.ok) {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] OpenAI embedding failed: ${response.status}${errBody ? ` – ${errBody.slice(0, 200)}` : \"\"}`,\n );\n }\n\n const data = (await response.json()) as {\n data: Array<{ embedding: number[] }>;\n };\n\n const entry = data.data[0];\n if (!entry) {\n throw new Error(\n \"[Directive] OpenAI embedding response contained no data entries\",\n );\n }\n\n return entry.embedding;\n };\n}\n\n// ============================================================================\n// OpenAI Streaming Runner\n// ============================================================================\n\n/** Options for createOpenAIStreamingRunner */\nexport interface OpenAIStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create a StreamingCallbackRunner for OpenAI-compatible chat completions\n * with server-sent events. Can be used standalone or paired with `createOpenAIRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createOpenAIStreamingRunner({\n * apiKey: process.env.OPENAI_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createOpenAIStreamingRunner(\n options: OpenAIStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIStreamingRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n { role: \"user\", content: input },\n ],\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"OpenAI\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n\n const delta = (event.choices as Array<Record<string, unknown>>)?.[0]\n ?.delta as Record<string, unknown> | undefined;\n if (delta?.content) {\n result.text = delta.content as string;\n }\n\n if (event.usage) {\n result.inputTokens =\n ((event.usage as Record<string, unknown>)\n .prompt_tokens as number) ?? 0;\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .completion_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"OpenAI\",\n );\n\n const tokenUsage = { inputTokens, outputTokens };\n const totalTokens = inputTokens + outputTokens;\n\n callbacks.onMessage?.({ role: \"assistant\", content: fullText });\n fireAfterCallHook(\n hooks,\n agent,\n input,\n fullText,\n totalTokens,\n tokenUsage,\n startTime,\n );\n\n return buildStreamingResult(input, fullText, totalTokens, tokenUsage);\n } catch (err) {\n fireErrorHook(hooks, agent, input, err, startTime);\n\n throw err;\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapters/openai.ts"],"names":["OPENAI_PRICING","createOpenAIRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stop","responseFormat","validateBaseURL","warnIfMissingApiKey","resolvedResponseFormat","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createOpenAIEmbedder","dimensions","response","errBody","entry","createOpenAIStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","delta","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"sGAkDO,IAAMA,EACX,CACE,SAAA,CAAW,CAAE,KAAA,CAAO,CAAA,CAAG,OAAQ,CAAE,CAAA,CACjC,cAAA,CAAgB,CAAE,MAAO,EAAA,CAAK,MAAA,CAAQ,GAAI,CAAA,CAC1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,CAAAA,CAElC,OAAAQ,CAAAA,CAAU,SAAA,GAAY,CAAE,IAAA,CAAM,WAAA,CAAa,OAAA,CAASM,CAAS,CAAC,CAAA,CAC9DO,GAAAA,CACEtC,EACAS,CAAAA,CACAe,CAAAA,CACAO,EACAM,CAAAA,CACAD,CAAAA,CACAV,CACF,CAAA,CAEOa,EAAqBf,CAAAA,CAAOO,CAAAA,CAAUM,EAAaD,CAAU,CACtE,OAASI,CAAAA,CAAK,CACZ,MAAAC,CAAAA,CAAczC,CAAAA,CAAOS,EAAOe,CAAAA,CAAOgB,CAAAA,CAAKd,CAAS,CAAA,CAE3Cc,CACR,CACF,CACF","file":"openai.js","sourcesContent":["/**\n * @directive-run/ai/openai\n *\n * OpenAI adapter for Directive AI. Provides runners and embedders\n * for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * @example\n * ```typescript\n * import { createOpenAIRunner, createOpenAIEmbedder } from '@directive-run/ai/openai';\n *\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * ```\n */\n\nimport { createRunner, validateBaseURL } from \"../agent-utils.js\";\nimport type { EmbedderFn, Embedding } from \"../guardrails/semantic-cache.js\";\nimport type { AdapterHooks, AgentRunner } from \"../types.js\";\nimport type { StreamingCallbackRunner } from \"../types.js\";\nimport {\n buildStreamingResult,\n fireAfterCallHook,\n fireBeforeCallHook,\n fireErrorHook,\n getSSEReader,\n parseSSEStream,\n throwStreamingHTTPError,\n warnIfMissingApiKey,\n} from \"./shared.js\";\n\n// ============================================================================\n// Pricing Constants\n// ============================================================================\n\n/**\n * OpenAI model pricing (USD per million tokens).\n *\n * Use with `estimateCost()` for per-call cost tracking:\n * ```typescript\n * import { estimateCost } from '@directive-run/ai';\n * import { OPENAI_PRICING } from '@directive-run/ai/openai';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, OPENAI_PRICING[\"gpt-4o\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, OPENAI_PRICING[\"gpt-4o\"].output);\n * ```\n *\n * **Note:** Pricing changes over time. These values are provided as a convenience\n * and may not reflect the latest rates. Always verify at https://openai.com/pricing\n */\nexport const OPENAI_PRICING: Record<string, { input: number; output: number }> =\n {\n \"gpt-4.1\": { input: 2, output: 8 },\n \"gpt-4.1-mini\": { input: 0.4, output: 1.6 },\n \"gpt-4.1-nano\": { input: 0.1, output: 0.4 },\n \"gpt-4o\": { input: 2.5, output: 10 },\n \"gpt-4o-mini\": { input: 0.15, output: 0.6 },\n \"gpt-4-turbo\": { input: 10, output: 30 },\n \"o4-mini\": { input: 1.1, output: 4.4 },\n o3: { input: 10, output: 40 },\n \"o3-mini\": { input: 1.1, output: 4.4 },\n };\n\n// ============================================================================\n// OpenAI Runner\n// ============================================================================\n\n/** Options for createOpenAIRunner */\nexport interface OpenAIRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default undefined */\n timeoutMs?: number;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create an AgentRunner for OpenAI-compatible APIs (OpenAI, Azure, Together, etc.)\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * // OpenAI\n * const runner = createOpenAIRunner({ apiKey: process.env.OPENAI_API_KEY! });\n *\n * // Azure OpenAI\n * const azure = createOpenAIRunner({\n * apiKey: process.env.AZURE_KEY!,\n * baseURL: \"https://your-resource.openai.azure.com/v1\",\n * });\n *\n * // Together.ai (OpenAI-compatible)\n * const together = createOpenAIRunner({\n * apiKey: process.env.TOGETHER_KEY!,\n * baseURL: \"https://api.together.xyz/v1\",\n * });\n * ```\n */\nexport function createOpenAIRunner(options: OpenAIRunnerOptions): AgentRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/chat/completions`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n ...messages.map((m) => ({ role: m.role, content: m.content })),\n ],\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n }),\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.choices?.[0]?.message?.content ?? \"\";\n const inputTokens = data.usage?.prompt_tokens ?? 0;\n const outputTokens = data.usage?.completion_tokens ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// OpenAI Embedder\n// ============================================================================\n\n/** Options for createOpenAIEmbedder */\nexport interface OpenAIEmbedderOptions {\n apiKey: string;\n model?: string;\n dimensions?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default 30000 */\n timeoutMs?: number;\n}\n\n/**\n * Create an EmbedderFn that calls the OpenAI embeddings API.\n *\n * @example\n * ```typescript\n * const embedder = createOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY! });\n * const embedding = await embedder('How do constraints work?');\n * ```\n */\nexport function createOpenAIEmbedder(\n options: OpenAIEmbedderOptions,\n): EmbedderFn {\n const {\n apiKey,\n model = \"text-embedding-3-small\",\n dimensions = 1536,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIEmbedder\");\n\n return async (text: string): Promise<Embedding> => {\n const response = await fetchFn(`${baseURL}/embeddings`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ model, input: text, dimensions }),\n signal: AbortSignal.timeout(timeoutMs ?? 30_000),\n });\n\n if (!response.ok) {\n const errBody = await response.text().catch(() => \"\");\n\n throw new Error(\n `[Directive] OpenAI embedding failed: ${response.status}${errBody ? ` – ${errBody.slice(0, 200)}` : \"\"}`,\n );\n }\n\n const data = (await response.json()) as {\n data: Array<{ embedding: number[] }>;\n };\n\n const entry = data.data[0];\n if (!entry) {\n throw new Error(\n \"[Directive] OpenAI embedding response contained no data entries\",\n );\n }\n\n return entry.embedding;\n };\n}\n\n// ============================================================================\n// OpenAI Streaming Runner\n// ============================================================================\n\n/** Options for createOpenAIStreamingRunner */\nexport interface OpenAIStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–2). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Up to 4 sequences where the API will stop generating. */\n stop?: string | string[];\n /**\n * Response format for structured output.\n * - `\"json\"` enables JSON mode (`{ type: \"json_object\" }`)\n * - Object form enables JSON Schema mode (`{ type: \"json_schema\", json_schema: ... }`)\n */\n responseFormat?: \"json\" | { type: \"json_schema\"; json_schema: unknown };\n}\n\n/**\n * Create a StreamingCallbackRunner for OpenAI-compatible chat completions\n * with server-sent events. Can be used standalone or paired with `createOpenAIRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createOpenAIStreamingRunner({\n * apiKey: process.env.OPENAI_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createOpenAIStreamingRunner(\n options: OpenAIStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"gpt-4o\",\n maxTokens,\n baseURL = \"https://api.openai.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stop,\n responseFormat,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createOpenAIStreamingRunner\");\n\n const resolvedResponseFormat =\n responseFormat === \"json\"\n ? { type: \"json_object\" as const }\n : (responseFormat ?? undefined);\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n ...(maxTokens != null ? { max_tokens: maxTokens } : {}),\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stop != null ? { stop } : {}),\n ...(resolvedResponseFormat != null\n ? { response_format: resolvedResponseFormat }\n : {}),\n messages: [\n ...(agent.instructions\n ? [{ role: \"system\", content: agent.instructions }]\n : []),\n { role: \"user\", content: input },\n ],\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"OpenAI\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n\n const delta = (event.choices as Record<string, unknown>[])?.[0]\n ?.delta as Record<string, unknown> | undefined;\n if (delta?.content) {\n result.text = delta.content as string;\n }\n\n if (event.usage) {\n result.inputTokens =\n ((event.usage as Record<string, unknown>)\n .prompt_tokens as number) ?? 0;\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .completion_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"OpenAI\",\n );\n\n const tokenUsage = { inputTokens, outputTokens };\n const totalTokens = inputTokens + outputTokens;\n\n callbacks.onMessage?.({ role: \"assistant\", content: fullText });\n fireAfterCallHook(\n hooks,\n agent,\n input,\n fullText,\n totalTokens,\n tokenUsage,\n startTime,\n );\n\n return buildStreamingResult(input, fullText, totalTokens, tokenUsage);\n } catch (err) {\n fireErrorHook(hooks, agent, input, err, startTime);\n\n throw err;\n }\n };\n}\n"]}
|
|
@@ -1250,7 +1250,7 @@ interface RaceSuccessEntry<T = unknown> {
|
|
|
1250
1250
|
interface RaceResult<T = unknown> {
|
|
1251
1251
|
winnerId: string;
|
|
1252
1252
|
result: T;
|
|
1253
|
-
allResults?:
|
|
1253
|
+
allResults?: RaceSuccessEntry<T>[];
|
|
1254
1254
|
}
|
|
1255
1255
|
/**
|
|
1256
1256
|
* Debate pattern - agents compete, evaluator judges across rounds.
|
|
@@ -1250,7 +1250,7 @@ interface RaceSuccessEntry<T = unknown> {
|
|
|
1250
1250
|
interface RaceResult<T = unknown> {
|
|
1251
1251
|
winnerId: string;
|
|
1252
1252
|
result: T;
|
|
1253
|
-
allResults?:
|
|
1253
|
+
allResults?: RaceSuccessEntry<T>[];
|
|
1254
1254
|
}
|
|
1255
1255
|
/**
|
|
1256
1256
|
* Debate pattern - agents compete, evaluator judges across rounds.
|
package/dist/predicate.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkMDXDPECP_cjs=require('./chunk-MDXDPECP.cjs');require('./chunk-WCQK3JOR.cjs');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}});//# sourceMappingURL=predicate.cjs.map
|
|
2
2
|
//# sourceMappingURL=predicate.cjs.map
|
package/dist/predicate.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as PredicateFromIntentError,b as predicateFromIntent,c as predicateFromIntentRaw,g as predicateFromIntentWithProvenance,f as predicateToolSpec,e as predicateToolSpecAnthropic,d as predicateToolSpecOpenAI}from'./chunk-
|
|
1
|
+
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';import'./chunk-HRR45JZX.js';//# sourceMappingURL=predicate.js.map
|
|
2
2
|
//# sourceMappingURL=predicate.js.map
|
package/dist/testing.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunk2TD4ZSGZ_cjs=require('./chunk-2TD4ZSGZ.cjs'),chunkA22KLB23_cjs=require('./chunk-A22KLB23.cjs');require('./chunk-K64WKZ22.cjs');var chunkWOFIBIPW_cjs=require('./chunk-WOFIBIPW.cjs');require('./chunk-FFRWQNK7.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=chunk2TD4ZSGZ_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=chunkA22KLB23_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 chunkA22KLB23_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 chunkA22KLB23_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 chunkD5APTMCT_cjs=require('./chunk-D5APTMCT.cjs'),chunk7DPTXZZI_cjs=require('./chunk-7DPTXZZI.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=chunkD5APTMCT_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=chunk7DPTXZZI_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 chunk7DPTXZZI_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 chunk7DPTXZZI_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
|
package/dist/testing.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as MultiAgentOrchestrator, a as MultiAgentOrchestratorOptions, A as AgentOrchestrator, O as OrchestratorOptions, b as MultiplexedStreamChunk, T as TaskRegistration, R as ReflectionEvaluator } from './orchestrator-types-
|
|
1
|
+
import { M as MultiAgentOrchestrator, a as MultiAgentOrchestratorOptions, A as AgentOrchestrator, O as OrchestratorOptions, b as MultiplexedStreamChunk, T as TaskRegistration, R as ReflectionEvaluator } from './orchestrator-types-CbNE7Rjp.cjs';
|
|
2
2
|
import { A as ApprovalRequest, B as BreakpointModifications, I as InputGuardrailData, O as OutputGuardrailData, M as Message, T as ToolCallGuardrailData, a as ToolCall, G as GuardrailResult, b as AgentLike, c as AgentRunner, R as RunOptions, d as BreakpointRequest, C as Checkpoint, D as DagExecutionContext, e as DagNodeStatus, f as RerouteEvent, S as Scratchpad, g as DebugEventType, h as CheckpointStore, i as InMemoryCheckpointStore, j as DagNode, k as DagPattern, l as DebugEvent, m as GuardrailFn, n as GuardrailContext } from './types-DJ09LjZX.cjs';
|
|
3
3
|
import { D as DebugTimeline } from './debug-timeline-DpnRMnLU.cjs';
|
|
4
4
|
import { H as HealthMonitor } from './health-monitor-C6xoXrQz.cjs';
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as MultiAgentOrchestrator, a as MultiAgentOrchestratorOptions, A as AgentOrchestrator, O as OrchestratorOptions, b as MultiplexedStreamChunk, T as TaskRegistration, R as ReflectionEvaluator } from './orchestrator-types-
|
|
1
|
+
import { M as MultiAgentOrchestrator, a as MultiAgentOrchestratorOptions, A as AgentOrchestrator, O as OrchestratorOptions, b as MultiplexedStreamChunk, T as TaskRegistration, R as ReflectionEvaluator } from './orchestrator-types-ZK9lv5Sm.js';
|
|
2
2
|
import { A as ApprovalRequest, B as BreakpointModifications, I as InputGuardrailData, O as OutputGuardrailData, M as Message, T as ToolCallGuardrailData, a as ToolCall, G as GuardrailResult, b as AgentLike, c as AgentRunner, R as RunOptions, d as BreakpointRequest, C as Checkpoint, D as DagExecutionContext, e as DagNodeStatus, f as RerouteEvent, S as Scratchpad, g as DebugEventType, h as CheckpointStore, i as InMemoryCheckpointStore, j as DagNode, k as DagPattern, l as DebugEvent, m as GuardrailFn, n as GuardrailContext } from './types-DJ09LjZX.js';
|
|
3
3
|
import { D as DebugTimeline } from './debug-timeline-L13P-U2I.js';
|
|
4
4
|
import { H as HealthMonitor } from './health-monitor-qL9RNMH3.js';
|